ServerBuilder.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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(to socketAddress: SocketAddress) -> EventLoopFuture<Server> {
  58. self.configuration.target = .socketAddress(socketAddress)
  59. self.configuration.tlsConfiguration = self.maybeTLS
  60. return Server.start(configuration: self.configuration)
  61. }
  62. public func bind(vsockAddress: VsockAddress) -> EventLoopFuture<Server> {
  63. self.configuration.target = .vsockAddress(vsockAddress)
  64. self.configuration.tlsConfiguration = self.maybeTLS
  65. return Server.start(configuration: self.configuration)
  66. }
  67. public func bind(to target: BindTarget) -> EventLoopFuture<Server> {
  68. self.configuration.target = target
  69. self.configuration.tlsConfiguration = self.maybeTLS
  70. return Server.start(configuration: self.configuration)
  71. }
  72. /// Create a gRPC server from the file descriptor of an already accepted TCP connection.
  73. ///
  74. /// - Parameter handle: The handle to the accepted socket.
  75. /// - Important: This is only supported with `NIOPosix` (i.e. when using a
  76. /// `MultiThreadedEventLoopGroup` or one of its loops and TLS configured via `NIOSSL`).
  77. /// - Warning: By calling this function you hand responsibility of the socket to gRPC.
  78. /// Crucially you must **not** close the socket directly after calling this function, gRPC
  79. /// will do it for you.
  80. /// - Returns: A configured gRPC server.
  81. public func fromAcceptedConnection(
  82. takingOwnershipOf handle: NIOBSDSocket.Handle
  83. ) -> EventLoopFuture<Server> {
  84. self.configuration.target = .connectedSocket(handle)
  85. self.configuration.connectedSocketTargetIsAcceptedConnection = true
  86. self.configuration.tlsConfiguration = self.maybeTLS
  87. return Server.start(configuration: self.configuration)
  88. }
  89. }
  90. }
  91. extension Server.Builder {
  92. /// Sets the server error delegate.
  93. @discardableResult
  94. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  95. self.configuration.errorDelegate = delegate
  96. return self
  97. }
  98. }
  99. extension Server.Builder {
  100. /// Sets the service providers that this server should offer. Note that calling this multiple
  101. /// times will override any previously set providers.
  102. @discardableResult
  103. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  104. self.configuration.serviceProviders = providers
  105. return self
  106. }
  107. }
  108. extension Server.Builder {
  109. @discardableResult
  110. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  111. self.configuration.connectionKeepalive = keepalive
  112. return self
  113. }
  114. }
  115. extension Server.Builder {
  116. /// The amount of time to wait before closing connections. The idle timeout will start only
  117. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  118. /// an idle timeout it set connections will not be idled by default.
  119. @discardableResult
  120. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  121. self.configuration.connectionIdleTimeout = timeout
  122. return self
  123. }
  124. }
  125. extension Server.Builder {
  126. /// Sets the message compression configuration. Compression is disabled if this is not configured
  127. /// and any RPCs using compression will not be accepted.
  128. @discardableResult
  129. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  130. self.configuration.messageEncoding = encoding
  131. return self
  132. }
  133. /// Sets the maximum message size in bytes the server may receive.
  134. ///
  135. /// - Precondition: `limit` must not be negative.
  136. @discardableResult
  137. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  138. self.configuration.maximumReceiveMessageLength = limit
  139. return self
  140. }
  141. }
  142. extension Server.Builder.Secure {
  143. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  144. /// defaults to `true` if not otherwise set.
  145. ///
  146. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  147. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  148. /// is being used and configure the connection appropriately.
  149. ///
  150. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  151. @discardableResult
  152. public func withTLS(requiringALPN: Bool) -> Self {
  153. self.tls.requireALPN = requiringALPN
  154. return self
  155. }
  156. }
  157. extension Server.Builder {
  158. /// Sets the HTTP/2 flow control target window size. Defaults to 8MB if not explicitly set.
  159. /// Values are clamped between 1 and 2^31-1 inclusive.
  160. @discardableResult
  161. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  162. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  163. return self
  164. }
  165. /// Sets the maximum allowed number of concurrent HTTP/2 streams a client may open for a given
  166. /// connection. Defaults to 100.
  167. @discardableResult
  168. public func withHTTPMaxConcurrentStreams(_ httpMaxConcurrentStreams: Int) -> Self {
  169. self.configuration.httpMaxConcurrentStreams = httpMaxConcurrentStreams
  170. return self
  171. }
  172. /// Sets the HTTP/2 max frame size. Defaults to 16384. Value are clamped between 2^14 and 2^24-1
  173. /// octets inclusive (the minimum and maximum permitted values per RFC 7540 § 4.2).
  174. ///
  175. /// Raising this value may lower CPU usage for large message at the cost of increasing head of
  176. /// line blocking for small messages.
  177. @discardableResult
  178. public func withHTTPMaxFrameSize(_ httpMaxFrameSize: Int) -> Self {
  179. self.configuration.httpMaxFrameSize = httpMaxFrameSize
  180. return self
  181. }
  182. }
  183. extension Server.Builder {
  184. /// Set the CORS configuration for gRPC Web.
  185. @discardableResult
  186. public func withCORSConfiguration(_ configuration: Server.Configuration.CORS) -> Self {
  187. self.configuration.webCORS = configuration
  188. return self
  189. }
  190. }
  191. extension Server.Builder {
  192. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  193. /// each connection will use a logger branched from the connections logger. This logger is made
  194. /// available to service providers via `context`. Defaults to a no-op logger.
  195. @discardableResult
  196. public func withLogger(_ logger: Logger) -> Self {
  197. self.configuration.logger = logger
  198. return self
  199. }
  200. }
  201. extension Server.Builder {
  202. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  203. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  204. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  205. ///
  206. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  207. /// be invoked at most once per accepted connection.
  208. @discardableResult
  209. public func withDebugChannelInitializer(
  210. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  211. ) -> Self {
  212. self.configuration.debugChannelInitializer = debugChannelInitializer
  213. return self
  214. }
  215. }
  216. extension Server {
  217. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  218. public static func insecure(group: EventLoopGroup) -> Builder {
  219. return Builder(group: group)
  220. }
  221. #if canImport(Network)
  222. /// Returns a `Server` builder configured with the 'Network.framework' TLS backend.
  223. ///
  224. /// This builder must use a `NIOTSEventLoopGroup`.
  225. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  226. public static func usingTLSBackedByNetworkFramework(
  227. on group: EventLoopGroup,
  228. with identity: SecIdentity
  229. ) -> Builder.Secure {
  230. precondition(
  231. PlatformSupport.isTransportServicesEventLoopGroup(group),
  232. "'usingTLSBackedByNetworkFramework(on:with:)' requires 'eventLoopGroup' to be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: group))'"
  233. )
  234. return Builder.Secure(
  235. group: group,
  236. tlsConfiguration: .makeServerConfigurationBackedByNetworkFramework(identity: identity)
  237. )
  238. }
  239. #endif
  240. /// Returns a `Server` builder configured with the TLS backend appropriate for the
  241. /// provided `configuration` and `EventLoopGroup`.
  242. ///
  243. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  244. /// the the `group`.
  245. public static func usingTLS(
  246. with configuration: GRPCTLSConfiguration,
  247. on group: EventLoopGroup
  248. ) -> Builder.Secure {
  249. return Builder.Secure(group: group, tlsConfiguration: configuration)
  250. }
  251. }