[example] Add C++ retry example (#37034)

<!--

If you know who should review your pull request, please assign it to that
person, otherwise the pull request would get assigned randomly.

If your pull request is for a specific language, please add the appropriate
lang label.

-->

Closes #37034

PiperOrigin-RevId: 646276954
pull/37003/head^2
Yijie Ma 5 months ago committed by Copybara-Service
parent fa84360551
commit 1913e16526
  1. 38
      examples/cpp/retry/BUILD
  2. 73
      examples/cpp/retry/CMakeLists.txt
  3. 69
      examples/cpp/retry/README.md
  4. 98
      examples/cpp/retry/client.cc
  5. 86
      examples/cpp/retry/server.cc

@ -0,0 +1,38 @@
# Copyright 2024 the gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
licenses(["notice"])
cc_binary(
name = "client",
srcs = ["client.cc"],
defines = ["BAZEL_BUILD"],
deps = [
"//:grpc++",
"//examples/protos:helloworld_cc_grpc",
"@com_google_absl//absl/strings:string_view",
],
)
cc_binary(
name = "server",
srcs = ["server.cc"],
defines = ["BAZEL_BUILD"],
deps = [
"//:grpc++",
"//:grpc++_reflection",
"//examples/protos:helloworld_cc_grpc",
"@com_google_absl//absl/strings:str_format",
],
)

@ -0,0 +1,73 @@
# Copyright 2024 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# cmake build file for C++ retry example.
# Assumes protobuf and gRPC have been installed using cmake.
# See cmake_externalproject/CMakeLists.txt for all-in-one cmake build
# that automatically builds all the dependencies before building retry.
cmake_minimum_required(VERSION 3.8)
project(Retry C CXX)
include(../cmake/common.cmake)
# Proto file
get_filename_component(hw_proto "../../protos/helloworld.proto" ABSOLUTE)
get_filename_component(hw_proto_path "${hw_proto}" PATH)
# Generated sources
set(hw_proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.cc")
set(hw_proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.h")
set(hw_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.cc")
set(hw_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.h")
add_custom_command(
OUTPUT "${hw_proto_srcs}" "${hw_proto_hdrs}" "${hw_grpc_srcs}" "${hw_grpc_hdrs}"
COMMAND ${_PROTOBUF_PROTOC}
ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}"
--cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
-I "${hw_proto_path}"
--plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
"${hw_proto}"
DEPENDS "${hw_proto}")
# Include generated *.pb.h files
include_directories("${CMAKE_CURRENT_BINARY_DIR}")
# hw_grpc_proto
add_library(hw_grpc_proto
${hw_grpc_srcs}
${hw_grpc_hdrs}
${hw_proto_srcs}
${hw_proto_hdrs})
target_link_libraries(hw_grpc_proto
absl::check
${_REFLECTION}
${_GRPC_GRPCPP}
${_PROTOBUF_LIBPROTOBUF})
# Targets (client|server)
foreach(_target
client server)
add_executable(${_target} "${_target}.cc")
target_link_libraries(${_target}
hw_grpc_proto
absl::check
absl::flags
absl::flags_parse
absl::log
${_REFLECTION}
${_GRPC_GRPCPP}
${_PROTOBUF_LIBPROTOBUF})
endforeach()

@ -0,0 +1,69 @@
# Retry
This example shows how to enable and configure retry on gRPC clients.
## Documentation
[gRFC for client-side retry support](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)
## Try it
This example includes a service implementation that fails requests three times with status
code `Unavailable`, then passes the fourth. The client is configured to make four retry attempts
when receiving an `Unavailable` status code.
First start the server:
```bash
$ ./server
```
Then run the client:
```bash
$ ./client
```
Expected server output:
```
Server listening on 0.0.0.0:50052
return UNAVAILABLE
return UNAVAILABLE
return UNAVAILABLE
return OK
```
Expected client output:
```
Greeter received: Hello world
```
## Usage
### Define your retry policy
Retry is enabled via the service config, which can be provided by the name resolver or
a [GRPC_ARG_SERVICE_CONFIG](https://github.com/grpc/grpc/blob/master/include/grpc/impl/channel_arg_names.h#L207-L209) channel argument. In the below config, we set retry policy for the "helloworld.Greeter" service.
`maxAttempts`: how many times to attempt the RPC before failing.
`initialBackoff`, `maxBackoff`, `backoffMultiplier`: configures delay between attempts.
`retryableStatusCodes`: Retry only when receiving these status codes.
```c++
constexpr absl::string_view kRetryPolicy =
"{\"methodConfig\" : [{"
" \"name\" : [{\"service\": \"helloworld.Greeter\"}],"
" \"waitForReady\": true,"
" \"retryPolicy\": {"
" \"maxAttempts\": 4,"
" \"initialBackoff\": \"1s\","
" \"maxBackoff\": \"120s\","
" \"backoffMultiplier\": 1.0,"
" \"retryableStatusCodes\": [\"UNAVAILABLE\"]"
" }"
"}]}";
```

@ -0,0 +1,98 @@
/*
* Copyright 2024 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <memory>
#include <string>
#include "absl/strings/string_view.h"
#include <grpcpp/grpcpp.h>
#include <grpcpp/support/status.h>
#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
constexpr absl::string_view kTargetAddress = "localhost:50052";
// clang-format off
constexpr absl::string_view kRetryPolicy =
"{\"methodConfig\" : [{"
" \"name\" : [{\"service\": \"helloworld.Greeter\"}],"
" \"waitForReady\": true,"
" \"retryPolicy\": {"
" \"maxAttempts\": 4,"
" \"initialBackoff\": \"1s\","
" \"maxBackoff\": \"120s\","
" \"backoffMultiplier\": 1.0,"
" \"retryableStatusCodes\": [\"UNAVAILABLE\"]"
" }"
"}]}";
// clang-format on
class GreeterClient {
public:
GreeterClient(std::shared_ptr<Channel> channel)
: stub_(Greeter::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
std::string SayHello(const std::string& user) {
// Data we are sending to the server.
HelloRequest request;
request.set_name(user);
// Container for the data we expect from the server.
HelloReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->SayHello(&context, request, &reply);
// Act upon its status.
if (status.ok()) {
return reply.message();
} else {
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
private:
std::unique_ptr<Greeter::Stub> stub_;
};
int main() {
auto channel_args = grpc::ChannelArguments();
channel_args.SetServiceConfigJSON(std::string(kRetryPolicy));
GreeterClient greeter(grpc::CreateCustomChannel(
std::string(kTargetAddress), grpc::InsecureChannelCredentials(),
channel_args));
std::string user("world");
std::string reply = greeter.SayHello(user);
std::cout << "Greeter received: " << reply << std::endl;
return 0;
}

@ -0,0 +1,86 @@
/*
* Copyright 2024 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>
#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service {
public:
Status SayHello(ServerContext* context, const HelloRequest* request,
HelloReply* reply) override {
if (++request_counter_ % request_modulo_ != 0) {
// Return an OK status for every request_modulo_ number of requests,
// return UNAVAILABLE otherwise.
std::cout << "return UNAVAILABLE" << std::endl;
return Status(StatusCode::UNAVAILABLE, "");
}
std::string prefix("Hello ");
reply->set_message(prefix + request->name());
std::cout << "return OK" << std::endl;
return Status::OK;
}
private:
static constexpr int request_modulo_ = 4;
int request_counter_ = 0;
};
void RunServer(uint16_t port) {
std::string server_address = absl::StrFormat("0.0.0.0:%d", port);
GreeterServiceImpl service;
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
ServerBuilder builder;
// Listen on the given address without any authentication mechanism.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
// Register "service" as the instance through which we'll communicate with
// clients. In this case it corresponds to an *synchronous* service.
builder.RegisterService(&service);
// Finally assemble the server.
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
// Wait for the server to shutdown. Note that some other thread must be
// responsible for shutting down the server for this call to ever return.
server->Wait();
}
int main(int argc, char** argv) {
RunServer(/*port=*/50052);
return 0;
}
Loading…
Cancel
Save