main.swift 8.2 KB

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