Debian Codegraph @

src/python/grpcio_testing/grpc_testing/_server/_service.py

raw
1 # Copyright 2017 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
15 import copy
16
17 import grpc
18
19
20 class _RequestIterator(object):
21
22 def __init__(self, rpc, handler):
23 self._rpc = rpc
24 self._handler = handler
25
26 def _next(self):
27 read = self._handler.take_request()
28 if read.requests_closed:
29 raise StopIteration()
30 elif read.terminated:
31 rpc_error = grpc.RpcError()
32 self._rpc.add_rpc_error(rpc_error)
33 raise rpc_error
34 else:
35 return read.request
36
37 def __iter__(self):
38 return self
39
40 def __next__(self):
41 return self._next()
42
43 def next(self):
44 return self._next()
45
46
47 def _unary_response(argument, implementation, rpc, servicer_context):
48 try:
49 response = implementation(argument, servicer_context)
50 except Exception as exception: # pylint: disable=broad-except
51 rpc.application_exception_abort(exception)
52 else:
53 rpc.unary_response_complete(response)
54
55
56 def _stream_response(argument, implementation, rpc, servicer_context):
57 try:
58 response_iterator = implementation(argument, servicer_context)
59 except Exception as exception: # pylint: disable=broad-except
60 rpc.application_exception_abort(exception)
61 else:
62 while True:
63 try:
64 response = copy.deepcopy(next(response_iterator))
65 except StopIteration:
66 rpc.stream_response_complete()
67 break
68 except Exception as exception: # pylint: disable=broad-except
69 rpc.application_exception_abort(exception)
70 break
71 else:
72 rpc.stream_response(response)
73
74
75 def unary_unary(implementation, rpc, request, servicer_context):
76 _unary_response(request, implementation, rpc, servicer_context)
77
78
79 def unary_stream(implementation, rpc, request, servicer_context):
80 _stream_response(request, implementation, rpc, servicer_context)
81
82
83 def stream_unary(implementation, rpc, handler, servicer_context):
84 _unary_response(_RequestIterator(rpc, handler), implementation, rpc,
85 servicer_context)
86
87
88 def stream_stream(implementation, rpc, handler, servicer_context):
89 _stream_response(_RequestIterator(rpc, handler), implementation, rpc,
90 servicer_context)