route_guide_callback_client.cc
Go to the documentation of this file.
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 <chrono>
20 #include <condition_variable>
21 #include <iostream>
22 #include <memory>
23 #include <mutex>
24 #include <random>
25 #include <string>
26 #include <thread>
27 
28 #include "helper.h"
29 
30 #include <grpc/grpc.h>
31 #include <grpcpp/alarm.h>
32 #include <grpcpp/channel.h>
33 #include <grpcpp/client_context.h>
34 #include <grpcpp/create_channel.h>
36 #ifdef BAZEL_BUILD
37 #include "examples/protos/route_guide.grpc.pb.h"
38 #else
39 #include "route_guide.grpc.pb.h"
40 #endif
41 
42 using grpc::Channel;
44 using grpc::Status;
46 using routeguide::Point;
48 using routeguide::RouteGuide;
51 
52 Point MakePoint(long latitude, long longitude) {
53  Point p;
54  p.set_latitude(latitude);
55  p.set_longitude(longitude);
56  return p;
57 }
58 
59 Feature MakeFeature(const std::string& name, long latitude, long longitude) {
60  Feature f;
61  f.set_name(name);
62  f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
63  return f;
64 }
65 
67  long longitude) {
68  RouteNote n;
69  n.set_message(message);
70  n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
71  return n;
72 }
73 
75  public:
76  RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
77  : stub_(RouteGuide::NewStub(channel)) {
79  }
80 
81  void GetFeature() {
82  Point point;
83  Feature feature;
84  point = MakePoint(409146138, -746188906);
85  GetOneFeature(point, &feature);
86  point = MakePoint(0, 0);
87  GetOneFeature(point, &feature);
88  }
89 
90  void ListFeatures() {
92  Feature feature;
93 
94  rect.mutable_lo()->set_latitude(400000000);
95  rect.mutable_lo()->set_longitude(-750000000);
96  rect.mutable_hi()->set_latitude(420000000);
97  rect.mutable_hi()->set_longitude(-730000000);
98  std::cout << "Looking for features between 40, -75 and 42, -73"
99  << std::endl;
100 
101  class Reader : public grpc::ClientReadReactor<Feature> {
102  public:
103  Reader(RouteGuide::Stub* stub, float coord_factor,
104  const routeguide::Rectangle& rect)
105  : coord_factor_(coord_factor) {
106  stub->async()->ListFeatures(&context_, &rect, this);
107  StartRead(&feature_);
108  StartCall();
109  }
110  void OnReadDone(bool ok) override {
111  if (ok) {
112  std::cout << "Found feature called " << feature_.name() << " at "
113  << feature_.location().latitude() / coord_factor_ << ", "
114  << feature_.location().longitude() / coord_factor_
115  << std::endl;
116  StartRead(&feature_);
117  }
118  }
119  void OnDone(const Status& s) override {
120  std::unique_lock<std::mutex> l(mu_);
121  status_ = s;
122  done_ = true;
123  cv_.notify_one();
124  }
125  Status Await() {
126  std::unique_lock<std::mutex> l(mu_);
127  cv_.wait(l, [this] { return done_; });
128  return std::move(status_);
129  }
130 
131  private:
133  float coord_factor_;
134  Feature feature_;
135  std::mutex mu_;
136  std::condition_variable cv_;
137  Status status_;
138  bool done_ = false;
139  };
140  Reader reader(stub_.get(), kCoordFactor_, rect);
141  Status status = reader.Await();
142  if (status.ok()) {
143  std::cout << "ListFeatures rpc succeeded." << std::endl;
144  } else {
145  std::cout << "ListFeatures rpc failed." << std::endl;
146  }
147  }
148 
149  void RecordRoute() {
150  class Recorder : public grpc::ClientWriteReactor<Point> {
151  public:
152  Recorder(RouteGuide::Stub* stub, float coord_factor,
153  const std::vector<Feature>* feature_list)
154  : coord_factor_(coord_factor),
155  feature_list_(feature_list),
156  generator_(
157  std::chrono::system_clock::now().time_since_epoch().count()),
158  feature_distribution_(0, feature_list->size() - 1),
159  delay_distribution_(500, 1500) {
160  stub->async()->RecordRoute(&context_, &stats_, this);
161  // Use a hold since some StartWrites are invoked indirectly from a
162  // delayed lambda in OnWriteDone rather than directly from the reaction
163  // itself
164  AddHold();
165  NextWrite();
166  StartCall();
167  }
168  void OnWriteDone(bool ok) override {
169  // Delay and then do the next write or WritesDone
170  alarm_.Set(
172  std::chrono::milliseconds(delay_distribution_(generator_)),
173  [this](bool /*ok*/) { NextWrite(); });
174  }
175  void OnDone(const Status& s) override {
176  std::unique_lock<std::mutex> l(mu_);
177  status_ = s;
178  done_ = true;
179  cv_.notify_one();
180  }
181  Status Await(RouteSummary* stats) {
182  std::unique_lock<std::mutex> l(mu_);
183  cv_.wait(l, [this] { return done_; });
184  *stats = stats_;
185  return std::move(status_);
186  }
187 
188  private:
189  void NextWrite() {
190  if (points_remaining_ != 0) {
191  const Feature& f =
192  (*feature_list_)[feature_distribution_(generator_)];
193  std::cout << "Visiting point "
194  << f.location().latitude() / coord_factor_ << ", "
195  << f.location().longitude() / coord_factor_ << std::endl;
196  StartWrite(&f.location());
197  points_remaining_--;
198  } else {
199  StartWritesDone();
200  RemoveHold();
201  }
202  }
204  float coord_factor_;
205  int points_remaining_ = 10;
206  Point point_;
207  RouteSummary stats_;
208  const std::vector<Feature>* feature_list_;
209  std::default_random_engine generator_;
210  std::uniform_int_distribution<int> feature_distribution_;
211  std::uniform_int_distribution<int> delay_distribution_;
212  grpc::Alarm alarm_;
213  std::mutex mu_;
214  std::condition_variable cv_;
215  Status status_;
216  bool done_ = false;
217  };
218  Recorder recorder(stub_.get(), kCoordFactor_, &feature_list_);
220  Status status = recorder.Await(&stats);
221  if (status.ok()) {
222  std::cout << "Finished trip with " << stats.point_count() << " points\n"
223  << "Passed " << stats.feature_count() << " features\n"
224  << "Travelled " << stats.distance() << " meters\n"
225  << "It took " << stats.elapsed_time() << " seconds"
226  << std::endl;
227  } else {
228  std::cout << "RecordRoute rpc failed." << std::endl;
229  }
230  }
231 
232  void RouteChat() {
233  class Chatter : public grpc::ClientBidiReactor<RouteNote, RouteNote> {
234  public:
235  explicit Chatter(RouteGuide::Stub* stub)
236  : notes_{MakeRouteNote("First message", 0, 0),
237  MakeRouteNote("Second message", 0, 1),
238  MakeRouteNote("Third message", 1, 0),
239  MakeRouteNote("Fourth message", 0, 0)},
240  notes_iterator_(notes_.begin()) {
241  stub->async()->RouteChat(&context_, this);
242  NextWrite();
243  StartRead(&server_note_);
244  StartCall();
245  }
246  void OnWriteDone(bool /*ok*/) override { NextWrite(); }
247  void OnReadDone(bool ok) override {
248  if (ok) {
249  std::cout << "Got message " << server_note_.message() << " at "
250  << server_note_.location().latitude() << ", "
251  << server_note_.location().longitude() << std::endl;
252  StartRead(&server_note_);
253  }
254  }
255  void OnDone(const Status& s) override {
256  std::unique_lock<std::mutex> l(mu_);
257  status_ = s;
258  done_ = true;
259  cv_.notify_one();
260  }
261  Status Await() {
262  std::unique_lock<std::mutex> l(mu_);
263  cv_.wait(l, [this] { return done_; });
264  return std::move(status_);
265  }
266 
267  private:
268  void NextWrite() {
269  if (notes_iterator_ != notes_.end()) {
270  const auto& note = *notes_iterator_;
271  std::cout << "Sending message " << note.message() << " at "
272  << note.location().latitude() << ", "
273  << note.location().longitude() << std::endl;
274  StartWrite(&note);
275  notes_iterator_++;
276  } else {
277  StartWritesDone();
278  }
279  }
281  const std::vector<RouteNote> notes_;
282  std::vector<RouteNote>::const_iterator notes_iterator_;
283  RouteNote server_note_;
284  std::mutex mu_;
285  std::condition_variable cv_;
286  Status status_;
287  bool done_ = false;
288  };
289 
290  Chatter chatter(stub_.get());
291  Status status = chatter.Await();
292  if (!status.ok()) {
293  std::cout << "RouteChat rpc failed." << std::endl;
294  }
295  }
296 
297  private:
298  bool GetOneFeature(const Point& point, Feature* feature) {
300  bool result;
301  std::mutex mu;
302  std::condition_variable cv;
303  bool done = false;
304  stub_->async()->GetFeature(
305  &context, &point, feature,
306  [&result, &mu, &cv, &done, feature, this](Status status) {
307  bool ret;
308  if (!status.ok()) {
309  std::cout << "GetFeature rpc failed." << std::endl;
310  ret = false;
311  } else if (!feature->has_location()) {
312  std::cout << "Server returns incomplete feature." << std::endl;
313  ret = false;
314  } else if (feature->name().empty()) {
315  std::cout << "Found no feature at "
316  << feature->location().latitude() / kCoordFactor_ << ", "
317  << feature->location().longitude() / kCoordFactor_
318  << std::endl;
319  ret = true;
320  } else {
321  std::cout << "Found feature called " << feature->name() << " at "
322  << feature->location().latitude() / kCoordFactor_ << ", "
323  << feature->location().longitude() / kCoordFactor_
324  << std::endl;
325  ret = true;
326  }
327  std::lock_guard<std::mutex> lock(mu);
328  result = ret;
329  done = true;
330  cv.notify_one();
331  });
332  std::unique_lock<std::mutex> lock(mu);
333  cv.wait(lock, [&done] { return done; });
334  return result;
335  }
336 
337  const float kCoordFactor_ = 10000000.0;
338  std::unique_ptr<RouteGuide::Stub> stub_;
339  std::vector<Feature> feature_list_;
340 };
341 
342 int main(int argc, char** argv) {
343  // Expect only arg: --db_path=path/to/route_guide_db.json.
344  std::string db = routeguide::GetDbFileContent(argc, argv);
345  RouteGuideClient guide(
346  grpc::CreateChannel("localhost:50051",
348  db);
349 
350  std::cout << "-------------- GetFeature --------------" << std::endl;
351  guide.GetFeature();
352  std::cout << "-------------- ListFeatures --------------" << std::endl;
353  guide.ListFeatures();
354  std::cout << "-------------- RecordRoute --------------" << std::endl;
355  guide.RecordRoute();
356  std::cout << "-------------- RouteChat --------------" << std::endl;
357  guide.RouteChat();
358 
359  return 0;
360 }
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
RouteGuideClient::kCoordFactor_
const float kCoordFactor_
Definition: route_guide_callback_client.cc:337
now
static double now(void)
Definition: test/core/fling/client.cc:130
MakePoint
Point MakePoint(long latitude, long longitude)
Definition: route_guide_callback_client.cc:52
MakeRouteNote
RouteNote MakeRouteNote(const std::string &message, long latitude, long longitude)
Definition: route_guide_callback_client.cc:66
main
int main(int argc, char **argv)
Definition: route_guide_callback_client.cc:342
cv_
std::condition_variable cv_
Definition: client_callback_end2end_test.cc:733
RouteGuideClient::ListFeatures
void ListFeatures()
Definition: route_guide_callback_client.cc:90
mutex
static uv_mutex_t mutex
Definition: threadpool.c:34
grpc::ClientBidiReactor
ClientBidiReactor is the interface for a bidirectional streaming RPC.
Definition: impl/codegen/client_callback.h:151
RouteGuideClient::stub_
std::unique_ptr< RouteGuide::Stub > stub_
Definition: route_guide_callback_client.cc:338
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
status
absl::Status status
Definition: rls.cc:251
grpc::ClientReadReactor
Definition: impl/codegen/client_callback.h:153
setup.name
name
Definition: setup.py:542
xds_manager.p
p
Definition: xds_manager.py:60
alarm.h
async_greeter_client.stub
stub
Definition: hellostreamingworld/async_greeter_client.py:26
MakeFeature
Feature MakeFeature(const std::string &name, long latitude, long longitude)
Definition: route_guide_callback_client.cc:59
message
char * message
Definition: libuv/docs/code/tty-gravity/main.c:12
done_
std::atomic< bool > done_
Definition: fuzzing_event_engine_test.cc:57
mu_
Mutex mu_
Definition: oob_backend_metric.cc:115
routeguide::GetDbFileContent
std::string GetDbFileContent(int argc, char **argv)
Definition: helper.cc:34
routeguide::ParseDb
void ParseDb(const std::string &db, std::vector< Feature > *feature_list)
Definition: helper.cc:143
route_guide_pb2.RouteSummary
RouteSummary
Definition: multiplex/route_guide_pb2.py:270
route_guide_pb2.Point
Point
Definition: multiplex/route_guide_pb2.py:242
framework.rpc.grpc_channelz.Channel
Channel
Definition: grpc_channelz.py:32
channel
wrapped_grpc_channel * channel
Definition: src/php/ext/grpc/call.h:33
autogen_x86imm.f
f
Definition: autogen_x86imm.py:9
absl::move
constexpr absl::remove_reference_t< T > && move(T &&t) noexcept
Definition: abseil-cpp/absl/utility/utility.h:221
context_
ScopedContext * context_
Definition: filter_fuzzer.cc:559
grpc::ClientWriteReactor
Definition: impl/codegen/client_callback.h:155
mu
Mutex mu
Definition: server_config_selector_filter.cc:74
RouteGuideClient::RecordRoute
void RecordRoute()
Definition: route_guide_callback_client.cc:149
grpc.h
gen_stats_data.stats
list stats
Definition: gen_stats_data.py:58
done
struct tab * done
Definition: bloaty/third_party/zlib/examples/enough.c:176
channel.h
RouteGuideClient::RouteChat
void RouteChat()
Definition: route_guide_callback_client.cc:232
status_
absl::Status status_
Definition: outlier_detection.cc:404
grpc::CreateChannel
std::shared_ptr< Channel > CreateChannel(const grpc::string &target, const std::shared_ptr< ChannelCredentials > &creds)
n
int n
Definition: abseil-cpp/absl/container/btree_test.cc:1080
grpc::ClientContext
Definition: grpcpp/impl/codegen/client_context.h:195
point
Definition: bloaty/third_party/zlib/examples/zran.c:67
client_context.h
credentials.h
cv
unsigned cv
Definition: cxa_demangle.cpp:4908
count
int * count
Definition: bloaty/third_party/googletest/googlemock/test/gmock_stress_test.cc:96
RouteGuideClient::RouteGuideClient
RouteGuideClient(std::shared_ptr< Channel > channel, const std::string &db)
Definition: route_guide_callback_client.cc:76
bm_diff.note
note
Definition: bm_diff.py:274
route_guide_pb2.Rectangle
Rectangle
Definition: multiplex/route_guide_pb2.py:249
ret
UniquePtr< SSL_SESSION > ret
Definition: ssl_x509.cc:1029
helper.h
grpc::protobuf::util::Status
GRPC_CUSTOM_UTIL_STATUS Status
Definition: include/grpcpp/impl/codegen/config_protobuf.h:93
grpc::Status
Definition: include/grpcpp/impl/codegen/status.h:35
ok
bool ok
Definition: async_end2end_test.cc:197
absl::Status::ok
ABSL_MUST_USE_RESULT bool ok() const
Definition: third_party/abseil-cpp/absl/status/status.h:802
generator_
Generator generator_
Definition: bloaty/third_party/protobuf/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc:124
context
grpc::ClientContext context
Definition: istio_echo_server_lib.cc:61
grpc::InsecureChannelCredentials
std::shared_ptr< ChannelCredentials > InsecureChannelCredentials()
Credentials for an unencrypted, unauthenticated channel.
Definition: cpp/client/insecure_credentials.cc:69
run_grpclb_interop_tests.l
dictionary l
Definition: run_grpclb_interop_tests.py:410
grpc::Alarm
Definition: grpcpp/alarm.h:35
RouteGuideClient
Definition: route_guide_callback_client.cc:74
RouteGuideClient::feature_list_
std::vector< Feature > feature_list_
Definition: route_guide_callback_client.cc:339
RouteGuideClient::GetFeature
void GetFeature()
Definition: route_guide_callback_client.cc:81
if
if(p->owned &&p->wrapped !=NULL)
Definition: call.c:42
reader
void reader(void *n)
Definition: libuv/docs/code/locks/main.c:8
create_channel.h
route_guide_pb2.Feature
Feature
Definition: multiplex/route_guide_pb2.py:256
RouteGuideClient::GetOneFeature
bool GetOneFeature(const Point &point, Feature *feature)
Definition: route_guide_callback_client.cc:298
route_guide_pb2.RouteNote
RouteNote
Definition: multiplex/route_guide_pb2.py:263


grpc
Author(s):
autogenerated on Thu Mar 13 2025 03:01:12