main.swift 8.1 KB

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