HTTP2ServerTransport+Posix.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. 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. private import Synchronization
  23. #if canImport(NIOSSL)
  24. import NIOSSL
  25. #endif
  26. extension HTTP2ServerTransport {
  27. /// A ``GRPCCore/ServerTransport`` using HTTP/2 built on top of `NIOPosix`.
  28. ///
  29. /// This transport builds on top of SwiftNIO's Posix networking layer and is suitable for use
  30. /// on Linux and Darwin based platform (macOS, iOS, etc.) However, it's *strongly* recommended
  31. /// that if you are targeting Darwin platforms then you should use the `NIOTS` variant of
  32. /// the ``GRPCHTTP2Core/HTTP2ServerTransport``.
  33. ///
  34. /// You can control various aspects of connection creation, management, security and RPC behavior via
  35. /// the ``Config``.
  36. ///
  37. /// Beyond creating the transport you don't need to interact with it directly, instead, pass it
  38. /// to a `GRPCServer`:
  39. ///
  40. /// ```swift
  41. /// try await withThrowingDiscardingTaskGroup { group in
  42. /// let transport = HTTP2ServerTransport.Posix(
  43. /// address: .ipv4(host: "127.0.0.1", port: 0),
  44. /// config: .defaults(transportSecurity: .plaintext)
  45. /// )
  46. /// let server = GRPCServer(transport: transport, services: someServices)
  47. /// group.addTask {
  48. /// try await server.serve()
  49. /// }
  50. ///
  51. /// // ...
  52. /// }
  53. /// ```
  54. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  55. public final class Posix: ServerTransport, ListeningServerTransport {
  56. private let address: GRPCHTTP2Core.SocketAddress
  57. private let config: Config
  58. private let eventLoopGroup: MultiThreadedEventLoopGroup
  59. private let serverQuiescingHelper: ServerQuiescingHelper
  60. private enum State {
  61. case idle(EventLoopPromise<GRPCHTTP2Core.SocketAddress>)
  62. case listening(EventLoopFuture<GRPCHTTP2Core.SocketAddress>)
  63. case closedOrInvalidAddress(RuntimeError)
  64. var listeningAddressFuture: EventLoopFuture<GRPCHTTP2Core.SocketAddress> {
  65. get throws {
  66. switch self {
  67. case .idle(let eventLoopPromise):
  68. return eventLoopPromise.futureResult
  69. case .listening(let eventLoopFuture):
  70. return eventLoopFuture
  71. case .closedOrInvalidAddress(let runtimeError):
  72. throw runtimeError
  73. }
  74. }
  75. }
  76. enum OnBound {
  77. case succeedPromise(
  78. _ promise: EventLoopPromise<GRPCHTTP2Core.SocketAddress>,
  79. address: GRPCHTTP2Core.SocketAddress
  80. )
  81. case failPromise(
  82. _ promise: EventLoopPromise<GRPCHTTP2Core.SocketAddress>,
  83. error: RuntimeError
  84. )
  85. }
  86. mutating func addressBound(
  87. _ address: NIOCore.SocketAddress?,
  88. userProvidedAddress: GRPCHTTP2Core.SocketAddress
  89. ) -> OnBound {
  90. switch self {
  91. case .idle(let listeningAddressPromise):
  92. if let address {
  93. self = .listening(listeningAddressPromise.futureResult)
  94. return .succeedPromise(
  95. listeningAddressPromise,
  96. address: GRPCHTTP2Core.SocketAddress(address)
  97. )
  98. } else if userProvidedAddress.virtualSocket != nil {
  99. self = .listening(listeningAddressPromise.futureResult)
  100. return .succeedPromise(listeningAddressPromise, address: userProvidedAddress)
  101. } else {
  102. assertionFailure("Unknown address type")
  103. let invalidAddressError = RuntimeError(
  104. code: .transportError,
  105. message: "Unknown address type returned by transport."
  106. )
  107. self = .closedOrInvalidAddress(invalidAddressError)
  108. return .failPromise(listeningAddressPromise, error: invalidAddressError)
  109. }
  110. case .listening, .closedOrInvalidAddress:
  111. fatalError(
  112. "Invalid state: addressBound should only be called once and when in idle state"
  113. )
  114. }
  115. }
  116. enum OnClose {
  117. case failPromise(
  118. EventLoopPromise<GRPCHTTP2Core.SocketAddress>,
  119. error: RuntimeError
  120. )
  121. case doNothing
  122. }
  123. mutating func close() -> OnClose {
  124. let serverStoppedError = RuntimeError(
  125. code: .serverIsStopped,
  126. message: """
  127. There is no listening address bound for this server: there may have been \
  128. an error which caused the transport to close, or it may have shut down.
  129. """
  130. )
  131. switch self {
  132. case .idle(let listeningAddressPromise):
  133. self = .closedOrInvalidAddress(serverStoppedError)
  134. return .failPromise(listeningAddressPromise, error: serverStoppedError)
  135. case .listening:
  136. self = .closedOrInvalidAddress(serverStoppedError)
  137. return .doNothing
  138. case .closedOrInvalidAddress:
  139. return .doNothing
  140. }
  141. }
  142. }
  143. private let listeningAddressState: Mutex<State>
  144. /// The listening address for this server transport.
  145. ///
  146. /// It is an `async` property because it will only return once the address has been successfully bound.
  147. ///
  148. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  149. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  150. /// invalid address.
  151. public var listeningAddress: GRPCHTTP2Core.SocketAddress {
  152. get async throws {
  153. try await self.listeningAddressState
  154. .withLock { try $0.listeningAddressFuture }
  155. .get()
  156. }
  157. }
  158. /// Create a new `Posix` transport.
  159. ///
  160. /// - Parameters:
  161. /// - address: The address to which the server should be bound.
  162. /// - config: The transport configuration.
  163. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  164. public init(
  165. address: GRPCHTTP2Core.SocketAddress,
  166. config: Config,
  167. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  168. ) {
  169. self.address = address
  170. self.config = config
  171. self.eventLoopGroup = eventLoopGroup
  172. self.serverQuiescingHelper = ServerQuiescingHelper(group: self.eventLoopGroup)
  173. let eventLoop = eventLoopGroup.any()
  174. self.listeningAddressState = Mutex(.idle(eventLoop.makePromise()))
  175. }
  176. public func listen(
  177. _ streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void
  178. ) async throws {
  179. defer {
  180. switch self.listeningAddressState.withLock({ $0.close() }) {
  181. case .failPromise(let promise, let error):
  182. promise.fail(error)
  183. case .doNothing:
  184. ()
  185. }
  186. }
  187. #if canImport(NIOSSL)
  188. let nioSSLContext: NIOSSLContext?
  189. switch self.config.transportSecurity.wrapped {
  190. case .plaintext:
  191. nioSSLContext = nil
  192. case .tls(let tlsConfig):
  193. do {
  194. nioSSLContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  195. } catch {
  196. throw RuntimeError(
  197. code: .transportError,
  198. message: "Couldn't create SSL context, check your TLS configuration.",
  199. cause: error
  200. )
  201. }
  202. }
  203. #endif
  204. let serverChannel = try await ServerBootstrap(group: self.eventLoopGroup)
  205. .serverChannelOption(
  206. ChannelOptions.socketOption(.so_reuseaddr),
  207. value: 1
  208. )
  209. .serverChannelInitializer { channel in
  210. let quiescingHandler = self.serverQuiescingHelper.makeServerChannelHandler(
  211. channel: channel
  212. )
  213. return channel.pipeline.addHandler(quiescingHandler)
  214. }
  215. .bind(to: self.address) { channel in
  216. channel.eventLoop.makeCompletedFuture {
  217. #if canImport(NIOSSL)
  218. if let nioSSLContext {
  219. try channel.pipeline.syncOperations.addHandler(
  220. NIOSSLServerHandler(context: nioSSLContext)
  221. )
  222. }
  223. #endif
  224. let requireALPN: Bool
  225. let scheme: Scheme
  226. switch self.config.transportSecurity.wrapped {
  227. case .plaintext:
  228. requireALPN = false
  229. scheme = .http
  230. case .tls(let tlsConfig):
  231. requireALPN = tlsConfig.requireALPN
  232. scheme = .https
  233. }
  234. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  235. channel: channel,
  236. compressionConfig: self.config.compression,
  237. connectionConfig: self.config.connection,
  238. http2Config: self.config.http2,
  239. rpcConfig: self.config.rpc,
  240. requireALPN: requireALPN,
  241. scheme: scheme
  242. )
  243. }
  244. }
  245. let action = self.listeningAddressState.withLock {
  246. $0.addressBound(
  247. serverChannel.channel.localAddress,
  248. userProvidedAddress: self.address
  249. )
  250. }
  251. switch action {
  252. case .succeedPromise(let promise, let address):
  253. promise.succeed(address)
  254. case .failPromise(let promise, let error):
  255. promise.fail(error)
  256. }
  257. try await serverChannel.executeThenClose { inbound in
  258. try await withThrowingDiscardingTaskGroup { group in
  259. for try await (connectionChannel, streamMultiplexer) in inbound {
  260. group.addTask {
  261. try await self.handleConnection(
  262. connectionChannel,
  263. multiplexer: streamMultiplexer,
  264. streamHandler: streamHandler
  265. )
  266. }
  267. }
  268. }
  269. }
  270. }
  271. private func handleConnection(
  272. _ connection: NIOAsyncChannel<HTTP2Frame, HTTP2Frame>,
  273. multiplexer: ChannelPipeline.SynchronousOperations.HTTP2StreamMultiplexer,
  274. streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void
  275. ) async throws {
  276. try await connection.executeThenClose { inbound, _ in
  277. await withDiscardingTaskGroup { group in
  278. group.addTask {
  279. do {
  280. for try await _ in inbound {}
  281. } catch {
  282. // We don't want to close the channel if one connection throws.
  283. return
  284. }
  285. }
  286. do {
  287. for try await (stream, descriptor) in multiplexer.inbound {
  288. group.addTask {
  289. await self.handleStream(stream, handler: streamHandler, descriptor: descriptor)
  290. }
  291. }
  292. } catch {
  293. return
  294. }
  295. }
  296. }
  297. }
  298. private func handleStream(
  299. _ stream: NIOAsyncChannel<RPCRequestPart, RPCResponsePart>,
  300. handler streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void,
  301. descriptor: EventLoopFuture<MethodDescriptor>
  302. ) async {
  303. // It's okay to ignore these errors:
  304. // - If we get an error because the http2Stream failed to close, then there's nothing we can do
  305. // - If we get an error because the inner closure threw, then the only possible scenario in which
  306. // that could happen is if methodDescriptor.get() throws - in which case, it means we never got
  307. // the RPC metadata, which means we can't do anything either and it's okay to just kill the stream.
  308. try? await stream.executeThenClose { inbound, outbound in
  309. guard let descriptor = try? await descriptor.get() else {
  310. return
  311. }
  312. let rpcStream = RPCStream(
  313. descriptor: descriptor,
  314. inbound: RPCAsyncSequence(wrapping: inbound),
  315. outbound: RPCWriter.Closable(
  316. wrapping: ServerConnection.Stream.Outbound(
  317. responseWriter: outbound,
  318. http2Stream: stream
  319. )
  320. )
  321. )
  322. await streamHandler(rpcStream)
  323. }
  324. }
  325. public func beginGracefulShutdown() {
  326. self.serverQuiescingHelper.initiateShutdown(promise: nil)
  327. }
  328. }
  329. }
  330. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  331. extension HTTP2ServerTransport.Posix {
  332. /// Config for the `Posix` transport.
  333. public struct Config: Sendable {
  334. /// Compression configuration.
  335. public var compression: HTTP2ServerTransport.Config.Compression
  336. /// Connection configuration.
  337. public var connection: HTTP2ServerTransport.Config.Connection
  338. /// HTTP2 configuration.
  339. public var http2: HTTP2ServerTransport.Config.HTTP2
  340. /// RPC configuration.
  341. public var rpc: HTTP2ServerTransport.Config.RPC
  342. /// The transport's security.
  343. public var transportSecurity: TransportSecurity
  344. /// Construct a new `Config`.
  345. ///
  346. /// - Parameters:
  347. /// - http2: HTTP2 configuration.
  348. /// - rpc: RPC configuration.
  349. /// - connection: Connection configuration.
  350. /// - compression: Compression configuration.
  351. /// - transportSecurity: The transport's security configuration.
  352. ///
  353. /// - SeeAlso: ``defaults(transportSecurity:configure:)``
  354. public init(
  355. http2: HTTP2ServerTransport.Config.HTTP2,
  356. rpc: HTTP2ServerTransport.Config.RPC,
  357. connection: HTTP2ServerTransport.Config.Connection,
  358. compression: HTTP2ServerTransport.Config.Compression,
  359. transportSecurity: TransportSecurity
  360. ) {
  361. self.compression = compression
  362. self.connection = connection
  363. self.http2 = http2
  364. self.rpc = rpc
  365. self.transportSecurity = transportSecurity
  366. }
  367. /// Default values for the different configurations.
  368. ///
  369. /// - Parameters:
  370. /// - transportSecurity: The security settings applied to the transport.
  371. /// - configure: A closure which allows you to modify the defaults before returning them.
  372. public static func defaults(
  373. transportSecurity: TransportSecurity,
  374. configure: (_ config: inout Self) -> Void = { _ in }
  375. ) -> Self {
  376. var config = Self(
  377. http2: .defaults,
  378. rpc: .defaults,
  379. connection: .defaults,
  380. compression: .defaults,
  381. transportSecurity: transportSecurity
  382. )
  383. configure(&config)
  384. return config
  385. }
  386. }
  387. }
  388. extension ServerBootstrap {
  389. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  390. fileprivate func bind<Output: Sendable>(
  391. to address: GRPCHTTP2Core.SocketAddress,
  392. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  393. ) async throws -> NIOAsyncChannel<Output, Never> {
  394. if let virtualSocket = address.virtualSocket {
  395. return try await self.bind(
  396. to: VsockAddress(virtualSocket),
  397. childChannelInitializer: childChannelInitializer
  398. )
  399. } else {
  400. return try await self.bind(
  401. to: NIOCore.SocketAddress(address),
  402. childChannelInitializer: childChannelInitializer
  403. )
  404. }
  405. }
  406. }
  407. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  408. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  409. /// Create a new `Posix` based HTTP/2 server transport.
  410. ///
  411. /// - Parameters:
  412. /// - address: The address to which the server should be bound.
  413. /// - config: The transport configuration.
  414. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  415. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  416. /// a `MultiThreadedEventLoopGroup`.
  417. public static func http2NIOPosix(
  418. address: GRPCHTTP2Core.SocketAddress,
  419. config: HTTP2ServerTransport.Posix.Config,
  420. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  421. ) -> Self {
  422. return HTTP2ServerTransport.Posix(
  423. address: address,
  424. config: config,
  425. eventLoopGroup: eventLoopGroup
  426. )
  427. }
  428. }