RouteGuideClient.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. #if compiler(>=5.6)
  17. import ArgumentParser
  18. import Foundation
  19. import GRPC
  20. import NIOCore
  21. import NIOPosix
  22. import RouteGuideModel
  23. /// Loads the features from `route_guide_db.json`, assumed to be in the directory above this file.
  24. func loadFeatures() throws -> [Routeguide_Feature] {
  25. let url = URL(fileURLWithPath: #filePath)
  26. .deletingLastPathComponent() // main.swift
  27. .deletingLastPathComponent() // Client/
  28. .appendingPathComponent("route_guide_db.json")
  29. let data = try Data(contentsOf: url)
  30. return try Routeguide_Feature.array(fromJSONUTF8Data: data)
  31. }
  32. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  33. internal struct RouteGuideExample {
  34. private let routeGuide: Routeguide_RouteGuideAsyncClient
  35. private let features: [Routeguide_Feature]
  36. init(routeGuide: Routeguide_RouteGuideAsyncClient, features: [Routeguide_Feature]) {
  37. self.routeGuide = routeGuide
  38. self.features = features
  39. }
  40. func run() async {
  41. // Look for a valid feature.
  42. await self.getFeature(latitude: 409_146_138, longitude: -746_188_906)
  43. // Look for a missing feature.
  44. await self.getFeature(latitude: 0, longitude: 0)
  45. // Looking for features between 40, -75 and 42, -73.
  46. await self.listFeatures(
  47. lowLatitude: 400_000_000,
  48. lowLongitude: -750_000_000,
  49. highLatitude: 420_000_000,
  50. highLongitude: -730_000_000
  51. )
  52. // Record a few randomly selected points from the features file.
  53. await self.recordRoute(features: self.features, featuresToVisit: 10)
  54. // Send and receive some notes.
  55. await self.routeChat()
  56. }
  57. }
  58. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  59. extension RouteGuideExample {
  60. /// Get the feature at the given latitude and longitude, if one exists.
  61. private func getFeature(latitude: Int, longitude: Int) async {
  62. print("\n→ GetFeature: lat=\(latitude) lon=\(longitude)")
  63. let point: Routeguide_Point = .with {
  64. $0.latitude = numericCast(latitude)
  65. $0.longitude = numericCast(longitude)
  66. }
  67. do {
  68. let feature = try await self.routeGuide.getFeature(point)
  69. if !feature.name.isEmpty {
  70. print("Found feature called '\(feature.name)' at \(feature.location)")
  71. } else {
  72. print("Found no feature at \(feature.location)")
  73. }
  74. } catch {
  75. print("RPC failed: \(error)")
  76. }
  77. }
  78. /// List all features in the area bounded by the high and low latitude and longitudes.
  79. private func listFeatures(
  80. lowLatitude: Int,
  81. lowLongitude: Int,
  82. highLatitude: Int,
  83. highLongitude: Int
  84. ) async {
  85. print(
  86. "\n→ ListFeatures: lowLat=\(lowLatitude) lowLon=\(lowLongitude), hiLat=\(highLatitude) hiLon=\(highLongitude)"
  87. )
  88. let rectangle: Routeguide_Rectangle = .with {
  89. $0.lo = .with {
  90. $0.latitude = numericCast(lowLatitude)
  91. $0.longitude = numericCast(lowLongitude)
  92. }
  93. $0.hi = .with {
  94. $0.latitude = numericCast(highLatitude)
  95. $0.longitude = numericCast(highLongitude)
  96. }
  97. }
  98. do {
  99. var resultCount = 1
  100. for try await feature in self.routeGuide.listFeatures(rectangle) {
  101. print("Result #\(resultCount): \(feature)")
  102. resultCount += 1
  103. }
  104. } catch {
  105. print("RPC failed: \(error)")
  106. }
  107. }
  108. /// Record a route for `featuresToVisit` features selected randomly from `features` and print a
  109. /// summary of the route.
  110. private func recordRoute(
  111. features: [Routeguide_Feature],
  112. featuresToVisit: Int
  113. ) async {
  114. print("\n→ RecordRoute")
  115. let recordRoute = self.routeGuide.makeRecordRouteCall()
  116. do {
  117. for i in 1 ... featuresToVisit {
  118. if let feature = features.randomElement() {
  119. let point = feature.location
  120. print("Visiting point #\(i) at \(point)")
  121. try await recordRoute.requestStream.send(point)
  122. // Sleep for 0.2s ... 1.0s before sending the next point.
  123. try await Task.sleep(nanoseconds: UInt64.random(in: UInt64(2e8) ... UInt64(1e9)))
  124. }
  125. }
  126. recordRoute.requestStream.finish()
  127. let summary = try await recordRoute.response
  128. print(
  129. "Finished trip with \(summary.pointCount) points. Passed \(summary.featureCount) features. " +
  130. "Travelled \(summary.distance) meters. It took \(summary.elapsedTime) seconds."
  131. )
  132. } catch {
  133. print("RecordRoute Failed: \(error)")
  134. }
  135. }
  136. /// Record notes at given locations, printing each all other messages which have previously been
  137. /// recorded at the same location.
  138. private func routeChat() async {
  139. print("\n→ RouteChat")
  140. let notes = [
  141. ("First message", 0, 0),
  142. ("Second message", 0, 1),
  143. ("Third message", 1, 0),
  144. ("Fourth message", 1, 1),
  145. ].map { message, latitude, longitude in
  146. Routeguide_RouteNote.with {
  147. $0.message = message
  148. $0.location = .with {
  149. $0.latitude = Int32(latitude)
  150. $0.longitude = Int32(longitude)
  151. }
  152. }
  153. }
  154. do {
  155. try await withThrowingTaskGroup(of: Void.self) { group in
  156. let routeChat = self.routeGuide.makeRouteChatCall()
  157. // Add a task to send each message adding a small sleep between each.
  158. group.addTask {
  159. for note in notes {
  160. print("Sending message '\(note.message)' at \(note.location)")
  161. try await routeChat.requestStream.send(note)
  162. // Sleep for 0.2s ... 1.0s before sending the next note.
  163. try await Task.sleep(nanoseconds: UInt64.random(in: UInt64(2e8) ... UInt64(1e9)))
  164. }
  165. routeChat.requestStream.finish()
  166. }
  167. // Add a task to print each message received on the response stream.
  168. group.addTask {
  169. for try await note in routeChat.responseStream {
  170. print("Received message '\(note.message)' at \(note.location)")
  171. }
  172. }
  173. try await group.waitForAll()
  174. }
  175. } catch {
  176. print("RouteChat Failed: \(error)")
  177. }
  178. }
  179. }
  180. @main
  181. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  182. struct RouteGuide: AsyncParsableCommand {
  183. @Option(help: "The port to connect to")
  184. var port: Int = 1234
  185. func run() async throws {
  186. // Load the features.
  187. let features = try loadFeatures()
  188. let group = PlatformSupport.makeEventLoopGroup(loopCount: 1)
  189. defer {
  190. try? group.syncShutdownGracefully()
  191. }
  192. let channel = try GRPCChannelPool.with(
  193. target: .host("localhost", port: self.port),
  194. transportSecurity: .plaintext,
  195. eventLoopGroup: group
  196. )
  197. defer {
  198. try? channel.close().wait()
  199. }
  200. let routeGuide = Routeguide_RouteGuideAsyncClient(channel: channel)
  201. let example = RouteGuideExample(routeGuide: routeGuide, features: features)
  202. await example.run()
  203. }
  204. }
  205. extension Routeguide_Point: CustomStringConvertible {
  206. public var description: String {
  207. return "(\(self.latitude), \(self.longitude))"
  208. }
  209. }
  210. extension Routeguide_Feature: CustomStringConvertible {
  211. public var description: String {
  212. return "\(self.name) at \(self.location)"
  213. }
  214. }
  215. #else
  216. @main
  217. enum NotAvailable {
  218. static func main() {
  219. print("This example requires Swift >= 5.6")
  220. }
  221. }
  222. #endif // compiler(>=5.6)