RecordRoute.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2024, 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 GRPCNIOTransportHTTP2
  18. struct RecordRoute: AsyncParsableCommand {
  19. static let configuration = CommandConfiguration(
  20. abstract: "Records a route by visiting N randomly selected points and prints a summary of it."
  21. )
  22. @Option(help: "The server's listening port")
  23. var port: Int = 31415
  24. @Option(help: "The number of places to visit.")
  25. var points: Int = 10
  26. func run() async throws {
  27. let transport = try HTTP2ClientTransport.Posix(
  28. target: .ipv4(host: "127.0.0.1", port: self.port),
  29. config: .defaults(transportSecurity: .plaintext)
  30. )
  31. let client = GRPCClient(transport: transport)
  32. try await withThrowingDiscardingTaskGroup { group in
  33. group.addTask {
  34. try await client.run()
  35. }
  36. let routeGuide = Routeguide_RouteGuide_Client(wrapping: client)
  37. // Get all features.
  38. let rectangle = Routeguide_Rectangle.with {
  39. $0.lo.latitude = 400_000_000
  40. $0.hi.latitude = 420_000_000
  41. $0.lo.longitude = -750_000_000
  42. $0.hi.longitude = -730_000_000
  43. }
  44. let features = try await routeGuide.listFeatures(rectangle) { response in
  45. try await response.messages.reduce(into: []) { $0.append($1) }
  46. }
  47. // Pick 'N' locations to visit.
  48. let placesToVisit = features.shuffled().map { $0.location }.prefix(self.points)
  49. // Record a route.
  50. let summary = try await routeGuide.recordRoute { writer in
  51. try await writer.write(contentsOf: placesToVisit)
  52. }
  53. let text = """
  54. Visited \(summary.pointCount) points and \(summary.featureCount) features covering \
  55. a distance \(summary.distance) metres.
  56. """
  57. print(text)
  58. client.beginGracefulShutdown()
  59. }
  60. }
  61. }