Echo.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /*
  2. * Copyright 2021, 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 NIOCore
  22. import NIOPosix
  23. #if canImport(NIOSSL)
  24. import NIOSSL
  25. #endif
  26. // MARK: - Argument parsing
  27. enum RPC: String, ExpressibleByArgument {
  28. case get
  29. case collect
  30. case expand
  31. case update
  32. }
  33. @main
  34. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  35. struct Echo: AsyncParsableCommand {
  36. static var configuration = CommandConfiguration(
  37. abstract: "An example to run and call a simple gRPC service for echoing messages.",
  38. subcommands: [Server.self, Client.self]
  39. )
  40. struct Server: AsyncParsableCommand {
  41. static var configuration = CommandConfiguration(
  42. abstract: "Start a gRPC server providing the Echo service."
  43. )
  44. @Option(help: "The port to listen on for new connections")
  45. var port = 1234
  46. @Flag(help: "Whether TLS should be used or not")
  47. var tls = false
  48. func run() async throws {
  49. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  50. defer {
  51. try! group.syncShutdownGracefully()
  52. }
  53. do {
  54. try await startEchoServer(group: group, port: self.port, useTLS: self.tls)
  55. } catch {
  56. print("Error running server: \(error)")
  57. }
  58. }
  59. }
  60. struct Client: AsyncParsableCommand {
  61. static var configuration = CommandConfiguration(
  62. abstract: "Calls an RPC on the Echo server."
  63. )
  64. @Option(help: "The port to connect to")
  65. var port = 1234
  66. @Flag(help: "Whether TLS should be used or not")
  67. var tls = false
  68. @Flag(help: "Whether interceptors should be used, see 'docs/interceptors-tutorial.md'.")
  69. var intercept = false
  70. @Option(help: "RPC to call ('get', 'collect', 'expand', 'update').")
  71. var rpc: RPC = .get
  72. @Option(help: "How many RPCs to do.")
  73. var iterations: Int = 1
  74. @Argument(help: "Message to echo")
  75. var message: String
  76. func run() async throws {
  77. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  78. defer {
  79. try! group.syncShutdownGracefully()
  80. }
  81. let client = makeClient(
  82. group: group,
  83. port: self.port,
  84. useTLS: self.tls,
  85. useInterceptor: self.intercept
  86. )
  87. defer {
  88. try! client.channel.close().wait()
  89. }
  90. for _ in 0 ..< self.iterations {
  91. await callRPC(self.rpc, using: client, message: self.message)
  92. }
  93. }
  94. }
  95. }
  96. // MARK: - Server
  97. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  98. func startEchoServer(group: EventLoopGroup, port: Int, useTLS: Bool) async throws {
  99. let builder: Server.Builder
  100. if useTLS {
  101. #if canImport(NIOSSL)
  102. // We're using some self-signed certs here: check they aren't expired.
  103. let caCert = SampleCertificate.ca
  104. let serverCert = SampleCertificate.server
  105. precondition(
  106. !caCert.isExpired && !serverCert.isExpired,
  107. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift."
  108. )
  109. builder = Server.usingTLSBackedByNIOSSL(
  110. on: group,
  111. certificateChain: [serverCert.certificate],
  112. privateKey: SamplePrivateKey.server
  113. )
  114. .withTLS(trustRoots: .certificates([caCert.certificate]))
  115. print("starting secure server")
  116. #else
  117. fatalError("'useTLS: true' passed to \(#function) but NIOSSL is not available")
  118. #endif // canImport(NIOSSL)
  119. } else {
  120. print("starting insecure server")
  121. builder = Server.insecure(group: group)
  122. }
  123. let server = try await builder.withServiceProviders([EchoAsyncProvider()])
  124. .bind(host: "localhost", port: port)
  125. .get()
  126. print("started server: \(server.channel.localAddress!)")
  127. // This blocks to keep the main thread from finishing while the server runs,
  128. // but the server never exits. Kill the process to stop it.
  129. try await server.onClose.get()
  130. }
  131. // MARK: - Client
  132. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  133. func makeClient(
  134. group: EventLoopGroup,
  135. port: Int,
  136. useTLS: Bool,
  137. useInterceptor: Bool
  138. ) -> Echo_EchoAsyncClient {
  139. let builder: ClientConnection.Builder
  140. if useTLS {
  141. #if canImport(NIOSSL)
  142. // We're using some self-signed certs here: check they aren't expired.
  143. let caCert = SampleCertificate.ca
  144. let clientCert = SampleCertificate.client
  145. precondition(
  146. !caCert.isExpired && !clientCert.isExpired,
  147. "SSL certificates are expired. Please submit an issue at https://github.com/grpc/grpc-swift."
  148. )
  149. builder = ClientConnection.usingTLSBackedByNIOSSL(on: group)
  150. .withTLS(certificateChain: [clientCert.certificate])
  151. .withTLS(privateKey: SamplePrivateKey.client)
  152. .withTLS(trustRoots: .certificates([caCert.certificate]))
  153. #else
  154. fatalError("'useTLS: true' passed to \(#function) but NIOSSL is not available")
  155. #endif // canImport(NIOSSL)
  156. } else {
  157. builder = ClientConnection.insecure(group: group)
  158. }
  159. // Start the connection and create the client:
  160. let connection = builder.connect(host: "localhost", port: port)
  161. return Echo_EchoAsyncClient(
  162. channel: connection,
  163. interceptors: useInterceptor ? ExampleClientInterceptorFactory() : nil
  164. )
  165. }
  166. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  167. func callRPC(_ rpc: RPC, using client: Echo_EchoAsyncClient, message: String) async {
  168. do {
  169. switch rpc {
  170. case .get:
  171. try await echoGet(client: client, message: message)
  172. case .collect:
  173. try await echoCollect(client: client, message: message)
  174. case .expand:
  175. try await echoExpand(client: client, message: message)
  176. case .update:
  177. try await echoUpdate(client: client, message: message)
  178. }
  179. } catch {
  180. print("\(rpc) RPC failed: \(error)")
  181. }
  182. }
  183. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  184. func echoGet(client: Echo_EchoAsyncClient, message: String) async throws {
  185. let response = try await client.get(.with { $0.text = message })
  186. print("get received: \(response.text)")
  187. }
  188. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  189. func echoCollect(client: Echo_EchoAsyncClient, message: String) async throws {
  190. let messages = message.components(separatedBy: " ").map { part in
  191. Echo_EchoRequest.with { $0.text = part }
  192. }
  193. let response = try await client.collect(messages)
  194. print("collect received: \(response.text)")
  195. }
  196. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  197. func echoExpand(client: Echo_EchoAsyncClient, message: String) async throws {
  198. for try await response in client.expand((.with { $0.text = message })) {
  199. print("expand received: \(response.text)")
  200. }
  201. }
  202. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  203. func echoUpdate(client: Echo_EchoAsyncClient, message: String) async throws {
  204. let requests = message.components(separatedBy: " ").map { word in
  205. Echo_EchoRequest.with { $0.text = word }
  206. }
  207. for try await response in client.update(requests) {
  208. print("update received: \(response.text)")
  209. }
  210. }