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