2
0

Server.swift 24 KB

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