main.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 ArgumentParser
  17. import EchoImplementation
  18. import EchoModel
  19. import Foundation
  20. import GRPC
  21. import GRPCSampleData
  22. import Logging
  23. import NIO
  24. import NIOSSL
  25. // MARK: - Argument parsing
  26. enum RPC: String, ExpressibleByArgument {
  27. case get
  28. case collect
  29. case expand
  30. case update
  31. }
  32. struct Echo: ParsableCommand {
  33. static var configuration = CommandConfiguration(
  34. abstract: "An example to run and call a simple gRPC service for echoing messages.",
  35. subcommands: [Server.self, Client.self]
  36. )
  37. struct Server: ParsableCommand {
  38. static var configuration = CommandConfiguration(
  39. abstract: "Start a gRPC server providing the Echo service."
  40. )
  41. @Option(help: "The port to listen on for new connections")
  42. var port = 1234
  43. @Flag(help: "Whether TLS should be used or not")
  44. var tls = false
  45. func run() throws {
  46. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  47. defer {
  48. try! group.syncShutdownGracefully()
  49. }
  50. do {
  51. try startEchoServer(group: group, port: self.port, useTLS: self.tls)
  52. } catch {
  53. print("Error running server: \(error)")
  54. }
  55. }
  56. }
  57. struct Client: ParsableCommand {
  58. static var configuration = CommandConfiguration(
  59. abstract: "Calls an RPC on the Echo server."
  60. )
  61. @Option(help: "The port to connect to")
  62. var port = 1234
  63. @Flag(help: "Whether TLS should be used or not")
  64. var tls = false
  65. @Flag(help: "Whether interceptors should be used, see 'docs/interceptors-tutorial.md'.")
  66. var intercept = false
  67. @Option(help: "RPC to call ('get', 'collect', 'expand', 'update').")
  68. var rpc: RPC = .get
  69. @Argument(help: "Message to echo")
  70. var message: String
  71. func run() throws {
  72. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  73. defer {
  74. try! group.syncShutdownGracefully()
  75. }
  76. let client = makeClient(
  77. group: group,
  78. port: self.port,
  79. useTLS: self.tls,
  80. useInterceptor: self.intercept
  81. )
  82. defer {
  83. try! client.channel.close().wait()
  84. }
  85. callRPC(self.rpc, using: client, message: self.message)
  86. }
  87. }
  88. }
  89. // MARK: - Server / Client
  90. func startEchoServer(group: EventLoopGroup, port: Int, useTLS: Bool) throws {
  91. let builder: Server.Builder
  92. if useTLS {
  93. // We're using some self-signed certs here: check they aren't expired.
  94. let caCert = SampleCertificate.ca
  95. let serverCert = SampleCertificate.server
  96. precondition(
  97. !caCert.isExpired && !serverCert.isExpired,
  98. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift."
  99. )
  100. builder = Server.secure(
  101. group: group,
  102. certificateChain: [serverCert.certificate],
  103. privateKey: SamplePrivateKey.server
  104. )
  105. .withTLS(trustRoots: .certificates([caCert.certificate]))
  106. print("starting secure server")
  107. } else {
  108. print("starting insecure server")
  109. builder = Server.insecure(group: group)
  110. }
  111. let server = try builder.withServiceProviders([EchoProvider()])
  112. .bind(host: "localhost", port: port)
  113. .wait()
  114. print("started server: \(server.channel.localAddress!)")
  115. // This blocks to keep the main thread from finishing while the server runs,
  116. // but the server never exits. Kill the process to stop it.
  117. try server.onClose.wait()
  118. }
  119. func makeClient(
  120. group: EventLoopGroup,
  121. port: Int,
  122. useTLS: Bool,
  123. useInterceptor: Bool
  124. ) -> Echo_EchoClient {
  125. let builder: ClientConnection.Builder
  126. if useTLS {
  127. // We're using some self-signed certs here: check they aren't expired.
  128. let caCert = SampleCertificate.ca
  129. let clientCert = SampleCertificate.client
  130. precondition(
  131. !caCert.isExpired && !clientCert.isExpired,
  132. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift."
  133. )
  134. builder = ClientConnection.secure(group: group)
  135. .withTLS(certificateChain: [clientCert.certificate])
  136. .withTLS(privateKey: SamplePrivateKey.client)
  137. .withTLS(trustRoots: .certificates([caCert.certificate]))
  138. } else {
  139. builder = ClientConnection.insecure(group: group)
  140. }
  141. // Start the connection and create the client:
  142. let connection = builder.connect(host: "localhost", port: port)
  143. return Echo_EchoClient(
  144. channel: connection,
  145. interceptors: useInterceptor ? ExampleClientInterceptorFactory() : nil
  146. )
  147. }
  148. func callRPC(_ rpc: RPC, using client: Echo_EchoClient, message: String) {
  149. do {
  150. switch rpc {
  151. case .get:
  152. try echoGet(client: client, message: message)
  153. case .collect:
  154. try echoCollect(client: client, message: message)
  155. case .expand:
  156. try echoExpand(client: client, message: message)
  157. case .update:
  158. try echoUpdate(client: client, message: message)
  159. }
  160. } catch {
  161. print("\(rpc) RPC failed: \(error)")
  162. }
  163. }
  164. func echoGet(client: Echo_EchoClient, message: String) throws {
  165. // Get is a unary call.
  166. let get = client.get(.with { $0.text = message })
  167. // Register a callback for the response:
  168. get.response.whenComplete { result in
  169. switch result {
  170. case let .success(response):
  171. print("get receieved: \(response.text)")
  172. case let .failure(error):
  173. print("get failed with error: \(error)")
  174. }
  175. }
  176. // wait() for the call to terminate
  177. let status = try get.status.wait()
  178. print("get completed with status: \(status.code)")
  179. }
  180. func echoCollect(client: Echo_EchoClient, message: String) throws {
  181. // Collect is a client streaming call
  182. let collect = client.collect()
  183. // Split the messages and map them into requests
  184. let messages = message.components(separatedBy: " ").map { part in
  185. Echo_EchoRequest.with { $0.text = part }
  186. }
  187. // Stream the to the service (this can also be done on individual requests using `sendMessage`).
  188. collect.sendMessages(messages, promise: nil)
  189. // Close the request stream.
  190. collect.sendEnd(promise: nil)
  191. // Register a callback for the response:
  192. collect.response.whenComplete { result in
  193. switch result {
  194. case let .success(response):
  195. print("collect receieved: \(response.text)")
  196. case let .failure(error):
  197. print("collect failed with error: \(error)")
  198. }
  199. }
  200. // wait() for the call to terminate
  201. let status = try collect.status.wait()
  202. print("collect completed with status: \(status.code)")
  203. }
  204. func echoExpand(client: Echo_EchoClient, message: String) throws {
  205. // Expand is a server streaming call; provide a response handler.
  206. let expand = client.expand(.with { $0.text = message }) { response in
  207. print("expand received: \(response.text)")
  208. }
  209. // wait() for the call to terminate
  210. let status = try expand.status.wait()
  211. print("expand completed with status: \(status.code)")
  212. }
  213. func echoUpdate(client: Echo_EchoClient, message: String) throws {
  214. // Update is a bidirectional streaming call; provide a response handler.
  215. let update = client.update { response in
  216. print("update received: \(response.text)")
  217. }
  218. // Split the messages and map them into requests
  219. let messages = message.components(separatedBy: " ").map { part in
  220. Echo_EchoRequest.with { $0.text = part }
  221. }
  222. // Stream the to the service (this can also be done on individual requests using `sendMessage`).
  223. update.sendMessages(messages, promise: nil)
  224. // Close the request stream.
  225. update.sendEnd(promise: nil)
  226. // wait() for the call to terminate
  227. let status = try update.status.wait()
  228. print("update completed with status: \(status.code)")
  229. }
  230. Echo.main()