2
0

ServerBuilder.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 NIOSSL
  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. private var tls: GRPCTLSConfiguration
  37. override var maybeTLS: GRPCTLSConfiguration? {
  38. return self.tls
  39. }
  40. fileprivate 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. }
  53. }
  54. extension Server.Builder {
  55. /// Sets the server error delegate.
  56. @discardableResult
  57. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  58. self.configuration.errorDelegate = delegate
  59. return self
  60. }
  61. }
  62. extension Server.Builder {
  63. /// Sets the service providers that this server should offer. Note that calling this multiple
  64. /// times will override any previously set providers.
  65. @discardableResult
  66. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  67. self.configuration.serviceProviders = providers
  68. return self
  69. }
  70. }
  71. extension Server.Builder {
  72. @discardableResult
  73. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  74. self.configuration.connectionKeepalive = keepalive
  75. return self
  76. }
  77. }
  78. extension Server.Builder {
  79. /// The amount of time to wait before closing connections. The idle timeout will start only
  80. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  81. /// an idle timeout it set connections will not be idled by default.
  82. @discardableResult
  83. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  84. self.configuration.connectionIdleTimeout = timeout
  85. return self
  86. }
  87. }
  88. extension Server.Builder {
  89. /// Sets the message compression configuration. Compression is disabled if this is not configured
  90. /// and any RPCs using compression will not be accepted.
  91. @discardableResult
  92. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  93. self.configuration.messageEncoding = encoding
  94. return self
  95. }
  96. /// Sets the maximum message size in bytes the server may receive.
  97. ///
  98. /// - Precondition: `limit` must not be negative.
  99. @discardableResult
  100. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  101. self.configuration.maximumReceiveMessageLength = limit
  102. return self
  103. }
  104. }
  105. extension Server.Builder.Secure {
  106. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  107. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  108. /// not set.
  109. ///
  110. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  111. @discardableResult
  112. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  113. self.tls.updateNIOTrustRoots(to: trustRoots)
  114. return self
  115. }
  116. /// Sets whether certificates should be verified. Defaults to `.none` if not set.
  117. ///
  118. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  119. @discardableResult
  120. public func withTLS(certificateVerification: CertificateVerification) -> Self {
  121. self.tls.updateNIOCertificateVerification(to: certificateVerification)
  122. return self
  123. }
  124. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  125. /// defaults to `true` if not otherwise set.
  126. ///
  127. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  128. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  129. /// is being used and configure the connection appropriately.
  130. ///
  131. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  132. @discardableResult
  133. public func withTLS(requiringALPN: Bool) -> Self {
  134. self.tls.requireALPN = requiringALPN
  135. return self
  136. }
  137. }
  138. extension Server.Builder {
  139. /// Sets the HTTP/2 flow control target window size. Defaults to 8MB if not explicitly set.
  140. /// Values are clamped between 1 and 2^31-1 inclusive.
  141. @discardableResult
  142. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  143. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  144. return self
  145. }
  146. /// Sets the maximum allowed number of concurrent HTTP/2 streams a client may open for a given
  147. /// connection. Defaults to 100.
  148. @discardableResult
  149. public func withHTTPMaxConcurrentStreams(_ httpMaxConcurrentStreams: Int) -> Self {
  150. self.configuration.httpMaxConcurrentStreams = httpMaxConcurrentStreams
  151. return self
  152. }
  153. /// Sets the HTTP/2 max frame size. Defaults to 16384. Value are clamped between 2^14 and 2^24-1
  154. /// octets inclusive (the minimum and maximum permitted values per RFC 7540 § 4.2).
  155. ///
  156. /// Raising this value may lower CPU usage for large message at the cost of increasing head of
  157. /// line blocking for small messages.
  158. @discardableResult
  159. public func withHTTPMaxFrameSize(_ httpMaxFrameSize: Int) -> Self {
  160. self.configuration.httpMaxFrameSize = httpMaxFrameSize
  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. /// Returns a `Server` builder configured with TLS.
  195. @available(
  196. *, deprecated,
  197. message: "Use one of 'usingTLSBackedByNIOSSL(on:certificateChain:privateKey:)', 'usingTLSBackedByNetworkFramework(on:with:)' or 'usingTLS(with:on:)'"
  198. )
  199. public static func secure(
  200. group: EventLoopGroup,
  201. certificateChain: [NIOSSLCertificate],
  202. privateKey: NIOSSLPrivateKey
  203. ) -> Builder.Secure {
  204. return Server.usingTLSBackedByNIOSSL(
  205. on: group,
  206. certificateChain: certificateChain,
  207. privateKey: privateKey
  208. )
  209. }
  210. /// Returns a `Server` builder configured with the 'NIOSSL' TLS backend.
  211. ///
  212. /// This builder may use either a `MultiThreadedEventLoopGroup` or a `NIOTSEventLoopGroup` (or an
  213. /// `EventLoop` from either group).
  214. public static func usingTLSBackedByNIOSSL(
  215. on group: EventLoopGroup,
  216. certificateChain: [NIOSSLCertificate],
  217. privateKey: NIOSSLPrivateKey
  218. ) -> Builder.Secure {
  219. return Builder.Secure(
  220. group: group,
  221. tlsConfiguration: .makeServerConfigurationBackedByNIOSSL(
  222. certificateChain: certificateChain.map { .certificate($0) },
  223. privateKey: .privateKey(privateKey)
  224. )
  225. )
  226. }
  227. #if canImport(Network)
  228. /// Returns a `Server` builder configured with the 'Network.framework' TLS backend.
  229. ///
  230. /// This builder must use a `NIOTSEventLoopGroup`.
  231. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  232. public static func usingTLSBackedByNetworkFramework(
  233. on group: EventLoopGroup,
  234. with identity: SecIdentity
  235. ) -> Builder.Secure {
  236. precondition(
  237. PlatformSupport.isTransportServicesEventLoopGroup(group),
  238. "'usingTLSBackedByNetworkFramework(on:with:)' requires 'eventLoopGroup' to be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: group))'"
  239. )
  240. return Builder.Secure(
  241. group: group,
  242. tlsConfiguration: .makeServerConfigurationBackedByNetworkFramework(identity: identity)
  243. )
  244. }
  245. #endif
  246. /// Returns a `Server` builder configured with the TLS backend appropriate for the
  247. /// provided `configuration` and `EventLoopGroup`.
  248. ///
  249. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  250. /// the the `group`.
  251. public static func usingTLS(
  252. with configuration: GRPCTLSConfiguration,
  253. on group: EventLoopGroup
  254. ) -> Builder.Secure {
  255. return Builder.Secure(group: group, tlsConfiguration: configuration)
  256. }
  257. }