xref: /aosp_15_r20/external/grpc-grpc/examples/python/retry/async_retry_client.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1# Copyright 2021 The 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"""The Python AsyncIO implementation of the gRPC client-side retry example."""
15
16import asyncio
17import json
18import logging
19
20import grpc
21
22helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
23    "helloworld.proto"
24)
25
26
27async def run() -> None:
28    # The ServiceConfig proto definition can be found:
29    # https://github.com/grpc/grpc-proto/blob/ec886024c2f7b7f597ba89d5b7d60c3f94627b17/grpc/service_config/service_config.proto#L377
30    service_config_json = json.dumps(
31        {
32            "methodConfig": [
33                {
34                    # To apply retry to all methods, put [{}] in the "name" field
35                    "name": [
36                        {"service": "helloworld.Greeter", "method": "SayHello"}
37                    ],
38                    "retryPolicy": {
39                        "maxAttempts": 5,
40                        "initialBackoff": "0.1s",
41                        "maxBackoff": "1s",
42                        "backoffMultiplier": 2,
43                        "retryableStatusCodes": ["UNAVAILABLE"],
44                    },
45                }
46            ]
47        }
48    )
49    options = []
50    # NOTE: the retry feature will be enabled by default >=v1.40.0
51    options.append(("grpc.enable_retries", 1))
52    options.append(("grpc.service_config", service_config_json))
53    async with grpc.aio.insecure_channel(
54        "localhost:50051", options=options
55    ) as channel:
56        stub = helloworld_pb2_grpc.GreeterStub(channel)
57        response = await stub.SayHello(helloworld_pb2.HelloRequest(name="you"))
58    print("Greeter client received: " + response.message)
59
60
61if __name__ == "__main__":
62    logging.basicConfig()
63    asyncio.run(run())
64