| 1 |
# Copyright 2019 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 |
"""This example sends out rich error status from server-side.""" |
| 15 |
|
| 16 |
from concurrent import futures |
| 17 |
import logging |
| 18 |
import threading |
| 19 |
|
| 20 |
from google.protobuf import any_pb2 |
| 21 |
from google.rpc import code_pb2 |
| 22 |
from google.rpc import error_details_pb2 |
| 23 |
from google.rpc import status_pb2 |
| 24 |
import grpc |
| 25 |
from grpc_status import rpc_status |
| 26 |
|
| 27 |
from examples.protos import helloworld_pb2 |
| 28 |
from examples.protos import helloworld_pb2_grpc |
| 29 |
|
| 30 |
|
| 31 |
def create_greet_limit_exceed_error_status(name): |
| 32 |
detail = any_pb2.Any() |
| 33 |
detail.Pack( |
| 34 |
error_details_pb2.QuotaFailure(violations=[ |
| 35 |
error_details_pb2.QuotaFailure.Violation( |
| 36 |
subject="name: %s" % name, |
| 37 |
description="Limit one greeting per person", |
| 38 |
) |
| 39 |
],)) |
| 40 |
return status_pb2.Status( |
| 41 |
code=code_pb2.RESOURCE_EXHAUSTED, |
| 42 |
message='Request limit exceeded.', |
| 43 |
details=[detail], |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
class LimitedGreeter(helloworld_pb2_grpc.GreeterServicer): |
| 48 |
|
| 49 |
def __init__(self): |
| 50 |
self._lock = threading.RLock() |
| 51 |
self._greeted = set() |
| 52 |
|
| 53 |
def SayHello(self, request, context): |
| 54 |
with self._lock: |
| 55 |
if request.name in self._greeted: |
| 56 |
rich_status = create_greet_limit_exceed_error_status( |
| 57 |
request.name) |
| 58 |
context.abort_with_status(rpc_status.to_status(rich_status)) |
| 59 |
else: |
| 60 |
self._greeted.add(request.name) |
| 61 |
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
| 62 |
|
| 63 |
|
| 64 |
def create_server(server_address): |
| 65 |
server = grpc.server(futures.ThreadPoolExecutor()) |
| 66 |
helloworld_pb2_grpc.add_GreeterServicer_to_server(LimitedGreeter(), server) |
| 67 |
port = server.add_insecure_port(server_address) |
| 68 |
return server, port |
| 69 |
|
| 70 |
|
| 71 |
def serve(server): |
| 72 |
server.start() |
| 73 |
server.wait_for_termination() |
| 74 |
|
| 75 |
|
| 76 |
def main(): |
| 77 |
server, unused_port = create_server('[::]:50051') |
| 78 |
serve(server) |
| 79 |
|
| 80 |
|
| 81 |
if __name__ == '__main__': |
| 82 |
logging.basicConfig() |
| 83 |
main() |