main.swift 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 GRPC
  20. import GRPCSampleData
  21. import Logging
  22. import NIOCore
  23. import NIOPosix
  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. @Option(help: "How many RPCs to do.")
  70. var iterations: Int = 1
  71. @Argument(help: "Message to echo")
  72. var message: String
  73. func run() throws {
  74. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  75. defer {
  76. try! group.syncShutdownGracefully()
  77. }
  78. let client = try makeClient(
  79. group: group,
  80. port: self.port,
  81. useTLS: self.tls,
  82. useInterceptor: self.intercept
  83. )
  84. defer {
  85. try! client.channel.close().wait()
  86. }
  87. for _ in 0 ..< self.iterations {
  88. callRPC(self.rpc, using: client, message: self.message)
  89. }
  90. }
  91. }
  92. }
  93. // MARK: - Server / Client
  94. func startEchoServer(group: EventLoopGroup, port: Int, useTLS: Bool) throws {
  95. let builder: Server.Builder
  96. if useTLS {
  97. // We're using some self-signed certs here: check they aren't expired.
  98. let caCert = SampleCertificate.ca
  99. let serverCert = SampleCertificate.server
  100. precondition(
  101. !caCert.isExpired && !serverCert.isExpired,
  102. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift."
  103. )
  104. builder = Server.usingTLSBackedByNIOSSL(
  105. on: group,
  106. certificateChain: [serverCert.certificate],
  107. privateKey: SamplePrivateKey.server
  108. )
  109. .withTLS(trustRoots: .certificates([caCert.certificate]))
  110. print("starting secure server")
  111. } else {
  112. print("starting insecure server")
  113. builder = Server.insecure(group: group)
  114. }
  115. let server = try builder.withServiceProviders([EchoProvider()])
  116. .bind(host: "localhost", port: port)
  117. .wait()
  118. print("started server: \(server.channel.localAddress!)")
  119. // This blocks to keep the main thread from finishing while the server runs,
  120. // but the server never exits. Kill the process to stop it.
  121. try server.onClose.wait()
  122. }
  123. func makeClient(
  124. group: EventLoopGroup,
  125. port: Int,
  126. useTLS: Bool,
  127. useInterceptor: Bool
  128. ) throws -> Echo_EchoClient {
  129. let security: GRPCChannelPool.Configuration.TransportSecurity
  130. if useTLS {
  131. // We're using some self-signed certs here: check they aren't expired.
  132. let caCert = SampleCertificate.ca
  133. let clientCert = SampleCertificate.client
  134. precondition(
  135. !caCert.isExpired && !clientCert.isExpired,
  136. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift."
  137. )
  138. let tlsConfiguration = GRPCTLSConfiguration.makeServerConfigurationBackedByNIOSSL(
  139. certificateChain: [.certificate(clientCert.certificate)],
  140. privateKey: .privateKey(SamplePrivateKey.client),
  141. trustRoots: .certificates([caCert.certificate])
  142. )
  143. security = .tls(tlsConfiguration)
  144. } else {
  145. security = .plaintext
  146. }
  147. let channel = try GRPCChannelPool.with(
  148. target: .host("localhost", port: port),
  149. transportSecurity: security,
  150. eventLoopGroup: group
  151. )
  152. return Echo_EchoClient(
  153. channel: channel,
  154. interceptors: useInterceptor ? ExampleClientInterceptorFactory() : nil
  155. )
  156. }
  157. func callRPC(_ rpc: RPC, using client: Echo_EchoClient, message: String) {
  158. do {
  159. switch rpc {
  160. case .get:
  161. try echoGet(client: client, message: message)
  162. case .collect:
  163. try echoCollect(client: client, message: message)
  164. case .expand:
  165. try echoExpand(client: client, message: message)
  166. case .update:
  167. try echoUpdate(client: client, message: message)
  168. }
  169. } catch {
  170. print("\(rpc) RPC failed: \(error)")
  171. }
  172. }
  173. func echoGet(client: Echo_EchoClient, message: String) throws {
  174. // Get is a unary call.
  175. let get = client.get(.with { $0.text = message })
  176. // Register a callback for the response:
  177. get.response.whenComplete { result in
  178. switch result {
  179. case let .success(response):
  180. print("get receieved: \(response.text)")
  181. case let .failure(error):
  182. print("get failed with error: \(error)")
  183. }
  184. }
  185. // wait() for the call to terminate
  186. let status = try get.status.wait()
  187. print("get completed with status: \(status.code)")
  188. }
  189. func echoCollect(client: Echo_EchoClient, message: String) throws {
  190. // Collect is a client streaming call
  191. let collect = client.collect()
  192. // Split the messages and map them into requests
  193. let messages = message.components(separatedBy: " ").map { part in
  194. Echo_EchoRequest.with { $0.text = part }
  195. }
  196. // Stream the to the service (this can also be done on individual requests using `sendMessage`).
  197. collect.sendMessages(messages, promise: nil)
  198. // Close the request stream.
  199. collect.sendEnd(promise: nil)
  200. // Register a callback for the response:
  201. collect.response.whenComplete { result in
  202. switch result {
  203. case let .success(response):
  204. print("collect receieved: \(response.text)")
  205. case let .failure(error):
  206. print("collect failed with error: \(error)")
  207. }
  208. }
  209. // wait() for the call to terminate
  210. let status = try collect.status.wait()
  211. print("collect completed with status: \(status.code)")
  212. }
  213. func echoExpand(client: Echo_EchoClient, message: String) throws {
  214. // Expand is a server streaming call; provide a response handler.
  215. let expand = client.expand(.with { $0.text = message }) { response in
  216. print("expand received: \(response.text)")
  217. }
  218. // wait() for the call to terminate
  219. let status = try expand.status.wait()
  220. print("expand completed with status: \(status.code)")
  221. }
  222. func echoUpdate(client: Echo_EchoClient, message: String) throws {
  223. // Update is a bidirectional streaming call; provide a response handler.
  224. let update = client.update { response in
  225. print("update received: \(response.text)")
  226. }
  227. // Split the messages and map them into requests
  228. let messages = message.components(separatedBy: " ").map { part in
  229. Echo_EchoRequest.with { $0.text = part }
  230. }
  231. // Stream the to the service (this can also be done on individual requests using `sendMessage`).
  232. update.sendMessages(messages, promise: nil)
  233. // Close the request stream.
  234. update.sendEnd(promise: nil)
  235. // wait() for the call to terminate
  236. let status = try update.status.wait()
  237. print("update completed with status: \(status.code)")
  238. }
  239. Echo.main()