Server.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. // Making a `NIOSSLContext` is expensive, we should only do it once per TLS configuration so
  98. // we'll do it now, before accepting connections. Unfortunately our API isn't throwing so we'll
  99. // only surface any error when initializing a child channel.
  100. //
  101. // 'nil' means we're not using TLS, or we're using the Network.framework TLS backend. If we're
  102. // using the Network.framework TLS backend we'll apply the settings just below.
  103. let sslContext: Result<NIOSSLContext, Error>?
  104. if let tlsConfiguration = configuration.tlsConfiguration {
  105. do {
  106. sslContext = try tlsConfiguration.makeNIOSSLContext().map { .success($0) }
  107. } catch {
  108. sslContext = .failure(error)
  109. }
  110. } else {
  111. // No TLS configuration, no SSL context.
  112. sslContext = nil
  113. }
  114. #endif // canImport(NIOSSL)
  115. #if canImport(Network)
  116. if let tlsConfiguration = configuration.tlsConfiguration {
  117. if #available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  118. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  119. {
  120. _ = transportServicesBootstrap.tlsOptions(from: tlsConfiguration)
  121. }
  122. }
  123. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
  124. let configurator = configuration.listenerNWParametersConfigurator,
  125. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  126. {
  127. _ = transportServicesBootstrap.configureNWParameters(configurator)
  128. }
  129. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
  130. let configurator = configuration.childChannelNWParametersConfigurator,
  131. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  132. {
  133. _ = transportServicesBootstrap.configureChildNWParameters(configurator)
  134. }
  135. #endif // canImport(Network)
  136. return
  137. bootstrap
  138. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  139. .serverChannelOption(
  140. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  141. value: 1
  142. )
  143. // Set the handlers that are applied to the accepted Channels
  144. .childChannelInitializer { channel in
  145. var configuration = configuration
  146. configuration.logger[metadataKey: MetadataKey.connectionID] = "\(UUID().uuidString)"
  147. configuration.logger.addIPAddressMetadata(
  148. local: channel.localAddress,
  149. remote: channel.remoteAddress
  150. )
  151. do {
  152. let sync = channel.pipeline.syncOperations
  153. #if canImport(NIOSSL)
  154. if let sslContext = try sslContext?.get() {
  155. let sslHandler: NIOSSLServerHandler
  156. if let verify = configuration.tlsConfiguration?.nioSSLCustomVerificationCallback {
  157. sslHandler = NIOSSLServerHandler(
  158. context: sslContext,
  159. customVerificationCallback: verify
  160. )
  161. } else {
  162. sslHandler = NIOSSLServerHandler(context: sslContext)
  163. }
  164. try sync.addHandler(sslHandler)
  165. }
  166. #endif // canImport(NIOSSL)
  167. // Configures the pipeline based on whether the connection uses TLS or not.
  168. try sync.addHandler(GRPCServerPipelineConfigurator(configuration: configuration))
  169. // Work around the zero length write issue, if needed.
  170. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  171. group: configuration.eventLoopGroup,
  172. hasTLS: configuration.tlsConfiguration != nil
  173. )
  174. if requiresZeroLengthWorkaround,
  175. #available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  176. {
  177. try sync.addHandler(NIOFilterEmptyWritesHandler())
  178. }
  179. } catch {
  180. return channel.eventLoop.makeFailedFuture(error)
  181. }
  182. // Run the debug initializer, if there is one.
  183. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  184. return debugAcceptedChannelInitializer(channel)
  185. } else {
  186. return channel.eventLoop.makeSucceededVoidFuture()
  187. }
  188. }
  189. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  190. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  191. .childChannelOption(
  192. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  193. value: 1
  194. )
  195. }
  196. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  197. /// available to configure the server.
  198. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  199. let quiescingHelper = ServerQuiescingHelper(group: configuration.eventLoopGroup)
  200. return self.makeBootstrap(configuration: configuration)
  201. .serverChannelInitializer { channel in
  202. channel.pipeline.addHandler(quiescingHelper.makeServerChannelHandler(channel: channel))
  203. }
  204. .bind(to: configuration.target)
  205. .map { channel in
  206. Server(
  207. channel: channel,
  208. quiescingHelper: quiescingHelper,
  209. errorDelegate: configuration.errorDelegate
  210. )
  211. }
  212. }
  213. public let channel: Channel
  214. private let quiescingHelper: ServerQuiescingHelper
  215. private var errorDelegate: ServerErrorDelegate?
  216. private init(
  217. channel: Channel,
  218. quiescingHelper: ServerQuiescingHelper,
  219. errorDelegate: ServerErrorDelegate?
  220. ) {
  221. self.channel = channel
  222. self.quiescingHelper = quiescingHelper
  223. // Maintain a strong reference to ensure it lives as long as the server.
  224. self.errorDelegate = errorDelegate
  225. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  226. // be added.
  227. if let errorDelegate = errorDelegate {
  228. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  229. }
  230. // nil out errorDelegate to avoid retain cycles.
  231. self.onClose.whenComplete { _ in
  232. self.errorDelegate = nil
  233. }
  234. }
  235. /// Fired when the server shuts down.
  236. public var onClose: EventLoopFuture<Void> {
  237. return self.channel.closeFuture
  238. }
  239. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  240. /// connections will be rejected.
  241. public func initiateGracefulShutdown(promise: EventLoopPromise<Void>?) {
  242. self.quiescingHelper.initiateShutdown(promise: promise)
  243. }
  244. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  245. /// connections will be rejected.
  246. public func initiateGracefulShutdown() -> EventLoopFuture<Void> {
  247. let promise = self.channel.eventLoop.makePromise(of: Void.self)
  248. self.initiateGracefulShutdown(promise: promise)
  249. return promise.futureResult
  250. }
  251. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  252. public func close(promise: EventLoopPromise<Void>?) {
  253. self.channel.close(mode: .all, promise: promise)
  254. }
  255. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  256. public func close() -> EventLoopFuture<Void> {
  257. return self.channel.close(mode: .all)
  258. }
  259. }
  260. public typealias BindTarget = ConnectionTarget
  261. extension Server {
  262. /// The configuration for a server.
  263. public struct Configuration {
  264. /// The target to bind to.
  265. public var target: BindTarget
  266. /// The event loop group to run the connection on.
  267. public var eventLoopGroup: EventLoopGroup
  268. /// Providers the server should use to handle gRPC requests.
  269. public var serviceProviders: [CallHandlerProvider] {
  270. get {
  271. return Array(self.serviceProvidersByName.values)
  272. }
  273. set {
  274. self
  275. .serviceProvidersByName = Dictionary(
  276. uniqueKeysWithValues:
  277. newValue
  278. .map { ($0.serviceName, $0) }
  279. )
  280. }
  281. }
  282. /// An error delegate which is called when errors are caught. Provided delegates **must not
  283. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  284. public var errorDelegate: ServerErrorDelegate?
  285. #if canImport(NIOSSL)
  286. /// TLS configuration for this connection. `nil` if TLS is not desired.
  287. @available(*, deprecated, renamed: "tlsConfiguration")
  288. public var tls: TLS? {
  289. get {
  290. return self.tlsConfiguration?.asDeprecatedServerConfiguration
  291. }
  292. set {
  293. self.tlsConfiguration = newValue.map { GRPCTLSConfiguration(transforming: $0) }
  294. }
  295. }
  296. #endif // canImport(NIOSSL)
  297. public var tlsConfiguration: GRPCTLSConfiguration?
  298. /// The connection keepalive configuration.
  299. public var connectionKeepalive = ServerConnectionKeepalive()
  300. /// The amount of time to wait before closing connections. The idle timeout will start only
  301. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  302. public var connectionIdleTimeout: TimeAmount = .nanoseconds(.max)
  303. /// The compression configuration for requests and responses.
  304. ///
  305. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  306. /// setting `compressionEnabled` to `false` on the context of the call.
  307. ///
  308. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  309. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  310. /// in `sendResponse(_:compression)`.
  311. ///
  312. /// Defaults to ``ServerMessageEncoding/disabled``.
  313. public var messageEncoding: ServerMessageEncoding = .disabled
  314. /// The maximum size in bytes of a message which may be received from a client. Defaults to 4MB.
  315. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  316. willSet {
  317. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  318. }
  319. }
  320. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  321. /// 1 and 2^31-1 inclusive.
  322. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  323. didSet {
  324. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  325. }
  326. }
  327. /// The HTTP/2 max number of concurrent streams. Defaults to 100. Must be non-negative.
  328. public var httpMaxConcurrentStreams: Int = 100 {
  329. willSet {
  330. precondition(newValue >= 0, "httpMaxConcurrentStreams must be non-negative")
  331. }
  332. }
  333. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  334. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  335. public var httpMaxFrameSize: Int = 16384 {
  336. didSet {
  337. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  338. }
  339. }
  340. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  341. /// each connection will use a logger branched from the connections logger. This logger is made
  342. /// available to service providers via `context`. Defaults to a no-op logger.
  343. public var logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  344. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  345. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  346. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  347. ///
  348. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  349. /// be invoked at most once per accepted connection.
  350. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  351. /// A calculated private cache of the service providers by name.
  352. ///
  353. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  354. /// the need to recalculate this dictionary each time we receive an rpc.
  355. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  356. #if canImport(Network)
  357. /// A closure allowing to customise the listener's `NWParameters` used when establishing a connection using `NIOTransportServices`.
  358. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  359. public var listenerNWParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  360. get {
  361. self._listenerNWParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  362. }
  363. set {
  364. self._listenerNWParametersConfigurator = newValue
  365. }
  366. }
  367. private var _listenerNWParametersConfigurator: (any Sendable)?
  368. /// A closure allowing to customise the child channels' `NWParameters` used when establishing connections using `NIOTransportServices`.
  369. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  370. public var childChannelNWParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  371. get {
  372. self._childChannelNWParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  373. }
  374. set {
  375. self._childChannelNWParametersConfigurator = newValue
  376. }
  377. }
  378. private var _childChannelNWParametersConfigurator: (any Sendable)?
  379. #endif
  380. /// CORS configuration for gRPC-Web support.
  381. public var webCORS = Configuration.CORS()
  382. #if canImport(NIOSSL)
  383. /// Create a `Configuration` with some pre-defined defaults.
  384. ///
  385. /// - Parameters:
  386. /// - target: The target to bind to.
  387. /// - eventLoopGroup: The event loop group to run the server on.
  388. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  389. /// to handle requests.
  390. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  391. /// - tls: TLS configuration, defaulting to `nil`.
  392. /// - connectionKeepalive: The keepalive configuration to use.
  393. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  394. /// indefinite by default.
  395. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  396. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  397. /// - logger: A logger. Defaults to a no-op logger.
  398. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  399. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  400. @available(*, deprecated, renamed: "default(target:eventLoopGroup:serviceProviders:)")
  401. public init(
  402. target: BindTarget,
  403. eventLoopGroup: EventLoopGroup,
  404. serviceProviders: [CallHandlerProvider],
  405. errorDelegate: ServerErrorDelegate? = nil,
  406. tls: TLS? = nil,
  407. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  408. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  409. messageEncoding: ServerMessageEncoding = .disabled,
  410. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  411. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  412. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  413. ) {
  414. self.target = target
  415. self.eventLoopGroup = eventLoopGroup
  416. self.serviceProvidersByName = Dictionary(
  417. uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }
  418. )
  419. self.errorDelegate = errorDelegate
  420. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  421. self.connectionKeepalive = connectionKeepalive
  422. self.connectionIdleTimeout = connectionIdleTimeout
  423. self.messageEncoding = messageEncoding
  424. self.httpTargetWindowSize = httpTargetWindowSize
  425. self.logger = logger
  426. self.debugChannelInitializer = debugChannelInitializer
  427. }
  428. #endif // canImport(NIOSSL)
  429. private init(
  430. eventLoopGroup: EventLoopGroup,
  431. target: BindTarget,
  432. serviceProviders: [CallHandlerProvider]
  433. ) {
  434. self.eventLoopGroup = eventLoopGroup
  435. self.target = target
  436. self.serviceProvidersByName = Dictionary(
  437. uniqueKeysWithValues: serviceProviders.map {
  438. ($0.serviceName, $0)
  439. }
  440. )
  441. }
  442. /// Make a new configuration using default values.
  443. ///
  444. /// - Parameters:
  445. /// - target: The target to bind to.
  446. /// - eventLoopGroup: The `EventLoopGroup` the server should run on.
  447. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  448. /// to handle requests.
  449. /// - Returns: A configuration with default values set.
  450. public static func `default`(
  451. target: BindTarget,
  452. eventLoopGroup: EventLoopGroup,
  453. serviceProviders: [CallHandlerProvider]
  454. ) -> Configuration {
  455. return .init(
  456. eventLoopGroup: eventLoopGroup,
  457. target: target,
  458. serviceProviders: serviceProviders
  459. )
  460. }
  461. }
  462. }
  463. extension Server.Configuration {
  464. public struct CORS: Hashable, Sendable {
  465. /// Determines which 'origin' header field values are permitted in a CORS request.
  466. public var allowedOrigins: AllowedOrigins
  467. /// Sets the headers which are permitted in a response to a CORS request.
  468. public var allowedHeaders: [String]
  469. /// Enabling this value allows sets the "access-control-allow-credentials" header field
  470. /// to "true" in respones to CORS requests. This must be enabled if the client intends to send
  471. /// credentials.
  472. public var allowCredentialedRequests: Bool
  473. /// The maximum age in seconds which pre-flight CORS requests may be cached for.
  474. public var preflightCacheExpiration: Int
  475. public init(
  476. allowedOrigins: AllowedOrigins = .all,
  477. allowedHeaders: [String] = ["content-type", "x-grpc-web", "x-user-agent"],
  478. allowCredentialedRequests: Bool = false,
  479. preflightCacheExpiration: Int = 86400
  480. ) {
  481. self.allowedOrigins = allowedOrigins
  482. self.allowedHeaders = allowedHeaders
  483. self.allowCredentialedRequests = allowCredentialedRequests
  484. self.preflightCacheExpiration = preflightCacheExpiration
  485. }
  486. }
  487. }
  488. extension Server.Configuration.CORS {
  489. public struct AllowedOrigins: Hashable, Sendable {
  490. enum Wrapped: Hashable, Sendable {
  491. case all
  492. case originBased
  493. case only([String])
  494. case custom(AnyCustomCORSAllowedOrigin)
  495. }
  496. private(set) var wrapped: Wrapped
  497. private init(_ wrapped: Wrapped) {
  498. self.wrapped = wrapped
  499. }
  500. /// Allow all origin values.
  501. public static let all = Self(.all)
  502. /// Allow all origin values; similar to `all` but returns the value of the origin header field
  503. /// in the 'access-control-allow-origin' response header (rather than "*").
  504. public static let originBased = Self(.originBased)
  505. /// Allow only the given origin values.
  506. public static func only(_ allowed: [String]) -> Self {
  507. return Self(.only(allowed))
  508. }
  509. /// Provide a custom CORS origin check.
  510. ///
  511. /// - Parameter checkOrigin: A closure which is called with the value of the 'origin' header
  512. /// and returns the value to use in the 'access-control-allow-origin' response header,
  513. /// or `nil` if the origin is not allowed.
  514. public static func custom<C: GRPCCustomCORSAllowedOrigin>(_ custom: C) -> Self {
  515. return Self(.custom(AnyCustomCORSAllowedOrigin(custom)))
  516. }
  517. }
  518. }
  519. extension ServerBootstrapProtocol {
  520. fileprivate func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  521. switch target.wrapped {
  522. case let .hostAndPort(host, port):
  523. return self.bind(host: host, port: port)
  524. case let .unixDomainSocket(path):
  525. return self.bind(unixDomainSocketPath: path)
  526. case let .socketAddress(address):
  527. return self.bind(to: address)
  528. case let .connectedSocket(socket):
  529. return self.withBoundSocket(socket)
  530. case let .vsockAddress(address):
  531. return self.bind(to: address)
  532. }
  533. }
  534. }
  535. extension Comparable {
  536. internal func clamped(to range: ClosedRange<Self>) -> Self {
  537. return min(max(self, range.lowerBound), range.upperBound)
  538. }
  539. }
  540. public protocol GRPCCustomCORSAllowedOrigin: Sendable, Hashable {
  541. /// Returns the value to use for the 'access-control-allow-origin' response header for the given
  542. /// value of the 'origin' request header.
  543. ///
  544. /// - Parameter origin: The value of the 'origin' request header field.
  545. /// - Returns: The value to use for the 'access-control-allow-origin' header field or `nil` if no
  546. /// CORS related headers should be returned.
  547. func check(origin: String) -> String?
  548. }
  549. extension Server.Configuration.CORS.AllowedOrigins {
  550. struct AnyCustomCORSAllowedOrigin: GRPCCustomCORSAllowedOrigin {
  551. private var checkOrigin: @Sendable (String) -> String?
  552. private let hashInto: @Sendable (inout Hasher) -> Void
  553. private let isEqualTo: @Sendable (any GRPCCustomCORSAllowedOrigin) -> Bool
  554. init<W: GRPCCustomCORSAllowedOrigin>(_ wrap: W) {
  555. self.checkOrigin = { wrap.check(origin: $0) }
  556. self.hashInto = { wrap.hash(into: &$0) }
  557. self.isEqualTo = { wrap == ($0 as? W) }
  558. }
  559. func check(origin: String) -> String? {
  560. return self.checkOrigin(origin)
  561. }
  562. func hash(into hasher: inout Hasher) {
  563. self.hashInto(&hasher)
  564. }
  565. static func == (
  566. lhs: Server.Configuration.CORS.AllowedOrigins.AnyCustomCORSAllowedOrigin,
  567. rhs: Server.Configuration.CORS.AllowedOrigins.AnyCustomCORSAllowedOrigin
  568. ) -> Bool {
  569. return lhs.isEqualTo(rhs)
  570. }
  571. }
  572. }