ServerBuilder.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 NIO
  18. import NIOSSL
  19. extension Server {
  20. public class Builder {
  21. private var configuration: Server.Configuration
  22. private var maybeTLS: Server.Configuration.TLS? { return nil }
  23. fileprivate init(group: EventLoopGroup) {
  24. self.configuration = .default(
  25. // This is okay: the configuration is only consumed on a call to `bind` which sets the host
  26. // and port.
  27. target: .hostAndPort("", .max),
  28. eventLoopGroup: group,
  29. serviceProviders: []
  30. )
  31. }
  32. public class Secure: Builder {
  33. private var tls: Server.Configuration.TLS
  34. override var maybeTLS: Server.Configuration.TLS? {
  35. return self.tls
  36. }
  37. fileprivate init(
  38. group: EventLoopGroup,
  39. certificateChain: [NIOSSLCertificate],
  40. privateKey: NIOSSLPrivateKey
  41. ) {
  42. self.tls = .init(
  43. certificateChain: certificateChain.map { .certificate($0) },
  44. privateKey: .privateKey(privateKey)
  45. )
  46. super.init(group: group)
  47. }
  48. }
  49. public func bind(host: String, port: Int) -> EventLoopFuture<Server> {
  50. // Finish setting up the configuration.
  51. self.configuration.target = .hostAndPort(host, port)
  52. self.configuration.tls = self.maybeTLS
  53. return Server.start(configuration: self.configuration)
  54. }
  55. }
  56. }
  57. extension Server.Builder {
  58. /// Sets the server error delegate.
  59. @discardableResult
  60. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  61. self.configuration.errorDelegate = delegate
  62. return self
  63. }
  64. }
  65. extension Server.Builder {
  66. /// Sets the service providers that this server should offer. Note that calling this multiple
  67. /// times will override any previously set providers.
  68. @discardableResult
  69. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  70. self.configuration.serviceProviders = providers
  71. return self
  72. }
  73. }
  74. extension Server.Builder {
  75. @discardableResult
  76. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  77. self.configuration.connectionKeepalive = keepalive
  78. return self
  79. }
  80. }
  81. extension Server.Builder {
  82. /// The amount of time to wait before closing connections. The idle timeout will start only
  83. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  84. /// an idle timeout it set connections will not be idled by default.
  85. @discardableResult
  86. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  87. self.configuration.connectionIdleTimeout = timeout
  88. return self
  89. }
  90. }
  91. extension Server.Builder {
  92. /// Sets the message compression configuration. Compression is disabled if this is not configured
  93. /// and any RPCs using compression will not be accepted.
  94. @discardableResult
  95. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  96. self.configuration.messageEncoding = encoding
  97. return self
  98. }
  99. /// Sets the maximum message size in bytes the server may receive.
  100. ///
  101. /// - Precondition: `limit` must not be negative.
  102. @discardableResult
  103. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  104. self.configuration.maximumReceiveMessageLength = limit
  105. return self
  106. }
  107. }
  108. extension Server.Builder.Secure {
  109. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  110. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  111. /// not set.
  112. @discardableResult
  113. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  114. self.tls.trustRoots = trustRoots
  115. return self
  116. }
  117. /// Sets whether certificates should be verified. Defaults to `.none` if not set.
  118. @discardableResult
  119. public func withTLS(certificateVerification: CertificateVerification) -> Self {
  120. self.tls.certificateVerification = certificateVerification
  121. return self
  122. }
  123. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  124. /// defaults to `true` if not otherwise set.
  125. ///
  126. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  127. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  128. /// is being used and configure the connection appropriately.
  129. @discardableResult
  130. public func withTLS(requiringALPN: Bool) -> Self {
  131. self.tls.requireALPN = requiringALPN
  132. return self
  133. }
  134. }
  135. extension Server.Builder {
  136. /// Sets the HTTP/2 flow control target window size. Defaults to 65,535 if not explicitly set.
  137. @discardableResult
  138. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  139. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  140. return self
  141. }
  142. }
  143. extension Server.Builder {
  144. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  145. /// each connection will use a logger branched from the connections logger. This logger is made
  146. /// available to service providers via `context`. Defaults to a no-op logger.
  147. @discardableResult
  148. public func withLogger(_ logger: Logger) -> Self {
  149. self.configuration.logger = logger
  150. return self
  151. }
  152. }
  153. extension Server.Builder {
  154. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  155. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  156. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  157. ///
  158. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  159. /// be invoked at most once per accepted connection.
  160. @discardableResult
  161. public func withDebugChannelInitializer(
  162. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  163. ) -> Self {
  164. self.configuration.debugChannelInitializer = debugChannelInitializer
  165. return self
  166. }
  167. }
  168. extension Server {
  169. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  170. public static func insecure(group: EventLoopGroup) -> Builder {
  171. return Builder(group: group)
  172. }
  173. /// Returns a `Server` builder configured with TLS.
  174. public static func secure(
  175. group: EventLoopGroup,
  176. certificateChain: [NIOSSLCertificate],
  177. privateKey: NIOSSLPrivateKey
  178. ) -> Builder.Secure {
  179. return Builder.Secure(
  180. group: group,
  181. certificateChain: certificateChain,
  182. privateKey: privateKey
  183. )
  184. }
  185. }