asyncio_route_guide_server.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # Copyright 2020 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """The Python AsyncIO implementation of the gRPC route guide server."""
  15. import asyncio
  16. import logging
  17. import math
  18. import time
  19. from typing import AsyncIterable, Iterable
  20. import grpc
  21. import route_guide_pb2
  22. import route_guide_pb2_grpc
  23. import route_guide_resources
  24. def get_feature(feature_db: Iterable[route_guide_pb2.Feature],
  25. point: route_guide_pb2.Point) -> route_guide_pb2.Feature:
  26. """Returns Feature at given location or None."""
  27. for feature in feature_db:
  28. if feature.location == point:
  29. return feature
  30. return None
  31. def get_distance(start: route_guide_pb2.Point,
  32. end: route_guide_pb2.Point) -> float:
  33. """Distance between two points."""
  34. coord_factor = 10000000.0
  35. lat_1 = start.latitude / coord_factor
  36. lat_2 = end.latitude / coord_factor
  37. lon_1 = start.longitude / coord_factor
  38. lon_2 = end.longitude / coord_factor
  39. lat_rad_1 = math.radians(lat_1)
  40. lat_rad_2 = math.radians(lat_2)
  41. delta_lat_rad = math.radians(lat_2 - lat_1)
  42. delta_lon_rad = math.radians(lon_2 - lon_1)
  43. # Formula is based on http://mathforum.org/library/drmath/view/51879.html
  44. a = (pow(math.sin(delta_lat_rad / 2), 2) +
  45. (math.cos(lat_rad_1) * math.cos(lat_rad_2) *
  46. pow(math.sin(delta_lon_rad / 2), 2)))
  47. c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  48. R = 6371000
  49. # metres
  50. return R * c
  51. class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
  52. """Provides methods that implement functionality of route guide server."""
  53. def __init__(self) -> None:
  54. self.db = route_guide_resources.read_route_guide_database()
  55. def GetFeature(self, request: route_guide_pb2.Point,
  56. unused_context) -> route_guide_pb2.Feature:
  57. feature = get_feature(self.db, request)
  58. if feature is None:
  59. return route_guide_pb2.Feature(name="", location=request)
  60. else:
  61. return feature
  62. async def ListFeatures(
  63. self, request: route_guide_pb2.Rectangle,
  64. unused_context) -> AsyncIterable[route_guide_pb2.Feature]:
  65. left = min(request.lo.longitude, request.hi.longitude)
  66. right = max(request.lo.longitude, request.hi.longitude)
  67. top = max(request.lo.latitude, request.hi.latitude)
  68. bottom = min(request.lo.latitude, request.hi.latitude)
  69. for feature in self.db:
  70. if (feature.location.longitude >= left and
  71. feature.location.longitude <= right and
  72. feature.location.latitude >= bottom and
  73. feature.location.latitude <= top):
  74. yield feature
  75. async def RecordRoute(self, request_iterator: AsyncIterable[
  76. route_guide_pb2.Point], unused_context) -> route_guide_pb2.RouteSummary:
  77. point_count = 0
  78. feature_count = 0
  79. distance = 0.0
  80. prev_point = None
  81. start_time = time.time()
  82. async for point in request_iterator:
  83. point_count += 1
  84. if get_feature(self.db, point):
  85. feature_count += 1
  86. if prev_point:
  87. distance += get_distance(prev_point, point)
  88. prev_point = point
  89. elapsed_time = time.time() - start_time
  90. return route_guide_pb2.RouteSummary(point_count=point_count,
  91. feature_count=feature_count,
  92. distance=int(distance),
  93. elapsed_time=int(elapsed_time))
  94. async def RouteChat(
  95. self, request_iterator: AsyncIterable[route_guide_pb2.RouteNote],
  96. unused_context) -> AsyncIterable[route_guide_pb2.RouteNote]:
  97. prev_notes = []
  98. async for new_note in request_iterator:
  99. for prev_note in prev_notes:
  100. if prev_note.location == new_note.location:
  101. yield prev_note
  102. prev_notes.append(new_note)
  103. async def serve() -> None:
  104. server = grpc.aio.server()
  105. route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
  106. RouteGuideServicer(), server)
  107. server.add_insecure_port('[::]:50051')
  108. await server.start()
  109. await server.wait_for_termination()
  110. if __name__ == '__main__':
  111. logging.basicConfig(level=logging.INFO)
  112. asyncio.get_event_loop().run_until_complete(serve())