main.swift 8.4 KB

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