HTTP2ServerTransport+Posix.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 struct Posix: ServerTransport, ListeningServerTransport {
  56. private struct ListenerFactory: HTTP2ListenerFactory {
  57. let config: Config
  58. func makeListeningChannel(
  59. eventLoopGroup: any EventLoopGroup,
  60. address: GRPCHTTP2Core.SocketAddress,
  61. serverQuiescingHelper: ServerQuiescingHelper
  62. ) async throws -> NIOAsyncChannel<AcceptedChannel, Never> {
  63. #if canImport(NIOSSL)
  64. let sslContext: NIOSSLContext?
  65. switch self.config.transportSecurity.wrapped {
  66. case .plaintext:
  67. sslContext = nil
  68. case .tls(let tlsConfig):
  69. do {
  70. sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  71. } catch {
  72. throw RuntimeError(
  73. code: .transportError,
  74. message: "Couldn't create SSL context, check your TLS configuration.",
  75. cause: error
  76. )
  77. }
  78. }
  79. #endif
  80. let serverChannel = try await ServerBootstrap(group: eventLoopGroup)
  81. .serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
  82. .serverChannelInitializer { channel in
  83. let quiescingHandler = serverQuiescingHelper.makeServerChannelHandler(channel: channel)
  84. return channel.pipeline.addHandler(quiescingHandler)
  85. }
  86. .bind(to: address) { channel in
  87. channel.eventLoop.makeCompletedFuture {
  88. #if canImport(NIOSSL)
  89. if let sslContext {
  90. try channel.pipeline.syncOperations.addHandler(
  91. NIOSSLServerHandler(context: sslContext)
  92. )
  93. }
  94. #endif
  95. let requireALPN: Bool
  96. let scheme: Scheme
  97. switch self.config.transportSecurity.wrapped {
  98. case .plaintext:
  99. requireALPN = false
  100. scheme = .http
  101. case .tls(let tlsConfig):
  102. requireALPN = tlsConfig.requireALPN
  103. scheme = .https
  104. }
  105. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  106. channel: channel,
  107. compressionConfig: self.config.compression,
  108. connectionConfig: self.config.connection,
  109. http2Config: self.config.http2,
  110. rpcConfig: self.config.rpc,
  111. requireALPN: requireALPN,
  112. scheme: scheme
  113. )
  114. }
  115. }
  116. return serverChannel
  117. }
  118. }
  119. private let underlyingTransport: CommonHTTP2ServerTransport<ListenerFactory>
  120. /// The listening address for this server transport.
  121. ///
  122. /// It is an `async` property because it will only return once the address has been successfully bound.
  123. ///
  124. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  125. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  126. /// invalid address.
  127. public var listeningAddress: GRPCHTTP2Core.SocketAddress {
  128. get async throws {
  129. try await self.underlyingTransport.listeningAddress
  130. }
  131. }
  132. /// Create a new `Posix` transport.
  133. ///
  134. /// - Parameters:
  135. /// - address: The address to which the server should be bound.
  136. /// - config: The transport configuration.
  137. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  138. public init(
  139. address: GRPCHTTP2Core.SocketAddress,
  140. config: Config,
  141. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  142. ) {
  143. let factory = ListenerFactory(config: config)
  144. let helper = ServerQuiescingHelper(group: eventLoopGroup)
  145. self.underlyingTransport = CommonHTTP2ServerTransport(
  146. address: address,
  147. eventLoopGroup: eventLoopGroup,
  148. quiescingHelper: helper,
  149. listenerFactory: factory
  150. )
  151. }
  152. public func listen(
  153. _ streamHandler: @escaping @Sendable (RPCStream<Inbound, Outbound>) async -> Void
  154. ) async throws {
  155. try await self.underlyingTransport.listen(streamHandler)
  156. }
  157. public func beginGracefulShutdown() {
  158. self.underlyingTransport.beginGracefulShutdown()
  159. }
  160. }
  161. }
  162. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  163. extension HTTP2ServerTransport.Posix {
  164. /// Config for the `Posix` transport.
  165. public struct Config: Sendable {
  166. /// Compression configuration.
  167. public var compression: HTTP2ServerTransport.Config.Compression
  168. /// Connection configuration.
  169. public var connection: HTTP2ServerTransport.Config.Connection
  170. /// HTTP2 configuration.
  171. public var http2: HTTP2ServerTransport.Config.HTTP2
  172. /// RPC configuration.
  173. public var rpc: HTTP2ServerTransport.Config.RPC
  174. /// The transport's security.
  175. public var transportSecurity: TransportSecurity
  176. /// Construct a new `Config`.
  177. ///
  178. /// - Parameters:
  179. /// - http2: HTTP2 configuration.
  180. /// - rpc: RPC configuration.
  181. /// - connection: Connection configuration.
  182. /// - compression: Compression configuration.
  183. /// - transportSecurity: The transport's security configuration.
  184. ///
  185. /// - SeeAlso: ``defaults(transportSecurity:configure:)``
  186. public init(
  187. http2: HTTP2ServerTransport.Config.HTTP2,
  188. rpc: HTTP2ServerTransport.Config.RPC,
  189. connection: HTTP2ServerTransport.Config.Connection,
  190. compression: HTTP2ServerTransport.Config.Compression,
  191. transportSecurity: TransportSecurity
  192. ) {
  193. self.compression = compression
  194. self.connection = connection
  195. self.http2 = http2
  196. self.rpc = rpc
  197. self.transportSecurity = transportSecurity
  198. }
  199. /// Default values for the different configurations.
  200. ///
  201. /// - Parameters:
  202. /// - transportSecurity: The security settings applied to the transport.
  203. /// - configure: A closure which allows you to modify the defaults before returning them.
  204. public static func defaults(
  205. transportSecurity: TransportSecurity,
  206. configure: (_ config: inout Self) -> Void = { _ in }
  207. ) -> Self {
  208. var config = Self(
  209. http2: .defaults,
  210. rpc: .defaults,
  211. connection: .defaults,
  212. compression: .defaults,
  213. transportSecurity: transportSecurity
  214. )
  215. configure(&config)
  216. return config
  217. }
  218. }
  219. }
  220. extension ServerBootstrap {
  221. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  222. fileprivate func bind<Output: Sendable>(
  223. to address: GRPCHTTP2Core.SocketAddress,
  224. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  225. ) async throws -> NIOAsyncChannel<Output, Never> {
  226. if let virtualSocket = address.virtualSocket {
  227. return try await self.bind(
  228. to: VsockAddress(virtualSocket),
  229. childChannelInitializer: childChannelInitializer
  230. )
  231. } else {
  232. return try await self.bind(
  233. to: NIOCore.SocketAddress(address),
  234. childChannelInitializer: childChannelInitializer
  235. )
  236. }
  237. }
  238. }
  239. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  240. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  241. /// Create a new `Posix` based HTTP/2 server transport.
  242. ///
  243. /// - Parameters:
  244. /// - address: The address to which the server should be bound.
  245. /// - config: The transport configuration.
  246. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  247. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  248. /// a `MultiThreadedEventLoopGroup`.
  249. public static func http2NIOPosix(
  250. address: GRPCHTTP2Core.SocketAddress,
  251. config: HTTP2ServerTransport.Posix.Config,
  252. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  253. ) -> Self {
  254. return HTTP2ServerTransport.Posix(
  255. address: address,
  256. config: config,
  257. eventLoopGroup: eventLoopGroup
  258. )
  259. }
  260. }