flaky_server.py 2.0 KB

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