main.swift 7.9 KB

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