xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/error_details/greeter_server.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2023 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 
15 #include <iostream>
16 #include <memory>
17 #include <string>
18 #include <unordered_set>
19 
20 #include "absl/flags/flag.h"
21 #include "absl/flags/parse.h"
22 #include "absl/strings/str_format.h"
23 #include "absl/synchronization/mutex.h"
24 
25 #include <grpcpp/ext/proto_server_reflection_plugin.h>
26 #include <grpcpp/grpcpp.h>
27 #include <grpcpp/health_check_service_interface.h>
28 
29 #ifdef BAZEL_BUILD
30 #include "examples/protos/helloworld.grpc.pb.h"
31 #include "google/rpc/error_details.pb.h"
32 
33 #include "src/proto/grpc/status/status.pb.h"
34 #else
35 #include "error_details.pb.h"
36 #include "helloworld.grpc.pb.h"
37 #include "status.pb.h"
38 #endif
39 
40 ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
41 
42 using grpc::CallbackServerContext;
43 using grpc::Server;
44 using grpc::ServerBuilder;
45 using grpc::ServerUnaryReactor;
46 using grpc::Status;
47 using grpc::StatusCode;
48 using helloworld::Greeter;
49 using helloworld::HelloReply;
50 using helloworld::HelloRequest;
51 
52 // Logic and data behind the server's behavior.
53 class GreeterServiceImpl final : public Greeter::CallbackService {
SayHello(CallbackServerContext * context,const HelloRequest * request,HelloReply * reply)54   ServerUnaryReactor* SayHello(CallbackServerContext* context,
55                                const HelloRequest* request,
56                                HelloReply* reply) override {
57     ServerUnaryReactor* reactor = context->DefaultReactor();
58     Status status;
59     // Checks whether it is a duplicate request
60     if (CheckRequestDuplicate(request->name())) {
61       // Returns an error status with more detailed information.
62       // In this example, the status has additional google::rpc::QuotaFailure
63       // conveying additional information about the error.
64       google::rpc::QuotaFailure quota_failure;
65       auto violation = quota_failure.add_violations();
66       violation->set_subject("name: " + request->name());
67       violation->set_description("Limit one greeting per person");
68       google::rpc::Status s;
69       s.set_code(static_cast<int>(StatusCode::RESOURCE_EXHAUSTED));
70       s.set_message("Request limit exceeded");
71       s.add_details()->PackFrom(quota_failure);
72       status = Status(StatusCode::RESOURCE_EXHAUSTED, "Request limit exceeded",
73                       s.SerializeAsString());
74     } else {
75       reply->set_message(absl::StrFormat("Hello %s", request->name()));
76       status = Status::OK;
77     }
78     reactor->Finish(status);
79     return reactor;
80   }
81 
82  private:
CheckRequestDuplicate(const std::string & name)83   bool CheckRequestDuplicate(const std::string& name) {
84     absl::MutexLock lock(&mu_);
85     return !request_name_set_.insert(name).second;
86   }
87 
88   absl::Mutex mu_;
89   std::unordered_set<std::string> request_name_set_;
90 };
91 
RunServer(uint16_t port)92 void RunServer(uint16_t port) {
93   std::string server_address = absl::StrFormat("0.0.0.0:%d", port);
94   GreeterServiceImpl service;
95 
96   grpc::EnableDefaultHealthCheckService(true);
97   grpc::reflection::InitProtoReflectionServerBuilderPlugin();
98   ServerBuilder builder;
99   // Listen on the given address without any authentication mechanism.
100   builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
101   // Register "service" as the instance through which we'll communicate with
102   // clients. In this case it corresponds to an *synchronous* service.
103   builder.RegisterService(&service);
104   // Finally assemble the server.
105   std::unique_ptr<Server> server(builder.BuildAndStart());
106   std::cout << "Server listening on " << server_address << std::endl;
107 
108   // Wait for the server to shutdown. Note that some other thread must be
109   // responsible for shutting down the server for this call to ever return.
110   server->Wait();
111 }
112 
main(int argc,char ** argv)113 int main(int argc, char** argv) {
114   absl::ParseCommandLine(argc, argv);
115   RunServer(absl::GetFlag(FLAGS_port));
116   return 0;
117 }
118