xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/error_details/greeter_client.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 <condition_variable>
16 #include <iostream>
17 #include <memory>
18 #include <mutex>
19 #include <string>
20 
21 #include "absl/flags/flag.h"
22 #include "absl/flags/parse.h"
23 #include "absl/strings/str_format.h"
24 
25 #include <grpcpp/grpcpp.h>
26 
27 #ifdef BAZEL_BUILD
28 #include "examples/protos/helloworld.grpc.pb.h"
29 #include "google/rpc/error_details.pb.h"
30 
31 #include "src/proto/grpc/status/status.pb.h"
32 #else
33 #include "error_details.pb.h"
34 #include "helloworld.grpc.pb.h"
35 #include "status.pb.h"
36 #endif
37 
38 ABSL_FLAG(std::string, target, "localhost:50051", "Server address");
39 
40 using grpc::Channel;
41 using grpc::ClientContext;
42 using grpc::Status;
43 using helloworld::Greeter;
44 using helloworld::HelloReply;
45 using helloworld::HelloRequest;
46 
47 class GreeterClient {
48  public:
GreeterClient(std::shared_ptr<Channel> channel)49   GreeterClient(std::shared_ptr<Channel> channel)
50       : stub_(Greeter::NewStub(channel)) {}
51 
52   // Assembles the client's payload, sends it and prints the response back
53   // from the server.
SayHello(const std::string & user)54   void SayHello(const std::string& user) {
55     // Data we are sending to the server.
56     HelloRequest request;
57     request.set_name(user);
58     // Container for the data we expect from the server.
59     HelloReply reply;
60     // Context for the client. It could be used to convey extra information to
61     // the server and/or tweak certain RPC behaviors.
62     ClientContext context;
63     // The actual RPC.
64     std::mutex mu;
65     std::condition_variable cv;
66     bool done = false;
67     Status status;
68     std::cout << absl::StrFormat("### Send: SayHello(name=%s)", user)
69               << std::endl;
70     stub_->async()->SayHello(&context, &request, &reply, [&](Status s) {
71       status = std::move(s);
72       std::lock_guard<std::mutex> lock(mu);
73       done = true;
74       cv.notify_one();
75     });
76     std::unique_lock<std::mutex> lock(mu);
77     while (!done) {
78       cv.wait(lock);
79     }
80     // Handles the reply
81     if (status.ok()) {
82       std::cout << absl::StrFormat("Ok. ReplyMessage=%s", reply.message())
83                 << std::endl;
84     } else {
85       std::cout << absl::StrFormat("Failed. Code=%d Message=%s",
86                                    status.error_code(), status.error_message())
87                 << std::endl;
88       PrintErrorDetails(status);
89     }
90   }
91 
PrintErrorDetails(grpc::Status status)92   void PrintErrorDetails(grpc::Status status) {
93     auto error_details = status.error_details();
94     if (error_details.empty()) {
95       return;
96     }
97     // If error_details are present in the status, this tries to deserialize
98     // those assuming they're proto messages.
99     google::rpc::Status s;
100     if (!s.ParseFromString(error_details)) {
101       std::cout << "Failed to deserialize `error_details`" << std::endl;
102       return;
103     }
104     std::cout << absl::StrFormat("Details:") << std::endl;
105     for (auto& detail : s.details()) {
106       google::rpc::QuotaFailure quota_failure;
107       if (detail.UnpackTo(&quota_failure)) {
108         for (auto& violation : quota_failure.violations()) {
109           std::cout << absl::StrFormat("- Quota: subject=%s description=%s",
110                                        violation.subject(),
111                                        violation.description())
112                     << std::endl;
113         }
114       } else {
115         std::cout << "Unknown error_detail: " + detail.type_url() << std::endl;
116       }
117     }
118   }
119 
120  private:
121   std::unique_ptr<Greeter::Stub> stub_;
122 };
123 
main(int argc,char ** argv)124 int main(int argc, char** argv) {
125   absl::ParseCommandLine(argc, argv);
126   // Instantiate the client. It requires a channel, out of which the actual RPCs
127   // are created. This channel models a connection to an endpoint specified by
128   // the argument "--target=" which is the only expected argument.
129   std::string target_str = absl::GetFlag(FLAGS_target);
130   // We indicate that the channel isn't authenticated (use of
131   // InsecureChannelCredentials()).
132   GreeterClient greeter(
133       grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
134   // Sends a first new name, expecting OK
135   greeter.SayHello("World");
136   // Sends a duplicate name, expecting RESOURCE_EXHAUSTED with error_details
137   greeter.SayHello("World");
138   return 0;
139 }
140