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