flaky_server.py
Go to the documentation of this file.
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 
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()
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())
flaky_server.ErrorInjectingGreeter.SayHello
helloworld_pb2.HelloReply SayHello(self, helloworld_pb2.HelloRequest request, grpc.aio.ServicerContext context)
Definition: flaky_server.py:32
flaky_server.ErrorInjectingGreeter._counter
_counter
Definition: flaky_server.py:30
flaky_server.ErrorInjectingGreeter
Definition: flaky_server.py:27
flaky_server.serve
None serve()
Definition: flaky_server.py:45
helloworld_pb2.HelloReply
HelloReply
Definition: helloworld/helloworld_pb2.py:100
flaky_server.ErrorInjectingGreeter.__init__
def __init__(self)
Definition: flaky_server.py:29
helloworld_pb2_grpc.GreeterServicer
Definition: helloworld/helloworld_pb2_grpc.py:24
grpc.aio._base_server.ServicerContext
Definition: _base_server.py:138
helloworld_pb2_grpc.add_GreeterServicer_to_server
def add_GreeterServicer_to_server(servicer, server)
Definition: helloworld/helloworld_pb2_grpc.py:36


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:59:21