main.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. * Copyright 2019, 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 Commander
  17. import Dispatch
  18. import Foundation
  19. import NIO
  20. import NIOSSL
  21. import GRPC
  22. import GRPCSampleData
  23. // Common flags and options
  24. let sslFlag = Flag("ssl", description: "if true, use SSL for connections")
  25. func addressOption(_ address: String) -> Option<String> {
  26. return Option("address", default: address, description: "address of server")
  27. }
  28. let portOption = Option("port", default: 8080)
  29. let messageOption = Option("message",
  30. default: "Testing 1 2 3",
  31. description: "message to send")
  32. func makeClientSSLContext() throws -> NIOSSLContext {
  33. return try NIOSSLContext(configuration: makeClientTLSConfiguration())
  34. }
  35. func makeServerSSLContext() throws -> NIOSSLContext {
  36. return try NIOSSLContext(configuration: makeServerTLSConfiguration())
  37. }
  38. func makeClientTLSConfiguration() -> TLSConfiguration {
  39. let caCert = SampleCertificate.ca
  40. let clientCert = SampleCertificate.client
  41. precondition(!caCert.isExpired && !clientCert.isExpired,
  42. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift.")
  43. return .forClient(certificateVerification: .noHostnameVerification,
  44. trustRoots: .certificates([caCert.certificate]),
  45. certificateChain: [.certificate(clientCert.certificate)],
  46. privateKey: .privateKey(SamplePrivateKey.client),
  47. applicationProtocols: GRPCApplicationProtocolIdentifier.allCases.map { $0.rawValue })
  48. }
  49. func makeServerTLSConfiguration() -> TLSConfiguration {
  50. let caCert = SampleCertificate.ca
  51. let serverCert = SampleCertificate.server
  52. precondition(!caCert.isExpired && !serverCert.isExpired,
  53. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift.")
  54. return .forServer(certificateChain: [.certificate(serverCert.certificate)],
  55. privateKey: .privateKey(SamplePrivateKey.server),
  56. trustRoots: .certificates([caCert.certificate]),
  57. applicationProtocols: GRPCApplicationProtocolIdentifier.allCases.map { $0.rawValue })
  58. }
  59. /// Create en `EchoClient` and wait for it to initialize. Returns nil if initialisation fails.
  60. func makeEchoClient(address: String, port: Int, ssl: Bool) -> Echo_EchoServiceClient? {
  61. let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  62. do {
  63. let tlsConfiguration: ClientConnection.TLSConfiguration?
  64. if ssl {
  65. tlsConfiguration = .init(sslContext: try makeClientSSLContext())
  66. } else {
  67. tlsConfiguration = nil
  68. }
  69. let configuration = ClientConnection.Configuration(
  70. target: .hostAndPort(address, port),
  71. eventLoopGroup: eventLoopGroup,
  72. tlsConfiguration: tlsConfiguration)
  73. return try ClientConnection.start(configuration)
  74. .map { Echo_EchoServiceClient(connection: $0) }
  75. .wait()
  76. } catch {
  77. print("Unable to create an EchoClient: \(error)")
  78. return nil
  79. }
  80. }
  81. Group {
  82. $0.command("serve",
  83. sslFlag,
  84. addressOption("localhost"),
  85. portOption,
  86. description: "Run an echo server.") { ssl, address, port in
  87. let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  88. var configuration = Server.Configuration(
  89. target: .hostAndPort(address, port),
  90. eventLoopGroup: eventLoopGroup,
  91. serviceProviders: [EchoProvider()])
  92. if ssl {
  93. print("starting secure server")
  94. configuration.tlsConfiguration = .init(sslContext: try makeServerSSLContext())
  95. } else {
  96. print("starting insecure server")
  97. }
  98. let server = try! Server.start(configuration: configuration)
  99. .wait()
  100. // This blocks to keep the main thread from finishing while the server runs,
  101. // but the server never exits. Kill the process to stop it.
  102. try server.onClose.wait()
  103. }
  104. $0.command(
  105. "get",
  106. sslFlag,
  107. addressOption("localhost"),
  108. portOption,
  109. messageOption,
  110. description: "Perform a unary get()."
  111. ) { ssl, address, port, message in
  112. print("calling get")
  113. guard let echo = makeEchoClient(address: address, port: port, ssl: ssl) else { return }
  114. var requestMessage = Echo_EchoRequest()
  115. requestMessage.text = message
  116. print("get sending: \(requestMessage.text)")
  117. let get = echo.get(requestMessage)
  118. get.response.whenSuccess { response in
  119. print("get received: \(response.text)")
  120. }
  121. get.response.whenFailure { error in
  122. print("get response failed with error: \(error)")
  123. }
  124. // wait() on the status to stop the program from exiting.
  125. do {
  126. let status = try get.status.wait()
  127. print("get completed with status: \(status)")
  128. } catch {
  129. print("get status failed with error: \(error)")
  130. }
  131. }
  132. $0.command(
  133. "expand",
  134. sslFlag,
  135. addressOption("localhost"),
  136. portOption,
  137. messageOption,
  138. description: "Perform a server-streaming expand()."
  139. ) { ssl, address, port, message in
  140. print("calling expand")
  141. guard let echo = makeEchoClient(address: address, port: port, ssl: ssl) else { return }
  142. let requestMessage = Echo_EchoRequest.with { $0.text = message }
  143. print("expand sending: \(requestMessage.text)")
  144. let expand = echo.expand(requestMessage) { response in
  145. print("expand received: \(response.text)")
  146. }
  147. // wait() on the status to stop the program from exiting.
  148. do {
  149. let status = try expand.status.wait()
  150. print("expand completed with status: \(status)")
  151. } catch {
  152. print("expand status failed with error: \(error)")
  153. }
  154. }
  155. $0.command(
  156. "collect",
  157. sslFlag,
  158. addressOption("localhost"),
  159. portOption,
  160. messageOption,
  161. description: "Perform a client-streaming collect()."
  162. ) { ssl, address, port, message in
  163. print("calling collect")
  164. guard let echo = makeEchoClient(address: address, port: port, ssl: ssl) else { return }
  165. let collect = echo.collect()
  166. var queue = collect.newMessageQueue()
  167. for part in message.components(separatedBy: " ") {
  168. var requestMessage = Echo_EchoRequest()
  169. requestMessage.text = part
  170. print("collect sending: \(requestMessage.text)")
  171. queue = queue.flatMap { collect.sendMessage(requestMessage) }
  172. }
  173. queue.whenSuccess { collect.sendEnd(promise: nil) }
  174. collect.response.whenSuccess { respone in
  175. print("collect received: \(respone.text)")
  176. }
  177. collect.response.whenFailure { error in
  178. print("collect response failed with error: \(error)")
  179. }
  180. // wait() on the status to stop the program from exiting.
  181. do {
  182. let status = try collect.status.wait()
  183. print("collect completed with status: \(status)")
  184. } catch {
  185. print("collect status failed with error: \(error)")
  186. }
  187. }
  188. $0.command(
  189. "update",
  190. sslFlag,
  191. addressOption("localhost"),
  192. portOption,
  193. messageOption,
  194. description: "Perform a bidirectional-streaming update()."
  195. ) { ssl, address, port, message in
  196. print("calling update")
  197. guard let echo = makeEchoClient(address: address, port: port, ssl: ssl) else { return }
  198. let update = echo.update { response in
  199. print("update received: \(response.text)")
  200. }
  201. var queue = update.newMessageQueue()
  202. for part in message.components(separatedBy: " ") {
  203. var requestMessage = Echo_EchoRequest()
  204. requestMessage.text = part
  205. print("update sending: \(requestMessage.text)")
  206. queue = queue.flatMap { update.sendMessage(requestMessage) }
  207. }
  208. queue.whenSuccess { update.sendEnd(promise: nil) }
  209. // wait() on the status to stop the program from exiting.
  210. do {
  211. let status = try update.status.wait()
  212. print("update completed with status: \(status)")
  213. } catch {
  214. print("update status failed with error: \(error)")
  215. }
  216. }
  217. }.run()