ServerBuilder.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. * Copyright 2020, 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 Logging
  17. import NIOCore
  18. import NIOPosix
  19. #if canImport(Network)
  20. import Security
  21. #endif
  22. extension Server {
  23. public class Builder {
  24. private var configuration: Server.Configuration
  25. private var maybeTLS: GRPCTLSConfiguration? { return nil }
  26. fileprivate init(group: EventLoopGroup) {
  27. self.configuration = .default(
  28. // This is okay: the configuration is only consumed on a call to `bind` which sets the host
  29. // and port.
  30. target: .hostAndPort("", .max),
  31. eventLoopGroup: group,
  32. serviceProviders: []
  33. )
  34. }
  35. public class Secure: Builder {
  36. internal var tls: GRPCTLSConfiguration
  37. override var maybeTLS: GRPCTLSConfiguration? {
  38. return self.tls
  39. }
  40. internal init(group: EventLoopGroup, tlsConfiguration: GRPCTLSConfiguration) {
  41. group.preconditionCompatible(with: tlsConfiguration)
  42. self.tls = tlsConfiguration
  43. super.init(group: group)
  44. }
  45. }
  46. public func bind(host: String, port: Int) -> EventLoopFuture<Server> {
  47. // Finish setting up the configuration.
  48. self.configuration.target = .hostAndPort(host, port)
  49. self.configuration.tlsConfiguration = self.maybeTLS
  50. return Server.start(configuration: self.configuration)
  51. }
  52. public func bind(unixDomainSocketPath path: String) -> EventLoopFuture<Server> {
  53. self.configuration.target = .unixDomainSocket(path)
  54. self.configuration.tlsConfiguration = self.maybeTLS
  55. return Server.start(configuration: self.configuration)
  56. }
  57. public func bind(vsockAddress: VsockAddress) -> EventLoopFuture<Server> {
  58. self.configuration.target = .vsockAddress(vsockAddress)
  59. self.configuration.tlsConfiguration = self.maybeTLS
  60. return Server.start(configuration: self.configuration)
  61. }
  62. }
  63. }
  64. extension Server.Builder {
  65. /// Sets the server error delegate.
  66. @discardableResult
  67. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  68. self.configuration.errorDelegate = delegate
  69. return self
  70. }
  71. }
  72. extension Server.Builder {
  73. /// Sets the service providers that this server should offer. Note that calling this multiple
  74. /// times will override any previously set providers.
  75. @discardableResult
  76. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  77. self.configuration.serviceProviders = providers
  78. return self
  79. }
  80. }
  81. extension Server.Builder {
  82. @discardableResult
  83. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  84. self.configuration.connectionKeepalive = keepalive
  85. return self
  86. }
  87. }
  88. extension Server.Builder {
  89. /// The amount of time to wait before closing connections. The idle timeout will start only
  90. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  91. /// an idle timeout it set connections will not be idled by default.
  92. @discardableResult
  93. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  94. self.configuration.connectionIdleTimeout = timeout
  95. return self
  96. }
  97. }
  98. extension Server.Builder {
  99. /// Sets the message compression configuration. Compression is disabled if this is not configured
  100. /// and any RPCs using compression will not be accepted.
  101. @discardableResult
  102. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  103. self.configuration.messageEncoding = encoding
  104. return self
  105. }
  106. /// Sets the maximum message size in bytes the server may receive.
  107. ///
  108. /// - Precondition: `limit` must not be negative.
  109. @discardableResult
  110. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  111. self.configuration.maximumReceiveMessageLength = limit
  112. return self
  113. }
  114. }
  115. extension Server.Builder.Secure {
  116. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  117. /// defaults to `true` if not otherwise set.
  118. ///
  119. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  120. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  121. /// is being used and configure the connection appropriately.
  122. ///
  123. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  124. @discardableResult
  125. public func withTLS(requiringALPN: Bool) -> Self {
  126. self.tls.requireALPN = requiringALPN
  127. return self
  128. }
  129. }
  130. extension Server.Builder {
  131. /// Sets the HTTP/2 flow control target window size. Defaults to 8MB if not explicitly set.
  132. /// Values are clamped between 1 and 2^31-1 inclusive.
  133. @discardableResult
  134. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  135. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  136. return self
  137. }
  138. /// Sets the maximum allowed number of concurrent HTTP/2 streams a client may open for a given
  139. /// connection. Defaults to 100.
  140. @discardableResult
  141. public func withHTTPMaxConcurrentStreams(_ httpMaxConcurrentStreams: Int) -> Self {
  142. self.configuration.httpMaxConcurrentStreams = httpMaxConcurrentStreams
  143. return self
  144. }
  145. /// Sets the HTTP/2 max frame size. Defaults to 16384. Value are clamped between 2^14 and 2^24-1
  146. /// octets inclusive (the minimum and maximum permitted values per RFC 7540 § 4.2).
  147. ///
  148. /// Raising this value may lower CPU usage for large message at the cost of increasing head of
  149. /// line blocking for small messages.
  150. @discardableResult
  151. public func withHTTPMaxFrameSize(_ httpMaxFrameSize: Int) -> Self {
  152. self.configuration.httpMaxFrameSize = httpMaxFrameSize
  153. return self
  154. }
  155. }
  156. extension Server.Builder {
  157. /// Set the CORS configuration for gRPC Web.
  158. @discardableResult
  159. public func withCORSConfiguration(_ configuration: Server.Configuration.CORS) -> Self {
  160. self.configuration.webCORS = configuration
  161. return self
  162. }
  163. }
  164. extension Server.Builder {
  165. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  166. /// each connection will use a logger branched from the connections logger. This logger is made
  167. /// available to service providers via `context`. Defaults to a no-op logger.
  168. @discardableResult
  169. public func withLogger(_ logger: Logger) -> Self {
  170. self.configuration.logger = logger
  171. return self
  172. }
  173. }
  174. extension Server.Builder {
  175. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  176. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  177. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  178. ///
  179. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  180. /// be invoked at most once per accepted connection.
  181. @discardableResult
  182. public func withDebugChannelInitializer(
  183. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  184. ) -> Self {
  185. self.configuration.debugChannelInitializer = debugChannelInitializer
  186. return self
  187. }
  188. }
  189. extension Server {
  190. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  191. public static func insecure(group: EventLoopGroup) -> Builder {
  192. return Builder(group: group)
  193. }
  194. #if canImport(Network)
  195. /// Returns a `Server` builder configured with the 'Network.framework' TLS backend.
  196. ///
  197. /// This builder must use a `NIOTSEventLoopGroup`.
  198. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  199. public static func usingTLSBackedByNetworkFramework(
  200. on group: EventLoopGroup,
  201. with identity: SecIdentity
  202. ) -> Builder.Secure {
  203. precondition(
  204. PlatformSupport.isTransportServicesEventLoopGroup(group),
  205. "'usingTLSBackedByNetworkFramework(on:with:)' requires 'eventLoopGroup' to be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: group))'"
  206. )
  207. return Builder.Secure(
  208. group: group,
  209. tlsConfiguration: .makeServerConfigurationBackedByNetworkFramework(identity: identity)
  210. )
  211. }
  212. #endif
  213. /// Returns a `Server` builder configured with the TLS backend appropriate for the
  214. /// provided `configuration` and `EventLoopGroup`.
  215. ///
  216. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  217. /// the the `group`.
  218. public static func usingTLS(
  219. with configuration: GRPCTLSConfiguration,
  220. on group: EventLoopGroup
  221. ) -> Builder.Secure {
  222. return Builder.Secure(group: group, tlsConfiguration: configuration)
  223. }
  224. }