RecordRoute.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. let transport = try HTTP2ClientTransport.Posix(
  29. target: .ipv4(host: "127.0.0.1", port: self.port),
  30. transportSecurity: .plaintext
  31. )
  32. let client = GRPCClient(transport: transport)
  33. try await withThrowingDiscardingTaskGroup { group in
  34. group.addTask {
  35. try await client.run()
  36. }
  37. let routeGuide = Routeguide_RouteGuide.Client(wrapping: client)
  38. // Get all features.
  39. let rectangle = Routeguide_Rectangle.with {
  40. $0.lo.latitude = 400_000_000
  41. $0.hi.latitude = 420_000_000
  42. $0.lo.longitude = -750_000_000
  43. $0.hi.longitude = -730_000_000
  44. }
  45. let features = try await routeGuide.listFeatures(rectangle) { response in
  46. try await response.messages.reduce(into: []) { $0.append($1) }
  47. }
  48. // Pick 'N' locations to visit.
  49. let placesToVisit = features.shuffled().map { $0.location }.prefix(self.points)
  50. // Record a route.
  51. let summary = try await routeGuide.recordRoute { writer in
  52. try await writer.write(contentsOf: placesToVisit)
  53. }
  54. let text = """
  55. Visited \(summary.pointCount) points and \(summary.featureCount) features covering \
  56. a distance \(summary.distance) metres.
  57. """
  58. print(text)
  59. client.beginGracefulShutdown()
  60. }
  61. }
  62. }