route_guide_callback_server.cc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. *
  3. * Copyright 2021 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <algorithm>
  19. #include <chrono>
  20. #include <cmath>
  21. #include <iostream>
  22. #include <memory>
  23. #include <string>
  24. #include <thread>
  25. #include "helper.h"
  26. #include <grpc/grpc.h>
  27. #include <grpcpp/security/server_credentials.h>
  28. #include <grpcpp/server.h>
  29. #include <grpcpp/server_builder.h>
  30. #include <grpcpp/server_context.h>
  31. #ifdef BAZEL_BUILD
  32. #include "examples/protos/route_guide.grpc.pb.h"
  33. #else
  34. #include "route_guide.grpc.pb.h"
  35. #endif
  36. using grpc::CallbackServerContext;
  37. using grpc::Server;
  38. using grpc::ServerBuilder;
  39. using grpc::Status;
  40. using routeguide::Feature;
  41. using routeguide::Point;
  42. using routeguide::Rectangle;
  43. using routeguide::RouteGuide;
  44. using routeguide::RouteNote;
  45. using routeguide::RouteSummary;
  46. using std::chrono::system_clock;
  47. float ConvertToRadians(float num) { return num * 3.1415926 / 180; }
  48. // The formula is based on http://mathforum.org/library/drmath/view/51879.html
  49. float GetDistance(const Point& start, const Point& end) {
  50. const float kCoordFactor = 10000000.0;
  51. float lat_1 = start.latitude() / kCoordFactor;
  52. float lat_2 = end.latitude() / kCoordFactor;
  53. float lon_1 = start.longitude() / kCoordFactor;
  54. float lon_2 = end.longitude() / kCoordFactor;
  55. float lat_rad_1 = ConvertToRadians(lat_1);
  56. float lat_rad_2 = ConvertToRadians(lat_2);
  57. float delta_lat_rad = ConvertToRadians(lat_2 - lat_1);
  58. float delta_lon_rad = ConvertToRadians(lon_2 - lon_1);
  59. float a = pow(sin(delta_lat_rad / 2), 2) +
  60. cos(lat_rad_1) * cos(lat_rad_2) * pow(sin(delta_lon_rad / 2), 2);
  61. float c = 2 * atan2(sqrt(a), sqrt(1 - a));
  62. int R = 6371000; // metres
  63. return R * c;
  64. }
  65. std::string GetFeatureName(const Point& point,
  66. const std::vector<Feature>& feature_list) {
  67. for (const Feature& f : feature_list) {
  68. if (f.location().latitude() == point.latitude() &&
  69. f.location().longitude() == point.longitude()) {
  70. return f.name();
  71. }
  72. }
  73. return "";
  74. }
  75. class RouteGuideImpl final : public RouteGuide::CallbackService {
  76. public:
  77. explicit RouteGuideImpl(const std::string& db) {
  78. routeguide::ParseDb(db, &feature_list_);
  79. }
  80. grpc::ServerUnaryReactor* GetFeature(CallbackServerContext* context,
  81. const Point* point,
  82. Feature* feature) override {
  83. feature->set_name(GetFeatureName(*point, feature_list_));
  84. feature->mutable_location()->CopyFrom(*point);
  85. auto* reactor = context->DefaultReactor();
  86. reactor->Finish(Status::OK);
  87. return reactor;
  88. }
  89. grpc::ServerWriteReactor<Feature>* ListFeatures(
  90. CallbackServerContext* context,
  91. const routeguide::Rectangle* rectangle) override {
  92. class Lister : public grpc::ServerWriteReactor<Feature> {
  93. public:
  94. Lister(const routeguide::Rectangle* rectangle,
  95. const std::vector<Feature>* feature_list)
  96. : left_((std::min)(rectangle->lo().longitude(),
  97. rectangle->hi().longitude())),
  98. right_((std::max)(rectangle->lo().longitude(),
  99. rectangle->hi().longitude())),
  100. top_((std::max)(rectangle->lo().latitude(),
  101. rectangle->hi().latitude())),
  102. bottom_((std::min)(rectangle->lo().latitude(),
  103. rectangle->hi().latitude())),
  104. feature_list_(feature_list),
  105. next_feature_(feature_list_->begin()) {
  106. NextWrite();
  107. }
  108. void OnDone() override { delete this; }
  109. void OnWriteDone(bool /*ok*/) override { NextWrite(); }
  110. private:
  111. void NextWrite() {
  112. while (next_feature_ != feature_list_->end()) {
  113. const Feature& f = *next_feature_;
  114. next_feature_++;
  115. if (f.location().longitude() >= left_ &&
  116. f.location().longitude() <= right_ &&
  117. f.location().latitude() >= bottom_ &&
  118. f.location().latitude() <= top_) {
  119. StartWrite(&f);
  120. return;
  121. }
  122. }
  123. // Didn't write anything, all is done.
  124. Finish(Status::OK);
  125. }
  126. const long left_;
  127. const long right_;
  128. const long top_;
  129. const long bottom_;
  130. const std::vector<Feature>* feature_list_;
  131. std::vector<Feature>::const_iterator next_feature_;
  132. };
  133. return new Lister(rectangle, &feature_list_);
  134. }
  135. grpc::ServerReadReactor<Point>* RecordRoute(CallbackServerContext* context,
  136. RouteSummary* summary) override {
  137. class Recorder : public grpc::ServerReadReactor<Point> {
  138. public:
  139. Recorder(RouteSummary* summary, const std::vector<Feature>* feature_list)
  140. : start_time_(system_clock::now()),
  141. summary_(summary),
  142. feature_list_(feature_list) {
  143. StartRead(&point_);
  144. }
  145. void OnDone() { delete this; }
  146. void OnReadDone(bool ok) {
  147. if (ok) {
  148. point_count_++;
  149. if (!GetFeatureName(point_, *feature_list_).empty()) {
  150. feature_count_++;
  151. }
  152. if (point_count_ != 1) {
  153. distance_ += GetDistance(previous_, point_);
  154. }
  155. previous_ = point_;
  156. StartRead(&point_);
  157. } else {
  158. summary_->set_point_count(point_count_);
  159. summary_->set_feature_count(feature_count_);
  160. summary_->set_distance(static_cast<long>(distance_));
  161. auto secs = std::chrono::duration_cast<std::chrono::seconds>(
  162. system_clock::now() - start_time_);
  163. summary_->set_elapsed_time(secs.count());
  164. Finish(Status::OK);
  165. }
  166. }
  167. private:
  168. system_clock::time_point start_time_;
  169. RouteSummary* summary_;
  170. const std::vector<Feature>* feature_list_;
  171. Point point_;
  172. int point_count_ = 0;
  173. int feature_count_ = 0;
  174. float distance_ = 0.0;
  175. Point previous_;
  176. };
  177. return new Recorder(summary, &feature_list_);
  178. }
  179. grpc::ServerBidiReactor<RouteNote, RouteNote>* RouteChat(
  180. CallbackServerContext* context) override {
  181. class Chatter : public grpc::ServerBidiReactor<RouteNote, RouteNote> {
  182. public:
  183. Chatter(std::mutex* mu, std::vector<RouteNote>* received_notes)
  184. : mu_(mu), received_notes_(received_notes) {
  185. StartRead(&note_);
  186. }
  187. void OnDone() override {
  188. // Collect the read_starter thread if needed
  189. if (read_starter_.joinable()) {
  190. read_starter_.join();
  191. }
  192. delete this;
  193. }
  194. void OnReadDone(bool ok) override {
  195. if (ok) {
  196. // We may need to wait an arbitary amount of time on this mutex
  197. // and we cannot delay the reaction, so start it in a thread
  198. // Collect the previous read_starter thread if needed
  199. if (read_starter_.joinable()) {
  200. read_starter_.join();
  201. }
  202. read_starter_ = std::thread([this] {
  203. mu_->lock();
  204. notes_iterator_ = received_notes_->begin();
  205. NextWrite();
  206. });
  207. } else {
  208. Finish(Status::OK);
  209. }
  210. }
  211. void OnWriteDone(bool /*ok*/) override { NextWrite(); }
  212. private:
  213. void NextWrite() {
  214. while (notes_iterator_ != received_notes_->end()) {
  215. const RouteNote& n = *notes_iterator_;
  216. notes_iterator_++;
  217. if (n.location().latitude() == note_.location().latitude() &&
  218. n.location().longitude() == note_.location().longitude()) {
  219. StartWrite(&n);
  220. return;
  221. }
  222. }
  223. // Didn't write anything, so all done with this note
  224. received_notes_->push_back(note_);
  225. mu_->unlock();
  226. StartRead(&note_);
  227. }
  228. RouteNote note_;
  229. std::mutex* mu_;
  230. std::vector<RouteNote>* received_notes_;
  231. std::vector<RouteNote>::iterator notes_iterator_;
  232. std::thread read_starter_;
  233. };
  234. return new Chatter(&mu_, &received_notes_);
  235. }
  236. private:
  237. std::vector<Feature> feature_list_;
  238. std::mutex mu_;
  239. std::vector<RouteNote> received_notes_;
  240. };
  241. void RunServer(const std::string& db_path) {
  242. std::string server_address("0.0.0.0:50051");
  243. RouteGuideImpl service(db_path);
  244. ServerBuilder builder;
  245. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  246. builder.RegisterService(&service);
  247. std::unique_ptr<Server> server(builder.BuildAndStart());
  248. std::cout << "Server listening on " << server_address << std::endl;
  249. server->Wait();
  250. }
  251. int main(int argc, char** argv) {
  252. // Expect only arg: --db_path=path/to/route_guide_db.json.
  253. std::string db = routeguide::GetDbFileContent(argc, argv);
  254. RunServer(db);
  255. return 0;
  256. }