RecordRoute.swift 2.1 KB

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