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