[Example] Update route_guide example (#36930)

The intention behind this PR is to improve the example to aid the upcoming callback API guide.

Also fixes #25823

Closes #36930

PiperOrigin-RevId: 644166441
pull/36958/head
Yash Tibrewal 5 months ago committed by Copybara-Service
parent 1f6978f155
commit 1071ada87c
  1. 5
      examples/cpp/route_guide/BUILD
  2. 8
      examples/cpp/route_guide/CMakeLists.txt
  3. 1
      examples/cpp/route_guide/Makefile
  4. 20
      examples/cpp/route_guide/README.md
  5. 37
      examples/cpp/route_guide/helper.cc
  6. 71
      examples/cpp/route_guide/route_guide_callback_server.cc

@ -24,6 +24,7 @@ cc_library(
deps = [
"//:grpc++",
"//examples/protos:route_guide",
"@com_google_absl//absl/log",
],
)
@ -80,5 +81,9 @@ cc_binary(
":route_guide_helper",
"//:grpc++",
"//examples/protos:route_guide",
"@com_google_absl//absl/flags:parse",
"@com_google_absl//absl/log",
"@com_google_absl//absl/log:globals",
"@com_google_absl//absl/log:initialize",
],
)

@ -23,6 +23,9 @@ project(RouteGuide C CXX)
include(../cmake/common.cmake)
# Find absl package
find_package(absl CONFIG REQUIRED)
# Proto file
get_filename_component(rg_proto "../../protos/route_guide.proto" ABSOLUTE)
get_filename_component(rg_proto_path "${rg_proto}" PATH)
@ -52,6 +55,7 @@ add_library(rg_grpc_proto
${rg_proto_srcs}
${rg_proto_hdrs})
target_link_libraries(rg_grpc_proto
absl::absl_log
${_REFLECTION}
${_GRPC_GRPCPP}
${_PROTOBUF_LIBPROTOBUF})
@ -74,6 +78,10 @@ foreach(_target
target_link_libraries(${_target}
rg_grpc_proto
route_guide_helper
absl::flags_parse
absl::absl_log
absl::log_initialize
absl::log_globals
${_REFLECTION}
${_GRPC_GRPCPP}
${_PROTOBUF_LIBPROTOBUF})

@ -30,6 +30,7 @@ CXXFLAGS += -std=c++14
ifeq ($(SYSTEM),Darwin)
LDFLAGS += -L/usr/local/lib `pkg-config --libs --static protobuf grpc++ $(PROTOBUF_ABSL_DEPS)`\
$(PROTOBUF_UTF8_RANGE_LINK_LIBS) \
-labsl_flags_parse -labsl_absl_log -labsl_log_globals -labsl_log_initialize
-pthread\
-lgrpc++_reflection\
-ldl

@ -4,3 +4,23 @@ The files in this folder are the samples used in [gRPC Basics: C++][],
a detailed tutorial for using gRPC in C++.
[gRPC Basics: C++]:https://grpc.io/docs/languages/cpp/basics
## Configuration
The RouteGuide proto definition is available [here](../../protos/route_guide.proto).
The server takes the following command-line argument -
* db_path - Path to json file containing database. Defaults to `examples/cpp/route_guide/route_guide_db.json` on bazel builds, and `route_guide_db.json` for non-bazel builds.
## Running the example
To run the server -
```
$ tools/bazel run examples/cpp/route_guide:route_guide_callback_server
```
To run the client -
```
$ tools/bazel run examples/cpp/route_guide:route_guide_callback_client
```

@ -23,36 +23,30 @@
#include <sstream>
#include <string>
#include <vector>
#include "absl/flags/flag.h"
#include "absl/log/log.h"
#ifdef BAZEL_BUILD
#include "examples/protos/route_guide.grpc.pb.h"
#else
#include "route_guide.grpc.pb.h"
#endif
namespace routeguide {
std::string GetDbFileContent(int argc, char** argv) {
std::string db_path;
std::string arg_str("--db_path");
if (argc > 1) {
std::string argv_1 = argv[1];
size_t start_position = argv_1.find(arg_str);
if (start_position != std::string::npos) {
start_position += arg_str.size();
if (argv_1[start_position] == ' ' || argv_1[start_position] == '=') {
db_path = argv_1.substr(start_position + 1);
}
}
} else {
#ifdef BAZEL_BUILD
db_path = "cpp/route_guide/route_guide_db.json";
ABSL_FLAG(std::string, db_path, "examples/cpp/route_guide/route_guide_db.json",
"Path to db file");
#else
db_path = "route_guide_db.json";
ABSL_FLAG(std::string, db_path, "route_guide_db.json", "Path to db file");
#endif
}
namespace routeguide {
std::string GetDbFileContent(int argc, char** argv) {
std::string db_path = absl::GetFlag(FLAGS_db_path);
std::ifstream db_file(db_path);
if (!db_file.is_open()) {
std::cout << "Failed to open " << db_path << std::endl;
LOG(ERROR) << "Failed to open " << db_path;
abort();
}
std::stringstream db;
@ -152,13 +146,12 @@ void ParseDb(const std::string& db, std::vector<Feature>* feature_list) {
while (!parser.Finished()) {
feature_list->push_back(Feature());
if (!parser.TryParseOne(&feature_list->back())) {
std::cout << "Error parsing the db file";
LOG(ERROR) << "Error parsing the db file";
feature_list->clear();
break;
}
}
std::cout << "DB parsed, loaded " << feature_list->size() << " features."
<< std::endl;
LOG(INFO) << "DB parsed, loaded " << feature_list->size() << " features.";
}
} // namespace routeguide

@ -24,6 +24,10 @@
#include <string>
#include <thread>
#include "absl/flags/parse.h"
#include "absl/log/globals.h"
#include "absl/log/initialize.h"
#include "absl/log/log.h"
#include "helper.h"
#include <grpc/grpc.h>
@ -88,6 +92,30 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
routeguide::ParseDb(db, &feature_list_);
}
grpc::ServerUnaryReactor* GetFeature(grpc::CallbackServerContext* context,
const Point* point,
Feature* feature) override {
class Reactor : public grpc::ServerUnaryReactor {
public:
Reactor(const Point& point, const std::vector<Feature>& feature_list,
Feature* feature) {
feature->set_name(GetFeatureName(point, feature_list));
*feature->mutable_location() = point;
Finish(grpc::Status::OK);
}
private:
void OnDone() override {
LOG(INFO) << "RPC Completed";
delete this;
}
void OnCancel() override { LOG(ERROR) << "RPC Cancelled"; }
};
return new Reactor(*point, feature_list_, feature);
}
/* Alternate simple implementation of GetFeature that uses the DefaultReactor.
grpc::ServerUnaryReactor* GetFeature(CallbackServerContext* context,
const Point* point,
Feature* feature) override {
@ -97,6 +125,7 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
reactor->Finish(Status::OK);
return reactor;
}
*/
grpc::ServerWriteReactor<Feature>* ListFeatures(
CallbackServerContext* context,
@ -117,8 +146,20 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
next_feature_(feature_list_->begin()) {
NextWrite();
}
void OnDone() override { delete this; }
void OnWriteDone(bool /*ok*/) override { NextWrite(); }
void OnWriteDone(bool ok) override {
if (!ok) {
Finish(Status(grpc::StatusCode::UNKNOWN, "Unexpected Failure"));
}
NextWrite();
}
void OnDone() override {
LOG(INFO) << "RPC Completed";
delete this;
}
void OnCancel() override { LOG(ERROR) << "RPC Cancelled"; }
private:
void NextWrite() {
@ -156,7 +197,7 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
feature_list_(feature_list) {
StartRead(&point_);
}
void OnDone() override { delete this; }
void OnReadDone(bool ok) override {
if (ok) {
point_count_++;
@ -179,6 +220,13 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
}
}
void OnDone() override {
LOG(INFO) << "RPC Completed";
delete this;
}
void OnCancel() override { LOG(ERROR) << "RPC Cancelled"; }
private:
system_clock::time_point start_time_;
RouteSummary* summary_;
@ -200,7 +248,7 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
: mu_(mu), received_notes_(received_notes) {
StartRead(&note_);
}
void OnDone() override { delete this; }
void OnReadDone(bool ok) override {
if (ok) {
// Unlike the other example in this directory that's not using
@ -228,6 +276,13 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
}
void OnWriteDone(bool /*ok*/) override { NextWrite(); }
void OnDone() override {
LOG(INFO) << "RPC Completed";
delete this;
}
void OnCancel() override { LOG(ERROR) << "RPC Cancelled"; }
private:
void NextWrite() {
if (notes_iterator_ != to_send_notes_.end()) {
@ -240,9 +295,10 @@ class RouteGuideImpl final : public RouteGuide::CallbackService {
StartRead(&note_);
}
}
RouteNote note_;
absl::Mutex* mu_;
std::vector<RouteNote>* received_notes_;
std::vector<RouteNote>* received_notes_ ABSL_GUARDED_BY(mu_);
std::vector<RouteNote> to_send_notes_;
std::vector<RouteNote>::iterator notes_iterator_;
};
@ -263,11 +319,14 @@ void RunServer(const std::string& db_path) {
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
LOG(INFO) << "Server listening on " << server_address;
server->Wait();
}
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo);
absl::InitializeLog();
// Expect only arg: --db_path=path/to/route_guide_db.json.
std::string db = routeguide::GetDbFileContent(argc, argv);
RunServer(db);

Loading…
Cancel
Save