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