Debian Codegraph @

examples/python/retry/flaky_server.py

raw
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 """A flaky backend for the gRPC Python retry example."""
15
16 import asyncio
17 import collections
18 import logging
19 import random
20
21 import grpc
22
23 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
24 "helloworld.proto")
25
26
27 class ErrorInjectingGreeter(helloworld_pb2_grpc.GreeterServicer):
28
29 def __init__(self):
30 self._counter = collections.defaultdict(int)
31
32 async def SayHello(
33 self, request: helloworld_pb2.HelloRequest,
34 context: grpc.aio.ServicerContext) -> helloworld_pb2.HelloReply:
35 self._counter[context.peer()] += 1
36 if self._counter[context.peer()] < 5:
37 if random.random() < 0.75:
38 logging.info('Injecting error to RPC from %s', context.peer())
39 await context.abort(grpc.StatusCode.UNAVAILABLE,
40 'injected error')
41 logging.info('Successfully responding to RPC from %s', context.peer())
42 return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
43
44
45 async def serve() -> None:
46 server = grpc.aio.server()
47 helloworld_pb2_grpc.add_GreeterServicer_to_server(ErrorInjectingGreeter(),
48 server)
49 listen_addr = '[::]:50051'
50 server.add_insecure_port(listen_addr)
51 logging.info("Starting flaky server on %s", listen_addr)
52 await server.start()
53 await server.wait_for_termination()
54
55
56 if __name__ == '__main__':
57 logging.basicConfig(level=logging.INFO)
58 asyncio.run(serve())