ServerBuilder.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 NIO
  17. import NIOSSL
  18. import Logging
  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 = Configuration(
  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(group: EventLoopGroup, certificateChain: [NIOSSLCertificate], privateKey: NIOSSLPrivateKey) {
  38. self.tls = .init(
  39. certificateChain: certificateChain.map { .certificate($0) },
  40. privateKey: .privateKey(privateKey)
  41. )
  42. super.init(group: group)
  43. }
  44. }
  45. public func bind(host: String, port: Int) -> EventLoopFuture<Server> {
  46. // Finish setting up the configuration.
  47. self.configuration.target = .hostAndPort(host, port)
  48. self.configuration.tls = self.maybeTLS
  49. return Server.start(configuration: self.configuration)
  50. }
  51. }
  52. }
  53. extension Server.Builder {
  54. /// Sets the server error delegate.
  55. @discardableResult
  56. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  57. self.configuration.errorDelegate = delegate
  58. return self
  59. }
  60. }
  61. extension Server.Builder {
  62. /// Sets the service providers that this server should offer. Note that calling this multiple
  63. /// times will override any previously set providers.
  64. @discardableResult
  65. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  66. self.configuration.serviceProviders = providers
  67. return self
  68. }
  69. }
  70. extension Server.Builder {
  71. @discardableResult
  72. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  73. self.configuration.connectionKeepalive = keepalive
  74. return self
  75. }
  76. }
  77. extension Server.Builder {
  78. /// The amount of time to wait before closing connections. The idle timeout will start only
  79. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Defaults to
  80. /// 5 minutes if not set.
  81. @discardableResult
  82. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  83. self.configuration.connectionIdleTimeout = timeout
  84. return self
  85. }
  86. }
  87. extension Server.Builder {
  88. /// Sets the message compression configuration. Compression is disabled if this is not configured
  89. /// and any RPCs using compression will not be accepted.
  90. @discardableResult
  91. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  92. self.configuration.messageEncoding = encoding
  93. return self
  94. }
  95. }
  96. extension Server.Builder.Secure {
  97. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  98. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  99. /// not set.
  100. @discardableResult
  101. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  102. self.tls.trustRoots = trustRoots
  103. return self
  104. }
  105. /// Sets whether certificates should be verified. Defaults to `.none` if not set.
  106. @discardableResult
  107. public func withTLS(certificateVerification: CertificateVerification) -> Self {
  108. self.tls.certificateVerification = certificateVerification
  109. return self
  110. }
  111. }
  112. extension Server.Builder {
  113. /// Sets the HTTP/2 flow control target window size. Defaults to 65,535 if not explicitly set.
  114. @discardableResult
  115. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  116. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  117. return self
  118. }
  119. }
  120. extension Server.Builder {
  121. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  122. /// each connection will use a logger branched from the connections logger. This logger is made
  123. /// available to service providers via `context`. Defaults to a no-op logger.
  124. @discardableResult
  125. public func withLogger(_ logger: Logger) -> Self {
  126. self.configuration.logger = logger
  127. return self
  128. }
  129. }
  130. extension Server.Builder {
  131. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  132. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  133. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  134. ///
  135. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  136. /// be invoked at most once per accepted connection.
  137. @discardableResult
  138. public func withDebugChannelInitializer(
  139. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  140. ) -> Self {
  141. self.configuration.debugChannelInitializer = debugChannelInitializer
  142. return self
  143. }
  144. }
  145. extension Server {
  146. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  147. public static func insecure(group: EventLoopGroup) -> Builder {
  148. return Builder(group: group)
  149. }
  150. /// Returns a `Server` builder configured with TLS.
  151. public static func secure(
  152. group: EventLoopGroup,
  153. certificateChain: [NIOSSLCertificate],
  154. privateKey: NIOSSLPrivateKey
  155. ) -> Builder.Secure {
  156. return Builder.Secure(
  157. group: group,
  158. certificateChain: certificateChain,
  159. privateKey: privateKey
  160. )
  161. }
  162. }