RouteGuideProvider.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 NIOConcurrencyHelpers
  19. import NIOCore
  20. import RouteGuideModel
  21. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  22. internal final class RouteGuideProvider: Routeguide_RouteGuideAsyncProvider {
  23. private let features: [Routeguide_Feature]
  24. private let notes: Notes
  25. internal init(features: [Routeguide_Feature]) {
  26. self.features = features
  27. self.notes = Notes()
  28. }
  29. internal func getFeature(
  30. request point: Routeguide_Point,
  31. context: GRPCAsyncServerCallContext
  32. ) async throws -> Routeguide_Feature {
  33. return self.lookupFeature(at: point) ?? .unnamedFeature(at: point)
  34. }
  35. internal func listFeatures(
  36. request: Routeguide_Rectangle,
  37. responseStream: GRPCAsyncResponseStreamWriter<Routeguide_Feature>,
  38. context: GRPCAsyncServerCallContext
  39. ) async throws {
  40. let longitudeRange = request.lo.longitude ... request.hi.longitude
  41. let latitudeRange = request.lo.latitude ... request.hi.latitude
  42. for feature in self.features where !feature.name.isEmpty {
  43. if feature.location.isWithin(latitude: latitudeRange, longitude: longitudeRange) {
  44. try await responseStream.send(feature)
  45. }
  46. }
  47. }
  48. internal func recordRoute(
  49. requestStream points: GRPCAsyncRequestStream<Routeguide_Point>,
  50. context: GRPCAsyncServerCallContext
  51. ) async throws -> Routeguide_RouteSummary {
  52. var pointCount: Int32 = 0
  53. var featureCount: Int32 = 0
  54. var distance = 0.0
  55. var previousPoint: Routeguide_Point?
  56. let startTimeNanos = DispatchTime.now().uptimeNanoseconds
  57. for try await point in points {
  58. pointCount += 1
  59. if let feature = self.lookupFeature(at: point), !feature.name.isEmpty {
  60. featureCount += 1
  61. }
  62. if let previous = previousPoint {
  63. distance += previous.distance(to: point)
  64. }
  65. previousPoint = point
  66. }
  67. let durationInNanos = DispatchTime.now().uptimeNanoseconds - startTimeNanos
  68. let durationInSeconds = Double(durationInNanos) / 1e9
  69. return .with {
  70. $0.pointCount = pointCount
  71. $0.featureCount = featureCount
  72. $0.elapsedTime = Int32(durationInSeconds)
  73. $0.distance = Int32(distance)
  74. }
  75. }
  76. internal func routeChat(
  77. requestStream: GRPCAsyncRequestStream<Routeguide_RouteNote>,
  78. responseStream: GRPCAsyncResponseStreamWriter<Routeguide_RouteNote>,
  79. context: GRPCAsyncServerCallContext
  80. ) async throws {
  81. for try await note in requestStream {
  82. let existingNotes = await self.notes.addNote(note, to: note.location)
  83. // Respond with all existing notes.
  84. for existingNote in existingNotes {
  85. try await responseStream.send(existingNote)
  86. }
  87. }
  88. }
  89. /// Returns a feature at the given location or an unnamed feature if none exist at that location.
  90. private func lookupFeature(at location: Routeguide_Point) -> Routeguide_Feature? {
  91. return self.features.first(where: {
  92. $0.location.latitude == location.latitude && $0.location.longitude == location.longitude
  93. })
  94. }
  95. }
  96. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  97. internal final actor Notes {
  98. private var recordedNotes: [Routeguide_Point: [Routeguide_RouteNote]]
  99. internal init() {
  100. self.recordedNotes = [:]
  101. }
  102. /// Record a note at the given location and return the all notes which were previously recorded
  103. /// at the location.
  104. internal func addNote(
  105. _ note: Routeguide_RouteNote,
  106. to location: Routeguide_Point
  107. ) -> ArraySlice<Routeguide_RouteNote> {
  108. self.recordedNotes[location, default: []].append(note)
  109. return self.recordedNotes[location]!.dropLast(1)
  110. }
  111. }
  112. private func degreesToRadians(_ degrees: Double) -> Double {
  113. return degrees * .pi / 180.0
  114. }
  115. extension Routeguide_Point {
  116. fileprivate func distance(to other: Routeguide_Point) -> Double {
  117. // Radius of Earth in meters
  118. let radius = 6_371_000.0
  119. // Points are in the E7 representation (degrees multiplied by 10**7 and rounded to the nearest
  120. // integer). See also `Routeguide_Point`.
  121. let coordinateFactor = 1.0e7
  122. let lat1 = degreesToRadians(Double(self.latitude) / coordinateFactor)
  123. let lat2 = degreesToRadians(Double(other.latitude) / coordinateFactor)
  124. let lon1 = degreesToRadians(Double(self.longitude) / coordinateFactor)
  125. let lon2 = degreesToRadians(Double(other.longitude) / coordinateFactor)
  126. let deltaLat = lat2 - lat1
  127. let deltaLon = lon2 - lon1
  128. let a = sin(deltaLat / 2) * sin(deltaLat / 2)
  129. + cos(lat1) * cos(lat2) * sin(deltaLon / 2) * sin(deltaLon / 2)
  130. let c = 2 * atan2(sqrt(a), sqrt(1 - a))
  131. return radius * c
  132. }
  133. func isWithin<Range: RangeExpression>(
  134. latitude: Range,
  135. longitude: Range
  136. ) -> Bool where Range.Bound == Int32 {
  137. return latitude.contains(self.latitude) && longitude.contains(self.longitude)
  138. }
  139. }
  140. extension Routeguide_Feature {
  141. static func unnamedFeature(at location: Routeguide_Point) -> Routeguide_Feature {
  142. return .with {
  143. $0.name = ""
  144. $0.location = location
  145. }
  146. }
  147. }