Server.swift 25 KB

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