main.swift 8.3 KB

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