Server.swift 25 KB

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