Server.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import Logging
  18. import NIOCore
  19. import NIOExtras
  20. import NIOHTTP1
  21. import NIOHTTP2
  22. import NIOPosix
  23. import NIOTransportServices
  24. #if canImport(NIOSSL)
  25. import NIOSSL
  26. #endif
  27. #if canImport(Network)
  28. import Network
  29. #endif
  30. /// Wrapper object to manage the lifecycle of a gRPC server.
  31. ///
  32. /// The pipeline is configured in three stages detailed below. Note: handlers marked with
  33. /// a '*' are responsible for handling errors.
  34. ///
  35. /// 1. Initial stage, prior to pipeline configuration.
  36. ///
  37. /// ┌─────────────────────────────────┐
  38. /// │ GRPCServerPipelineConfigurator* │
  39. /// └────▲───────────────────────┬────┘
  40. /// ByteBuffer│ │ByteBuffer
  41. /// ┌─┴───────────────────────▼─┐
  42. /// │ NIOSSLHandler │
  43. /// └─▲───────────────────────┬─┘
  44. /// ByteBuffer│ │ByteBuffer
  45. /// │ ▼
  46. ///
  47. /// The `NIOSSLHandler` is optional and depends on how the framework user has configured
  48. /// their server. The `GRPCServerPipelineConfigurator` detects which HTTP version is being used
  49. /// (via ALPN if TLS is used or by parsing the first bytes on the connection otherwise) and
  50. /// configures the pipeline accordingly.
  51. ///
  52. /// 2. HTTP version detected. "HTTP Handlers" depends on the HTTP version determined by
  53. /// `GRPCServerPipelineConfigurator`. In the case of HTTP/2:
  54. ///
  55. /// ┌─────────────────────────────────┐
  56. /// │ HTTP2StreamMultiplexer │
  57. /// └─▲─────────────────────────────┬─┘
  58. /// HTTP2Frame│ │HTTP2Frame
  59. /// ┌─┴─────────────────────────────▼─┐
  60. /// │ HTTP2Handler │
  61. /// └─▲─────────────────────────────┬─┘
  62. /// ByteBuffer│ │ByteBuffer
  63. /// ┌─┴─────────────────────────────▼─┐
  64. /// │ NIOSSLHandler │
  65. /// └─▲─────────────────────────────┬─┘
  66. /// ByteBuffer│ │ByteBuffer
  67. /// │ ▼
  68. ///
  69. /// The `HTTP2StreamMultiplexer` provides one `Channel` for each HTTP/2 stream (and thus each
  70. /// RPC).
  71. ///
  72. /// 3. The frames for each stream channel are routed by the `HTTP2ToRawGRPCServerCodec` handler to
  73. /// a handler containing the user-implemented logic provided by a `CallHandlerProvider`:
  74. ///
  75. /// ┌─────────────────────────────────┐
  76. /// │ BaseCallHandler* │
  77. /// └─▲─────────────────────────────┬─┘
  78. /// GRPCServerRequestPart│ │GRPCServerResponsePart
  79. /// ┌─┴─────────────────────────────▼─┐
  80. /// │ HTTP2ToRawGRPCServerCodec │
  81. /// └─▲─────────────────────────────┬─┘
  82. /// HTTP2Frame.FramePayload│ │HTTP2Frame.FramePayload
  83. /// │ ▼
  84. ///
  85. /// - Note: This class is thread safe. It's marked as `@unchecked Sendable` because the non-Sendable
  86. /// `errorDelegate` property is mutated, but it's done thread-safely, as it only happens inside the `EventLoop`.
  87. public final class Server: @unchecked Sendable {
  88. /// Makes and configures a `ServerBootstrap` using the provided configuration.
  89. public class func makeBootstrap(configuration: Configuration) -> ServerBootstrapProtocol {
  90. let bootstrap = PlatformSupport.makeServerBootstrap(group: configuration.eventLoopGroup)
  91. // Backlog is only available on `ServerBootstrap`.
  92. if bootstrap is ServerBootstrap {
  93. // Specify a backlog to avoid overloading the server.
  94. _ = bootstrap.serverChannelOption(ChannelOptions.backlog, value: 256)
  95. }
  96. #if canImport(NIOSSL)
  97. let sslContext = Self.makeNIOSSLContext(configuration: configuration)
  98. #endif // canImport(NIOSSL)
  99. #if canImport(Network)
  100. if let tlsConfiguration = configuration.tlsConfiguration {
  101. if #available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  102. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  103. {
  104. _ = transportServicesBootstrap.tlsOptions(from: tlsConfiguration)
  105. }
  106. }
  107. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
  108. let configurator = configuration.listenerNWParametersConfigurator,
  109. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  110. {
  111. _ = transportServicesBootstrap.configureNWParameters(configurator)
  112. }
  113. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
  114. let configurator = configuration.childChannelNWParametersConfigurator,
  115. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  116. {
  117. _ = transportServicesBootstrap.configureChildNWParameters(configurator)
  118. }
  119. #endif // canImport(Network)
  120. return
  121. bootstrap
  122. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  123. .serverChannelOption(
  124. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  125. value: 1
  126. )
  127. // Set the handlers that are applied to the accepted Channels
  128. .childChannelInitializer { channel in
  129. Self.configureAcceptedChannel(channel, configuration: configuration) { sync in
  130. #if canImport(NIOSSL)
  131. try Self.addNIOSSLHandler(sslContext, configuration: configuration, sync: sync)
  132. #endif // canImport(NIOSSL)
  133. }
  134. }
  135. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  136. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  137. .childChannelOption(
  138. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  139. value: 1
  140. )
  141. }
  142. #if canImport(NIOSSL)
  143. private static func makeNIOSSLContext(
  144. configuration: Configuration
  145. ) -> Result<NIOSSLContext, Error>? {
  146. // Making a `NIOSSLContext` is expensive, we should only do it once per TLS configuration so
  147. // we'll do it now, before accepting connections. Unfortunately our API isn't throwing so we'll
  148. // only surface any error when initializing a child channel.
  149. //
  150. // 'nil' means we're not using TLS, or we're using the Network.framework TLS backend. If we're
  151. // using the Network.framework TLS backend we'll apply the settings just below.
  152. let sslContext: Result<NIOSSLContext, Error>?
  153. if let tlsConfiguration = configuration.tlsConfiguration {
  154. do {
  155. sslContext = try tlsConfiguration.makeNIOSSLContext().map { .success($0) }
  156. } catch {
  157. sslContext = .failure(error)
  158. }
  159. } else {
  160. // No TLS configuration, no SSL context.
  161. sslContext = nil
  162. }
  163. return sslContext
  164. }
  165. private static func addNIOSSLHandler(
  166. _ sslContext: Result<NIOSSLContext, Error>?,
  167. configuration: Configuration,
  168. sync: ChannelPipeline.SynchronousOperations
  169. ) throws {
  170. if let sslContext = try sslContext?.get() {
  171. let sslHandler: NIOSSLServerHandler
  172. if let verify = configuration.tlsConfiguration?.nioSSLCustomVerificationCallback {
  173. sslHandler = NIOSSLServerHandler(
  174. context: sslContext,
  175. customVerificationCallback: verify
  176. )
  177. } else {
  178. sslHandler = NIOSSLServerHandler(context: sslContext)
  179. }
  180. try sync.addHandler(sslHandler)
  181. }
  182. }
  183. #endif // canImport(NIOSSL)
  184. private static func configureAcceptedChannel(
  185. _ channel: Channel,
  186. configuration: Configuration,
  187. addNIOSSLIfNecessary: (ChannelPipeline.SynchronousOperations) throws -> Void
  188. ) -> EventLoopFuture<Void> {
  189. var configuration = configuration
  190. configuration.logger[metadataKey: MetadataKey.connectionID] = "\(UUID().uuidString)"
  191. configuration.logger.addIPAddressMetadata(
  192. local: channel.localAddress,
  193. remote: channel.remoteAddress
  194. )
  195. do {
  196. let sync = channel.pipeline.syncOperations
  197. try addNIOSSLIfNecessary(sync)
  198. // Configures the pipeline based on whether the connection uses TLS or not.
  199. try sync.addHandler(GRPCServerPipelineConfigurator(configuration: configuration))
  200. // Work around the zero length write issue, if needed.
  201. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  202. group: configuration.eventLoopGroup,
  203. hasTLS: configuration.tlsConfiguration != nil
  204. )
  205. if requiresZeroLengthWorkaround,
  206. #available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  207. {
  208. try sync.addHandler(NIOFilterEmptyWritesHandler())
  209. }
  210. } catch {
  211. return channel.eventLoop.makeFailedFuture(error)
  212. }
  213. // Run the debug initializer, if there is one.
  214. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  215. return debugAcceptedChannelInitializer(channel)
  216. } else {
  217. return channel.eventLoop.makeSucceededVoidFuture()
  218. }
  219. }
  220. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  221. /// available to configure the server.
  222. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  223. switch configuration.target.wrapped {
  224. case .connectedSocket(let handle) where configuration.connectedSocketTargetIsAcceptedConnection:
  225. return Self.startServerFromAcceptedConnection(handle: handle, configuration: configuration)
  226. case .connectedSocket, .hostAndPort, .unixDomainSocket, .socketAddress, .vsockAddress:
  227. return Self.startServer(configuration: configuration)
  228. }
  229. }
  230. private static func startServer(configuration: Configuration) -> EventLoopFuture<Server> {
  231. let quiescingHelper = ServerQuiescingHelper(group: configuration.eventLoopGroup)
  232. return self.makeBootstrap(configuration: configuration)
  233. .serverChannelInitializer { channel in
  234. channel.pipeline.addHandler(quiescingHelper.makeServerChannelHandler(channel: channel))
  235. }
  236. .bind(to: configuration.target)
  237. .map { channel in
  238. Server(
  239. channel: channel,
  240. quiescingHelper: quiescingHelper,
  241. errorDelegate: configuration.errorDelegate
  242. )
  243. }
  244. }
  245. private static func startServerFromAcceptedConnection(
  246. handle: NIOBSDSocket.Handle,
  247. configuration: Configuration
  248. ) -> EventLoopFuture<Server> {
  249. guard let bootstrap = ClientBootstrap(validatingGroup: configuration.eventLoopGroup) else {
  250. let status = GRPCStatus(
  251. code: .unimplemented,
  252. message: """
  253. You must use a NIOPosix EventLoopGroup to create a server from an already accepted \
  254. socket.
  255. """
  256. )
  257. return configuration.eventLoopGroup.any().makeFailedFuture(status)
  258. }
  259. #if canImport(NIOSSL)
  260. let sslContext = Self.makeNIOSSLContext(configuration: configuration)
  261. #endif // canImport(NIOSSL)
  262. return bootstrap.channelInitializer { channel in
  263. Self.configureAcceptedChannel(channel, configuration: configuration) { sync in
  264. #if canImport(NIOSSL)
  265. try Self.addNIOSSLHandler(sslContext, configuration: configuration, sync: sync)
  266. #endif // canImport(NIOSSL)
  267. }
  268. }.withConnectedSocket(handle).map { channel in
  269. Server(
  270. channel: channel,
  271. quiescingHelper: nil,
  272. errorDelegate: configuration.errorDelegate
  273. )
  274. }
  275. }
  276. /// The listening server channel.
  277. ///
  278. /// If the server was created from an already accepted connection then this channel will
  279. /// be for the accepted connection.
  280. public let channel: Channel
  281. /// Quiescing helper. `nil` if `channel` is for an accepted connection.
  282. private let quiescingHelper: ServerQuiescingHelper?
  283. private var errorDelegate: ServerErrorDelegate?
  284. private init(
  285. channel: Channel,
  286. quiescingHelper: ServerQuiescingHelper?,
  287. errorDelegate: ServerErrorDelegate?
  288. ) {
  289. self.channel = channel
  290. self.quiescingHelper = quiescingHelper
  291. // Maintain a strong reference to ensure it lives as long as the server.
  292. self.errorDelegate = errorDelegate
  293. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  294. // be added.
  295. if let errorDelegate = errorDelegate {
  296. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  297. }
  298. // nil out errorDelegate to avoid retain cycles.
  299. self.onClose.whenComplete { _ in
  300. self.errorDelegate = nil
  301. }
  302. }
  303. /// Fired when the server shuts down.
  304. public var onClose: EventLoopFuture<Void> {
  305. return self.channel.closeFuture
  306. }
  307. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  308. /// connections will be rejected.
  309. public func initiateGracefulShutdown(promise: EventLoopPromise<Void>?) {
  310. if let quiescingHelper = self.quiescingHelper {
  311. quiescingHelper.initiateShutdown(promise: promise)
  312. } else {
  313. // No quiescing helper: the channel must be for an already accepted connection.
  314. self.channel.closeFuture.cascade(to: promise)
  315. self.channel.pipeline.fireUserInboundEventTriggered(ChannelShouldQuiesceEvent())
  316. }
  317. }
  318. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  319. /// connections will be rejected.
  320. public func initiateGracefulShutdown() -> EventLoopFuture<Void> {
  321. let promise = self.channel.eventLoop.makePromise(of: Void.self)
  322. self.initiateGracefulShutdown(promise: promise)
  323. return promise.futureResult
  324. }
  325. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  326. public func close(promise: EventLoopPromise<Void>?) {
  327. self.channel.close(mode: .all, promise: promise)
  328. }
  329. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  330. public func close() -> EventLoopFuture<Void> {
  331. return self.channel.close(mode: .all)
  332. }
  333. }
  334. public typealias BindTarget = ConnectionTarget
  335. extension Server {
  336. /// The configuration for a server.
  337. public struct Configuration {
  338. /// The target to bind to.
  339. public var target: BindTarget
  340. /// The event loop group to run the connection on.
  341. public var eventLoopGroup: EventLoopGroup
  342. /// Providers the server should use to handle gRPC requests.
  343. public var serviceProviders: [CallHandlerProvider] {
  344. get {
  345. return Array(self.serviceProvidersByName.values)
  346. }
  347. set {
  348. self
  349. .serviceProvidersByName = Dictionary(
  350. uniqueKeysWithValues:
  351. newValue
  352. .map { ($0.serviceName, $0) }
  353. )
  354. }
  355. }
  356. /// An error delegate which is called when errors are caught. Provided delegates **must not
  357. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  358. public var errorDelegate: ServerErrorDelegate?
  359. #if canImport(NIOSSL)
  360. /// TLS configuration for this connection. `nil` if TLS is not desired.
  361. @available(*, deprecated, renamed: "tlsConfiguration")
  362. public var tls: TLS? {
  363. get {
  364. return self.tlsConfiguration?.asDeprecatedServerConfiguration
  365. }
  366. set {
  367. self.tlsConfiguration = newValue.map { GRPCTLSConfiguration(transforming: $0) }
  368. }
  369. }
  370. #endif // canImport(NIOSSL)
  371. public var tlsConfiguration: GRPCTLSConfiguration?
  372. /// The connection keepalive configuration.
  373. public var connectionKeepalive = ServerConnectionKeepalive()
  374. /// The amount of time to wait before closing connections. The idle timeout will start only
  375. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  376. public var connectionIdleTimeout: TimeAmount = .nanoseconds(.max)
  377. /// The compression configuration for requests and responses.
  378. ///
  379. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  380. /// setting `compressionEnabled` to `false` on the context of the call.
  381. ///
  382. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  383. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  384. /// in `sendResponse(_:compression)`.
  385. ///
  386. /// Defaults to ``ServerMessageEncoding/disabled``.
  387. public var messageEncoding: ServerMessageEncoding = .disabled
  388. /// The maximum size in bytes of a message which may be received from a client. Defaults to 4MB.
  389. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  390. willSet {
  391. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  392. }
  393. }
  394. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  395. /// 1 and 2^31-1 inclusive.
  396. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  397. didSet {
  398. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  399. }
  400. }
  401. /// The HTTP/2 max number of concurrent streams. Defaults to 100. Must be non-negative.
  402. public var httpMaxConcurrentStreams: Int = 100 {
  403. willSet {
  404. precondition(newValue >= 0, "httpMaxConcurrentStreams must be non-negative")
  405. }
  406. }
  407. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  408. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  409. public var httpMaxFrameSize: Int = 16384 {
  410. didSet {
  411. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  412. }
  413. }
  414. /// The HTTP/2 max number of reset streams. Defaults to 32. Must be non-negative.
  415. public var httpMaxResetStreams: Int = 32 {
  416. willSet {
  417. precondition(newValue >= 0, "httpMaxResetStreams must be non-negative")
  418. }
  419. }
  420. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  421. /// each connection will use a logger branched from the connections logger. This logger is made
  422. /// available to service providers via `context`. Defaults to a no-op logger.
  423. public var logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  424. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  425. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  426. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  427. ///
  428. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  429. /// be invoked at most once per accepted connection.
  430. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  431. /// A calculated private cache of the service providers by name.
  432. ///
  433. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  434. /// the need to recalculate this dictionary each time we receive an rpc.
  435. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  436. #if canImport(Network)
  437. /// A closure allowing to customise the listener's `NWParameters` used when establishing a connection using `NIOTransportServices`.
  438. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  439. public var listenerNWParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  440. get {
  441. self._listenerNWParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  442. }
  443. set {
  444. self._listenerNWParametersConfigurator = newValue
  445. }
  446. }
  447. private var _listenerNWParametersConfigurator: (any Sendable)?
  448. /// A closure allowing to customise the child channels' `NWParameters` used when establishing connections using `NIOTransportServices`.
  449. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  450. public var childChannelNWParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  451. get {
  452. self._childChannelNWParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  453. }
  454. set {
  455. self._childChannelNWParametersConfigurator = newValue
  456. }
  457. }
  458. private var _childChannelNWParametersConfigurator: (any Sendable)?
  459. #endif
  460. /// CORS configuration for gRPC-Web support.
  461. public var webCORS = Configuration.CORS()
  462. /// Indicates whether a `connectedSocket` ``target`` is treated as an accepted connection.
  463. ///
  464. /// If ``target`` is a `connectedSocket` then this flag indicates whether that socket is for
  465. /// an already accepted connection. If the value is `false` then the socket is treated as a
  466. /// listener. This value is ignored if ``target`` is any value other than `connectedSocket`.
  467. public var connectedSocketTargetIsAcceptedConnection: Bool = false
  468. #if canImport(NIOSSL)
  469. /// Create a `Configuration` with some pre-defined defaults.
  470. ///
  471. /// - Parameters:
  472. /// - target: The target to bind to.
  473. /// - eventLoopGroup: The event loop group to run the server on.
  474. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  475. /// to handle requests.
  476. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  477. /// - tls: TLS configuration, defaulting to `nil`.
  478. /// - connectionKeepalive: The keepalive configuration to use.
  479. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  480. /// indefinite by default.
  481. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  482. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  483. /// - logger: A logger. Defaults to a no-op logger.
  484. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  485. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  486. @available(*, deprecated, renamed: "default(target:eventLoopGroup:serviceProviders:)")
  487. public init(
  488. target: BindTarget,
  489. eventLoopGroup: EventLoopGroup,
  490. serviceProviders: [CallHandlerProvider],
  491. errorDelegate: ServerErrorDelegate? = nil,
  492. tls: TLS? = nil,
  493. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  494. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  495. messageEncoding: ServerMessageEncoding = .disabled,
  496. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  497. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  498. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  499. ) {
  500. self.target = target
  501. self.eventLoopGroup = eventLoopGroup
  502. self.serviceProvidersByName = Dictionary(
  503. uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }
  504. )
  505. self.errorDelegate = errorDelegate
  506. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  507. self.connectionKeepalive = connectionKeepalive
  508. self.connectionIdleTimeout = connectionIdleTimeout
  509. self.messageEncoding = messageEncoding
  510. self.httpTargetWindowSize = httpTargetWindowSize
  511. self.logger = logger
  512. self.debugChannelInitializer = debugChannelInitializer
  513. }
  514. #endif // canImport(NIOSSL)
  515. private init(
  516. eventLoopGroup: EventLoopGroup,
  517. target: BindTarget,
  518. serviceProviders: [CallHandlerProvider]
  519. ) {
  520. self.eventLoopGroup = eventLoopGroup
  521. self.target = target
  522. self.serviceProvidersByName = Dictionary(
  523. uniqueKeysWithValues: serviceProviders.map {
  524. ($0.serviceName, $0)
  525. }
  526. )
  527. }
  528. /// Make a new configuration using default values.
  529. ///
  530. /// - Parameters:
  531. /// - target: The target to bind to.
  532. /// - eventLoopGroup: The `EventLoopGroup` the server should run on.
  533. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  534. /// to handle requests.
  535. /// - Returns: A configuration with default values set.
  536. public static func `default`(
  537. target: BindTarget,
  538. eventLoopGroup: EventLoopGroup,
  539. serviceProviders: [CallHandlerProvider]
  540. ) -> Configuration {
  541. return .init(
  542. eventLoopGroup: eventLoopGroup,
  543. target: target,
  544. serviceProviders: serviceProviders
  545. )
  546. }
  547. }
  548. }
  549. extension Server.Configuration {
  550. public struct CORS: Hashable, Sendable {
  551. /// Determines which 'origin' header field values are permitted in a CORS request.
  552. public var allowedOrigins: AllowedOrigins
  553. /// Sets the headers which are permitted in a response to a CORS request.
  554. public var allowedHeaders: [String]
  555. /// Enabling this value allows sets the "access-control-allow-credentials" header field
  556. /// to "true" in respones to CORS requests. This must be enabled if the client intends to send
  557. /// credentials.
  558. public var allowCredentialedRequests: Bool
  559. /// The maximum age in seconds which pre-flight CORS requests may be cached for.
  560. public var preflightCacheExpiration: Int
  561. public init(
  562. allowedOrigins: AllowedOrigins = .all,
  563. allowedHeaders: [String] = ["content-type", "x-grpc-web", "x-user-agent"],
  564. allowCredentialedRequests: Bool = false,
  565. preflightCacheExpiration: Int = 86400
  566. ) {
  567. self.allowedOrigins = allowedOrigins
  568. self.allowedHeaders = allowedHeaders
  569. self.allowCredentialedRequests = allowCredentialedRequests
  570. self.preflightCacheExpiration = preflightCacheExpiration
  571. }
  572. }
  573. }
  574. extension Server.Configuration.CORS {
  575. public struct AllowedOrigins: Hashable, Sendable {
  576. enum Wrapped: Hashable, Sendable {
  577. case all
  578. case originBased
  579. case only([String])
  580. case custom(AnyCustomCORSAllowedOrigin)
  581. }
  582. private(set) var wrapped: Wrapped
  583. private init(_ wrapped: Wrapped) {
  584. self.wrapped = wrapped
  585. }
  586. /// Allow all origin values.
  587. public static let all = Self(.all)
  588. /// Allow all origin values; similar to `all` but returns the value of the origin header field
  589. /// in the 'access-control-allow-origin' response header (rather than "*").
  590. public static let originBased = Self(.originBased)
  591. /// Allow only the given origin values.
  592. public static func only(_ allowed: [String]) -> Self {
  593. return Self(.only(allowed))
  594. }
  595. /// Provide a custom CORS origin check.
  596. ///
  597. /// - Parameter checkOrigin: A closure which is called with the value of the 'origin' header
  598. /// and returns the value to use in the 'access-control-allow-origin' response header,
  599. /// or `nil` if the origin is not allowed.
  600. public static func custom<C: GRPCCustomCORSAllowedOrigin>(_ custom: C) -> Self {
  601. return Self(.custom(AnyCustomCORSAllowedOrigin(custom)))
  602. }
  603. }
  604. }
  605. extension ServerBootstrapProtocol {
  606. fileprivate func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  607. switch target.wrapped {
  608. case let .hostAndPort(host, port):
  609. return self.bind(host: host, port: port)
  610. case let .unixDomainSocket(path):
  611. return self.bind(unixDomainSocketPath: path)
  612. case let .socketAddress(address):
  613. return self.bind(to: address)
  614. case let .connectedSocket(socket):
  615. return self.withBoundSocket(socket)
  616. case let .vsockAddress(address):
  617. return self.bind(to: address)
  618. }
  619. }
  620. }
  621. extension Comparable {
  622. internal func clamped(to range: ClosedRange<Self>) -> Self {
  623. return min(max(self, range.lowerBound), range.upperBound)
  624. }
  625. }
  626. public protocol GRPCCustomCORSAllowedOrigin: Sendable, Hashable {
  627. /// Returns the value to use for the 'access-control-allow-origin' response header for the given
  628. /// value of the 'origin' request header.
  629. ///
  630. /// - Parameter origin: The value of the 'origin' request header field.
  631. /// - Returns: The value to use for the 'access-control-allow-origin' header field or `nil` if no
  632. /// CORS related headers should be returned.
  633. func check(origin: String) -> String?
  634. }
  635. extension Server.Configuration.CORS.AllowedOrigins {
  636. struct AnyCustomCORSAllowedOrigin: GRPCCustomCORSAllowedOrigin {
  637. private var checkOrigin: @Sendable (String) -> String?
  638. private let hashInto: @Sendable (inout Hasher) -> Void
  639. private let isEqualTo: @Sendable (any GRPCCustomCORSAllowedOrigin) -> Bool
  640. init<W: GRPCCustomCORSAllowedOrigin>(_ wrap: W) {
  641. self.checkOrigin = { wrap.check(origin: $0) }
  642. self.hashInto = { wrap.hash(into: &$0) }
  643. self.isEqualTo = { wrap == ($0 as? W) }
  644. }
  645. func check(origin: String) -> String? {
  646. return self.checkOrigin(origin)
  647. }
  648. func hash(into hasher: inout Hasher) {
  649. self.hashInto(&hasher)
  650. }
  651. static func == (
  652. lhs: Server.Configuration.CORS.AllowedOrigins.AnyCustomCORSAllowedOrigin,
  653. rhs: Server.Configuration.CORS.AllowedOrigins.AnyCustomCORSAllowedOrigin
  654. ) -> Bool {
  655. return lhs.isEqualTo(rhs)
  656. }
  657. }
  658. }