RouteGuideProvider.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. import Foundation
  17. import GRPC
  18. import NIO
  19. import NIOConcurrencyHelpers
  20. import RouteGuideModel
  21. class RouteGuideProvider: Routeguide_RouteGuideProvider {
  22. private let features: [Routeguide_Feature]
  23. private var notes: [Routeguide_Point: [Routeguide_RouteNote]] = [:]
  24. private var lock = Lock()
  25. init(features: [Routeguide_Feature]) {
  26. self.features = features
  27. }
  28. /// A simple RPC.
  29. ///
  30. /// Obtains the feature at a given position.
  31. ///
  32. /// A feature with an empty name is returned if there's no feature at the given position.
  33. func getFeature(
  34. request point: Routeguide_Point,
  35. context: StatusOnlyCallContext
  36. ) -> EventLoopFuture<Routeguide_Feature> {
  37. return context.eventLoop.makeSucceededFuture(self.checkFeature(at: point))
  38. }
  39. /// A server-to-client streaming RPC.
  40. ///
  41. /// Obtains the Features available within the given Rectangle. Results are streamed rather than
  42. /// returned at once (e.g. in a response message with a repeated field), as the rectangle may
  43. /// cover a large area and contain a huge number of features.
  44. func listFeatures(
  45. request: Routeguide_Rectangle,
  46. context: StreamingResponseCallContext<Routeguide_Feature>
  47. ) -> EventLoopFuture<GRPCStatus> {
  48. let left = min(request.lo.longitude, request.hi.longitude)
  49. let right = max(request.lo.longitude, request.hi.longitude)
  50. let top = max(request.lo.latitude, request.hi.latitude)
  51. let bottom = max(request.lo.latitude, request.hi.latitude)
  52. self.features.lazy.filter { feature in
  53. return !feature.name.isEmpty
  54. && feature.location.longitude >= left
  55. && feature.location.longitude <= right
  56. && feature.location.latitude >= bottom
  57. && feature.location.latitude <= top
  58. }.forEach {
  59. _ = context.sendResponse($0)
  60. }
  61. return context.eventLoop.makeSucceededFuture(.ok)
  62. }
  63. /// A client-to-server streaming RPC.
  64. ///
  65. /// Accepts a stream of Points on a route being traversed, returning a RouteSummary when traversal
  66. /// is completed.
  67. func recordRoute(
  68. context: UnaryResponseCallContext<Routeguide_RouteSummary>
  69. ) -> EventLoopFuture<(StreamEvent<Routeguide_Point>) -> Void> {
  70. var pointCount: Int32 = 0
  71. var featureCount: Int32 = 0
  72. var distance = 0.0
  73. var previousPoint: Routeguide_Point?
  74. let startTime = Date()
  75. return context.eventLoop.makeSucceededFuture({ event in
  76. switch event {
  77. case .message(let point):
  78. pointCount += 1
  79. if !self.checkFeature(at: point).name.isEmpty {
  80. featureCount += 1
  81. }
  82. // For each point after the first, add the incremental distance from the previous point to
  83. // the total distance value.
  84. if let previous = previousPoint {
  85. distance += previous.distance(to: point)
  86. }
  87. previousPoint = point
  88. case .end:
  89. let seconds = Date().timeIntervalSince(startTime)
  90. let summary = Routeguide_RouteSummary.with {
  91. $0.pointCount = pointCount
  92. $0.featureCount = featureCount
  93. $0.elapsedTime = Int32(seconds)
  94. $0.distance = Int32(distance)
  95. }
  96. context.responsePromise.succeed(summary)
  97. }
  98. })
  99. }
  100. /// A Bidirectional streaming RPC.
  101. ///
  102. /// Accepts a stream of RouteNotes sent while a route is being traversed, while receiving other
  103. /// RouteNotes (e.g. from other users).
  104. func routeChat(
  105. context: StreamingResponseCallContext<Routeguide_RouteNote>
  106. ) -> EventLoopFuture<(StreamEvent<Routeguide_RouteNote>) -> Void> {
  107. return context.eventLoop.makeSucceededFuture({ event in
  108. switch event {
  109. case .message(let note):
  110. // Get any notes at the location of request note.
  111. var notes = self.lock.withLock {
  112. self.notes[note.location, default: []]
  113. }
  114. // Respond with all previous notes at this location.
  115. for note in notes {
  116. _ = context.sendResponse(note)
  117. }
  118. // Add the new note and update the stored notes.
  119. notes.append(note)
  120. self.lock.withLockVoid {
  121. self.notes[note.location] = notes
  122. }
  123. case .end:
  124. context.statusPromise.succeed(.ok)
  125. }
  126. })
  127. }
  128. }
  129. extension RouteGuideProvider {
  130. private func getOrCreateNotes(for point: Routeguide_Point) -> [Routeguide_RouteNote] {
  131. return self.lock.withLock {
  132. self.notes[point, default: []]
  133. }
  134. }
  135. /// Returns a feature at the given location or an unnamed feature if none exist at that location.
  136. private func checkFeature(at location: Routeguide_Point) -> Routeguide_Feature {
  137. return self.features.first(where: {
  138. return $0.location.latitude == location.latitude && $0.location.longitude == location.longitude
  139. }) ?? Routeguide_Feature.with {
  140. $0.name = ""
  141. $0.location = location
  142. }
  143. }
  144. }
  145. fileprivate func degreesToRadians(_ degrees: Double) -> Double {
  146. return degrees * .pi / 180.0
  147. }
  148. fileprivate extension Routeguide_Point {
  149. func distance(to other: Routeguide_Point) -> Double {
  150. // Radius of Earth in meters
  151. let radius = 6_371_000.0
  152. // Points are in the E7 representation (degrees multiplied by 10**7 and rounded to the nearest
  153. // integer). See also `Routeguide_Point`.
  154. let coordinateFactor = 1.0e7
  155. let lat1 = degreesToRadians(Double(self.latitude) / coordinateFactor)
  156. let lat2 = degreesToRadians(Double(other.latitude) / coordinateFactor)
  157. let lon1 = degreesToRadians(Double(self.longitude) / coordinateFactor)
  158. let lon2 = degreesToRadians(Double(other.longitude) / coordinateFactor)
  159. let deltaLat = lat2 - lat1
  160. let deltaLon = lon2 - lon1
  161. let a = sin(deltaLat / 2) * sin(deltaLat / 2)
  162. + cos(lat1) * cos(lat2) * sin(deltaLon / 2) * sin(deltaLon / 2)
  163. let c = 2 * atan2(sqrt(a), sqrt(1 - a))
  164. return radius * c
  165. }
  166. }