grpcio-fips 1.53.2__0-cp38-cp38-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- grpc/__init__.py +2174 -0
- grpc/_auth.py +68 -0
- grpc/_channel.py +1767 -0
- grpc/_common.py +177 -0
- grpc/_compression.py +63 -0
- grpc/_cython/__init__.py +13 -0
- grpc/_cython/_credentials/roots.pem +4337 -0
- grpc/_cython/_cygrpc/__init__.py +13 -0
- grpc/_cython/cygrpc.cp38-win_amd64.pyd +0 -0
- grpc/_grpcio_metadata.py +1 -0
- grpc/_interceptor.py +638 -0
- grpc/_plugin_wrapping.py +121 -0
- grpc/_runtime_protos.py +159 -0
- grpc/_server.py +1141 -0
- grpc/_simple_stubs.py +486 -0
- grpc/_typing.py +58 -0
- grpc/_utilities.py +180 -0
- grpc/aio/__init__.py +95 -0
- grpc/aio/_base_call.py +248 -0
- grpc/aio/_base_channel.py +348 -0
- grpc/aio/_base_server.py +369 -0
- grpc/aio/_call.py +649 -0
- grpc/aio/_channel.py +492 -0
- grpc/aio/_interceptor.py +1003 -0
- grpc/aio/_metadata.py +120 -0
- grpc/aio/_server.py +209 -0
- grpc/aio/_typing.py +35 -0
- grpc/aio/_utils.py +22 -0
- grpc/beta/__init__.py +13 -0
- grpc/beta/_client_adaptations.py +706 -0
- grpc/beta/_metadata.py +52 -0
- grpc/beta/_server_adaptations.py +385 -0
- grpc/beta/implementations.py +311 -0
- grpc/beta/interfaces.py +163 -0
- grpc/beta/utilities.py +149 -0
- grpc/experimental/__init__.py +128 -0
- grpc/experimental/aio/__init__.py +16 -0
- grpc/experimental/gevent.py +27 -0
- grpc/experimental/session_cache.py +45 -0
- grpc/framework/__init__.py +13 -0
- grpc/framework/common/__init__.py +13 -0
- grpc/framework/common/cardinality.py +26 -0
- grpc/framework/common/style.py +24 -0
- grpc/framework/foundation/__init__.py +13 -0
- grpc/framework/foundation/abandonment.py +22 -0
- grpc/framework/foundation/callable_util.py +94 -0
- grpc/framework/foundation/future.py +219 -0
- grpc/framework/foundation/logging_pool.py +71 -0
- grpc/framework/foundation/stream.py +43 -0
- grpc/framework/foundation/stream_util.py +148 -0
- grpc/framework/interfaces/__init__.py +13 -0
- grpc/framework/interfaces/base/__init__.py +13 -0
- grpc/framework/interfaces/base/base.py +325 -0
- grpc/framework/interfaces/base/utilities.py +71 -0
- grpc/framework/interfaces/face/__init__.py +13 -0
- grpc/framework/interfaces/face/face.py +1049 -0
- grpc/framework/interfaces/face/utilities.py +168 -0
- grpcio_fips-1.53.2.dist-info/LICENSE +610 -0
- grpcio_fips-1.53.2.dist-info/METADATA +139 -0
- grpcio_fips-1.53.2.dist-info/RECORD +62 -0
- grpcio_fips-1.53.2.dist-info/WHEEL +5 -0
- grpcio_fips-1.53.2.dist-info/top_level.txt +1 -0
grpc/_server.py
ADDED
|
@@ -0,0 +1,1141 @@
|
|
|
1
|
+
# Copyright 2016 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
|
+
"""Service-side implementation of gRPC Python."""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import collections
|
|
19
|
+
from concurrent import futures
|
|
20
|
+
import enum
|
|
21
|
+
import logging
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
import traceback
|
|
25
|
+
from typing import (Any, Callable, Iterable, Iterator, List, Mapping, Optional,
|
|
26
|
+
Sequence, Set, Tuple, Union)
|
|
27
|
+
|
|
28
|
+
import grpc # pytype: disable=pyi-error
|
|
29
|
+
from grpc import _common # pytype: disable=pyi-error
|
|
30
|
+
from grpc import _compression # pytype: disable=pyi-error
|
|
31
|
+
from grpc import _interceptor # pytype: disable=pyi-error
|
|
32
|
+
from grpc._cython import cygrpc
|
|
33
|
+
from grpc._typing import ArityAgnosticMethodHandler
|
|
34
|
+
from grpc._typing import ChannelArgumentType
|
|
35
|
+
from grpc._typing import DeserializingFunction
|
|
36
|
+
from grpc._typing import MetadataType
|
|
37
|
+
from grpc._typing import NullaryCallbackType
|
|
38
|
+
from grpc._typing import ResponseType
|
|
39
|
+
from grpc._typing import SerializingFunction
|
|
40
|
+
from grpc._typing import ServerCallbackTag
|
|
41
|
+
from grpc._typing import ServerTagCallbackType
|
|
42
|
+
|
|
43
|
+
_LOGGER = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
_SHUTDOWN_TAG = 'shutdown'
|
|
46
|
+
_REQUEST_CALL_TAG = 'request_call'
|
|
47
|
+
|
|
48
|
+
_RECEIVE_CLOSE_ON_SERVER_TOKEN = 'receive_close_on_server'
|
|
49
|
+
_SEND_INITIAL_METADATA_TOKEN = 'send_initial_metadata'
|
|
50
|
+
_RECEIVE_MESSAGE_TOKEN = 'receive_message'
|
|
51
|
+
_SEND_MESSAGE_TOKEN = 'send_message'
|
|
52
|
+
_SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN = (
|
|
53
|
+
'send_initial_metadata * send_message')
|
|
54
|
+
_SEND_STATUS_FROM_SERVER_TOKEN = 'send_status_from_server'
|
|
55
|
+
_SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN = (
|
|
56
|
+
'send_initial_metadata * send_status_from_server')
|
|
57
|
+
|
|
58
|
+
_OPEN = 'open'
|
|
59
|
+
_CLOSED = 'closed'
|
|
60
|
+
_CANCELLED = 'cancelled'
|
|
61
|
+
|
|
62
|
+
_EMPTY_FLAGS = 0
|
|
63
|
+
|
|
64
|
+
_DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0
|
|
65
|
+
_INF_TIMEOUT = 1e9
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _serialized_request(request_event: cygrpc.BaseEvent) -> bytes:
|
|
69
|
+
return request_event.batch_operations[0].message()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _application_code(code: grpc.StatusCode) -> cygrpc.StatusCode:
|
|
73
|
+
cygrpc_code = _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE.get(code)
|
|
74
|
+
return cygrpc.StatusCode.unknown if cygrpc_code is None else cygrpc_code
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _completion_code(state: _RPCState) -> cygrpc.StatusCode:
|
|
78
|
+
if state.code is None:
|
|
79
|
+
return cygrpc.StatusCode.ok
|
|
80
|
+
else:
|
|
81
|
+
return _application_code(state.code)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _abortion_code(state: _RPCState,
|
|
85
|
+
code: cygrpc.StatusCode) -> cygrpc.StatusCode:
|
|
86
|
+
if state.code is None:
|
|
87
|
+
return code
|
|
88
|
+
else:
|
|
89
|
+
return _application_code(state.code)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _details(state: _RPCState) -> bytes:
|
|
93
|
+
return b'' if state.details is None else state.details
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _HandlerCallDetails(
|
|
97
|
+
collections.namedtuple('_HandlerCallDetails', (
|
|
98
|
+
'method',
|
|
99
|
+
'invocation_metadata',
|
|
100
|
+
)), grpc.HandlerCallDetails):
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _RPCState(object):
|
|
105
|
+
condition: threading.Condition
|
|
106
|
+
due = Set[str]
|
|
107
|
+
request: Any
|
|
108
|
+
client: str
|
|
109
|
+
initial_metadata_allowed: bool
|
|
110
|
+
compression_algorithm: Optional[grpc.Compression]
|
|
111
|
+
disable_next_compression: bool
|
|
112
|
+
trailing_metadata: Optional[MetadataType]
|
|
113
|
+
code: Optional[grpc.StatusCode]
|
|
114
|
+
details: Optional[bytes]
|
|
115
|
+
statused: bool
|
|
116
|
+
rpc_errors: List[Exception]
|
|
117
|
+
callbacks: Optional[List[NullaryCallbackType]]
|
|
118
|
+
aborted: bool
|
|
119
|
+
|
|
120
|
+
def __init__(self):
|
|
121
|
+
self.condition = threading.Condition()
|
|
122
|
+
self.due = set()
|
|
123
|
+
self.request = None
|
|
124
|
+
self.client = _OPEN
|
|
125
|
+
self.initial_metadata_allowed = True
|
|
126
|
+
self.compression_algorithm = None
|
|
127
|
+
self.disable_next_compression = False
|
|
128
|
+
self.trailing_metadata = None
|
|
129
|
+
self.code = None
|
|
130
|
+
self.details = None
|
|
131
|
+
self.statused = False
|
|
132
|
+
self.rpc_errors = []
|
|
133
|
+
self.callbacks = []
|
|
134
|
+
self.aborted = False
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _raise_rpc_error(state: _RPCState) -> None:
|
|
138
|
+
rpc_error = grpc.RpcError()
|
|
139
|
+
state.rpc_errors.append(rpc_error)
|
|
140
|
+
raise rpc_error
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _possibly_finish_call(state: _RPCState,
|
|
144
|
+
token: str) -> ServerTagCallbackType:
|
|
145
|
+
state.due.remove(token)
|
|
146
|
+
if not _is_rpc_state_active(state) and not state.due:
|
|
147
|
+
callbacks = state.callbacks
|
|
148
|
+
state.callbacks = None
|
|
149
|
+
return state, callbacks
|
|
150
|
+
else:
|
|
151
|
+
return None, ()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _send_status_from_server(state: _RPCState, token: str) -> ServerCallbackTag:
|
|
155
|
+
|
|
156
|
+
def send_status_from_server(unused_send_status_from_server_event):
|
|
157
|
+
with state.condition:
|
|
158
|
+
return _possibly_finish_call(state, token)
|
|
159
|
+
|
|
160
|
+
return send_status_from_server
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _get_initial_metadata(
|
|
164
|
+
state: _RPCState,
|
|
165
|
+
metadata: Optional[MetadataType]) -> Optional[MetadataType]:
|
|
166
|
+
with state.condition:
|
|
167
|
+
if state.compression_algorithm:
|
|
168
|
+
compression_metadata = (
|
|
169
|
+
_compression.compression_algorithm_to_metadata(
|
|
170
|
+
state.compression_algorithm),)
|
|
171
|
+
if metadata is None:
|
|
172
|
+
return compression_metadata
|
|
173
|
+
else:
|
|
174
|
+
return compression_metadata + tuple(metadata)
|
|
175
|
+
else:
|
|
176
|
+
return metadata
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _get_initial_metadata_operation(
|
|
180
|
+
state: _RPCState, metadata: Optional[MetadataType]) -> cygrpc.Operation:
|
|
181
|
+
operation = cygrpc.SendInitialMetadataOperation(
|
|
182
|
+
_get_initial_metadata(state, metadata), _EMPTY_FLAGS)
|
|
183
|
+
return operation
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _abort(state: _RPCState, call: cygrpc.Call, code: cygrpc.StatusCode,
|
|
187
|
+
details: bytes) -> None:
|
|
188
|
+
if state.client is not _CANCELLED:
|
|
189
|
+
effective_code = _abortion_code(state, code)
|
|
190
|
+
effective_details = details if state.details is None else state.details
|
|
191
|
+
if state.initial_metadata_allowed:
|
|
192
|
+
operations = (
|
|
193
|
+
_get_initial_metadata_operation(state, None),
|
|
194
|
+
cygrpc.SendStatusFromServerOperation(state.trailing_metadata,
|
|
195
|
+
effective_code,
|
|
196
|
+
effective_details,
|
|
197
|
+
_EMPTY_FLAGS),
|
|
198
|
+
)
|
|
199
|
+
token = _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN
|
|
200
|
+
else:
|
|
201
|
+
operations = (cygrpc.SendStatusFromServerOperation(
|
|
202
|
+
state.trailing_metadata, effective_code, effective_details,
|
|
203
|
+
_EMPTY_FLAGS),)
|
|
204
|
+
token = _SEND_STATUS_FROM_SERVER_TOKEN
|
|
205
|
+
call.start_server_batch(operations,
|
|
206
|
+
_send_status_from_server(state, token))
|
|
207
|
+
state.statused = True
|
|
208
|
+
state.due.add(token)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _receive_close_on_server(state: _RPCState) -> ServerCallbackTag:
|
|
212
|
+
|
|
213
|
+
def receive_close_on_server(receive_close_on_server_event):
|
|
214
|
+
with state.condition:
|
|
215
|
+
if receive_close_on_server_event.batch_operations[0].cancelled():
|
|
216
|
+
state.client = _CANCELLED
|
|
217
|
+
elif state.client is _OPEN:
|
|
218
|
+
state.client = _CLOSED
|
|
219
|
+
state.condition.notify_all()
|
|
220
|
+
return _possibly_finish_call(state, _RECEIVE_CLOSE_ON_SERVER_TOKEN)
|
|
221
|
+
|
|
222
|
+
return receive_close_on_server
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _receive_message(
|
|
226
|
+
state: _RPCState, call: cygrpc.Call,
|
|
227
|
+
request_deserializer: Optional[DeserializingFunction]
|
|
228
|
+
) -> ServerCallbackTag:
|
|
229
|
+
|
|
230
|
+
def receive_message(receive_message_event):
|
|
231
|
+
serialized_request = _serialized_request(receive_message_event)
|
|
232
|
+
if serialized_request is None:
|
|
233
|
+
with state.condition:
|
|
234
|
+
if state.client is _OPEN:
|
|
235
|
+
state.client = _CLOSED
|
|
236
|
+
state.condition.notify_all()
|
|
237
|
+
return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
|
|
238
|
+
else:
|
|
239
|
+
request = _common.deserialize(serialized_request,
|
|
240
|
+
request_deserializer)
|
|
241
|
+
with state.condition:
|
|
242
|
+
if request is None:
|
|
243
|
+
_abort(state, call, cygrpc.StatusCode.internal,
|
|
244
|
+
b'Exception deserializing request!')
|
|
245
|
+
else:
|
|
246
|
+
state.request = request
|
|
247
|
+
state.condition.notify_all()
|
|
248
|
+
return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
|
|
249
|
+
|
|
250
|
+
return receive_message
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _send_initial_metadata(state: _RPCState) -> ServerCallbackTag:
|
|
254
|
+
|
|
255
|
+
def send_initial_metadata(unused_send_initial_metadata_event):
|
|
256
|
+
with state.condition:
|
|
257
|
+
return _possibly_finish_call(state, _SEND_INITIAL_METADATA_TOKEN)
|
|
258
|
+
|
|
259
|
+
return send_initial_metadata
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _send_message(state: _RPCState, token: str) -> ServerCallbackTag:
|
|
263
|
+
|
|
264
|
+
def send_message(unused_send_message_event):
|
|
265
|
+
with state.condition:
|
|
266
|
+
state.condition.notify_all()
|
|
267
|
+
return _possibly_finish_call(state, token)
|
|
268
|
+
|
|
269
|
+
return send_message
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class _Context(grpc.ServicerContext):
|
|
273
|
+
_rpc_event: cygrpc.BaseEvent
|
|
274
|
+
_state: _RPCState
|
|
275
|
+
request_deserializer: Optional[DeserializingFunction]
|
|
276
|
+
|
|
277
|
+
def __init__(self, rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
278
|
+
request_deserializer: Optional[DeserializingFunction]):
|
|
279
|
+
self._rpc_event = rpc_event
|
|
280
|
+
self._state = state
|
|
281
|
+
self._request_deserializer = request_deserializer
|
|
282
|
+
|
|
283
|
+
def is_active(self) -> bool:
|
|
284
|
+
with self._state.condition:
|
|
285
|
+
return _is_rpc_state_active(self._state)
|
|
286
|
+
|
|
287
|
+
def time_remaining(self) -> float:
|
|
288
|
+
return max(self._rpc_event.call_details.deadline - time.time(), 0)
|
|
289
|
+
|
|
290
|
+
def cancel(self) -> None:
|
|
291
|
+
self._rpc_event.call.cancel()
|
|
292
|
+
|
|
293
|
+
def add_callback(self, callback: NullaryCallbackType) -> bool:
|
|
294
|
+
with self._state.condition:
|
|
295
|
+
if self._state.callbacks is None:
|
|
296
|
+
return False
|
|
297
|
+
else:
|
|
298
|
+
self._state.callbacks.append(callback)
|
|
299
|
+
return True
|
|
300
|
+
|
|
301
|
+
def disable_next_message_compression(self) -> None:
|
|
302
|
+
with self._state.condition:
|
|
303
|
+
self._state.disable_next_compression = True
|
|
304
|
+
|
|
305
|
+
def invocation_metadata(self) -> Optional[MetadataType]:
|
|
306
|
+
return self._rpc_event.invocation_metadata
|
|
307
|
+
|
|
308
|
+
def peer(self) -> str:
|
|
309
|
+
return _common.decode(self._rpc_event.call.peer())
|
|
310
|
+
|
|
311
|
+
def peer_identities(self) -> Optional[Sequence[bytes]]:
|
|
312
|
+
return cygrpc.peer_identities(self._rpc_event.call)
|
|
313
|
+
|
|
314
|
+
def peer_identity_key(self) -> Optional[str]:
|
|
315
|
+
id_key = cygrpc.peer_identity_key(self._rpc_event.call)
|
|
316
|
+
return id_key if id_key is None else _common.decode(id_key)
|
|
317
|
+
|
|
318
|
+
def auth_context(self) -> Mapping[str, Sequence[bytes]]:
|
|
319
|
+
auth_context = cygrpc.auth_context(self._rpc_event.call)
|
|
320
|
+
auth_context_dict = {} if auth_context is None else auth_context
|
|
321
|
+
return {
|
|
322
|
+
_common.decode(key): value
|
|
323
|
+
for key, value in auth_context_dict.items()
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
def set_compression(self, compression: grpc.Compression) -> None:
|
|
327
|
+
with self._state.condition:
|
|
328
|
+
self._state.compression_algorithm = compression
|
|
329
|
+
|
|
330
|
+
def send_initial_metadata(self, initial_metadata: MetadataType) -> None:
|
|
331
|
+
with self._state.condition:
|
|
332
|
+
if self._state.client is _CANCELLED:
|
|
333
|
+
_raise_rpc_error(self._state)
|
|
334
|
+
else:
|
|
335
|
+
if self._state.initial_metadata_allowed:
|
|
336
|
+
operation = _get_initial_metadata_operation(
|
|
337
|
+
self._state, initial_metadata)
|
|
338
|
+
self._rpc_event.call.start_server_batch(
|
|
339
|
+
(operation,), _send_initial_metadata(self._state))
|
|
340
|
+
self._state.initial_metadata_allowed = False
|
|
341
|
+
self._state.due.add(_SEND_INITIAL_METADATA_TOKEN)
|
|
342
|
+
else:
|
|
343
|
+
raise ValueError('Initial metadata no longer allowed!')
|
|
344
|
+
|
|
345
|
+
def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None:
|
|
346
|
+
with self._state.condition:
|
|
347
|
+
self._state.trailing_metadata = trailing_metadata
|
|
348
|
+
|
|
349
|
+
def trailing_metadata(self) -> Optional[MetadataType]:
|
|
350
|
+
return self._state.trailing_metadata
|
|
351
|
+
|
|
352
|
+
def abort(self, code: grpc.StatusCode, details: str) -> None:
|
|
353
|
+
# treat OK like other invalid arguments: fail the RPC
|
|
354
|
+
if code == grpc.StatusCode.OK:
|
|
355
|
+
_LOGGER.error(
|
|
356
|
+
'abort() called with StatusCode.OK; returning UNKNOWN')
|
|
357
|
+
code = grpc.StatusCode.UNKNOWN
|
|
358
|
+
details = ''
|
|
359
|
+
with self._state.condition:
|
|
360
|
+
self._state.code = code
|
|
361
|
+
self._state.details = _common.encode(details)
|
|
362
|
+
self._state.aborted = True
|
|
363
|
+
raise Exception()
|
|
364
|
+
|
|
365
|
+
def abort_with_status(self, status: grpc.Status) -> None:
|
|
366
|
+
self._state.trailing_metadata = status.trailing_metadata
|
|
367
|
+
self.abort(status.code, status.details)
|
|
368
|
+
|
|
369
|
+
def set_code(self, code: grpc.StatusCode) -> None:
|
|
370
|
+
with self._state.condition:
|
|
371
|
+
self._state.code = code
|
|
372
|
+
|
|
373
|
+
def code(self) -> grpc.StatusCode:
|
|
374
|
+
return self._state.code
|
|
375
|
+
|
|
376
|
+
def set_details(self, details: str) -> None:
|
|
377
|
+
with self._state.condition:
|
|
378
|
+
self._state.details = _common.encode(details)
|
|
379
|
+
|
|
380
|
+
def details(self) -> bytes:
|
|
381
|
+
return self._state.details
|
|
382
|
+
|
|
383
|
+
def _finalize_state(self) -> None:
|
|
384
|
+
pass
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class _RequestIterator(object):
|
|
388
|
+
_state: _RPCState
|
|
389
|
+
_call: cygrpc.Call
|
|
390
|
+
_request_deserializer: Optional[DeserializingFunction]
|
|
391
|
+
|
|
392
|
+
def __init__(self, state: _RPCState, call: cygrpc.Call,
|
|
393
|
+
request_deserializer: Optional[DeserializingFunction]):
|
|
394
|
+
self._state = state
|
|
395
|
+
self._call = call
|
|
396
|
+
self._request_deserializer = request_deserializer
|
|
397
|
+
|
|
398
|
+
def _raise_or_start_receive_message(self) -> None:
|
|
399
|
+
if self._state.client is _CANCELLED:
|
|
400
|
+
_raise_rpc_error(self._state)
|
|
401
|
+
elif not _is_rpc_state_active(self._state):
|
|
402
|
+
raise StopIteration()
|
|
403
|
+
else:
|
|
404
|
+
self._call.start_server_batch(
|
|
405
|
+
(cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
|
|
406
|
+
_receive_message(self._state, self._call,
|
|
407
|
+
self._request_deserializer))
|
|
408
|
+
self._state.due.add(_RECEIVE_MESSAGE_TOKEN)
|
|
409
|
+
|
|
410
|
+
def _look_for_request(self) -> Any:
|
|
411
|
+
if self._state.client is _CANCELLED:
|
|
412
|
+
_raise_rpc_error(self._state)
|
|
413
|
+
elif (self._state.request is None and
|
|
414
|
+
_RECEIVE_MESSAGE_TOKEN not in self._state.due):
|
|
415
|
+
raise StopIteration()
|
|
416
|
+
else:
|
|
417
|
+
request = self._state.request
|
|
418
|
+
self._state.request = None
|
|
419
|
+
return request
|
|
420
|
+
|
|
421
|
+
raise AssertionError() # should never run
|
|
422
|
+
|
|
423
|
+
def _next(self) -> Any:
|
|
424
|
+
with self._state.condition:
|
|
425
|
+
self._raise_or_start_receive_message()
|
|
426
|
+
while True:
|
|
427
|
+
self._state.condition.wait()
|
|
428
|
+
request = self._look_for_request()
|
|
429
|
+
if request is not None:
|
|
430
|
+
return request
|
|
431
|
+
|
|
432
|
+
def __iter__(self) -> _RequestIterator:
|
|
433
|
+
return self
|
|
434
|
+
|
|
435
|
+
def __next__(self) -> Any:
|
|
436
|
+
return self._next()
|
|
437
|
+
|
|
438
|
+
def next(self) -> Any:
|
|
439
|
+
return self._next()
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _unary_request(
|
|
443
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
444
|
+
request_deserializer: Optional[DeserializingFunction]
|
|
445
|
+
) -> Callable[[], Any]:
|
|
446
|
+
|
|
447
|
+
def unary_request():
|
|
448
|
+
with state.condition:
|
|
449
|
+
if not _is_rpc_state_active(state):
|
|
450
|
+
return None
|
|
451
|
+
else:
|
|
452
|
+
rpc_event.call.start_server_batch(
|
|
453
|
+
(cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
|
|
454
|
+
_receive_message(state, rpc_event.call,
|
|
455
|
+
request_deserializer))
|
|
456
|
+
state.due.add(_RECEIVE_MESSAGE_TOKEN)
|
|
457
|
+
while True:
|
|
458
|
+
state.condition.wait()
|
|
459
|
+
if state.request is None:
|
|
460
|
+
if state.client is _CLOSED:
|
|
461
|
+
details = '"{}" requires exactly one request message.'.format(
|
|
462
|
+
rpc_event.call_details.method)
|
|
463
|
+
_abort(state, rpc_event.call,
|
|
464
|
+
cygrpc.StatusCode.unimplemented,
|
|
465
|
+
_common.encode(details))
|
|
466
|
+
return None
|
|
467
|
+
elif state.client is _CANCELLED:
|
|
468
|
+
return None
|
|
469
|
+
else:
|
|
470
|
+
request = state.request
|
|
471
|
+
state.request = None
|
|
472
|
+
return request
|
|
473
|
+
|
|
474
|
+
return unary_request
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _call_behavior(
|
|
478
|
+
rpc_event: cygrpc.BaseEvent,
|
|
479
|
+
state: _RPCState,
|
|
480
|
+
behavior: ArityAgnosticMethodHandler,
|
|
481
|
+
argument: Any,
|
|
482
|
+
request_deserializer: Optional[DeserializingFunction],
|
|
483
|
+
send_response_callback: Optional[Callable[[ResponseType], None]] = None
|
|
484
|
+
) -> Tuple[Union[ResponseType, Iterator[ResponseType]], bool]:
|
|
485
|
+
from grpc import _create_servicer_context # pytype: disable=pyi-error
|
|
486
|
+
with _create_servicer_context(rpc_event, state,
|
|
487
|
+
request_deserializer) as context:
|
|
488
|
+
try:
|
|
489
|
+
response_or_iterator = None
|
|
490
|
+
if send_response_callback is not None:
|
|
491
|
+
response_or_iterator = behavior(argument, context,
|
|
492
|
+
send_response_callback)
|
|
493
|
+
else:
|
|
494
|
+
response_or_iterator = behavior(argument, context)
|
|
495
|
+
return response_or_iterator, True
|
|
496
|
+
except Exception as exception: # pylint: disable=broad-except
|
|
497
|
+
with state.condition:
|
|
498
|
+
if state.aborted:
|
|
499
|
+
_abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
|
|
500
|
+
b'RPC Aborted')
|
|
501
|
+
elif exception not in state.rpc_errors:
|
|
502
|
+
try:
|
|
503
|
+
details = 'Exception calling application: {}'.format(
|
|
504
|
+
exception)
|
|
505
|
+
except Exception: # pylint: disable=broad-except
|
|
506
|
+
details = 'Calling application raised unprintable Exception!'
|
|
507
|
+
traceback.print_exc()
|
|
508
|
+
_LOGGER.exception(details)
|
|
509
|
+
_abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
|
|
510
|
+
_common.encode(details))
|
|
511
|
+
return None, False
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _take_response_from_response_iterator(
|
|
515
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
516
|
+
response_iterator: Iterator[ResponseType]) -> Tuple[ResponseType, bool]:
|
|
517
|
+
try:
|
|
518
|
+
return next(response_iterator), True
|
|
519
|
+
except StopIteration:
|
|
520
|
+
return None, True
|
|
521
|
+
except Exception as exception: # pylint: disable=broad-except
|
|
522
|
+
with state.condition:
|
|
523
|
+
if state.aborted:
|
|
524
|
+
_abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
|
|
525
|
+
b'RPC Aborted')
|
|
526
|
+
elif exception not in state.rpc_errors:
|
|
527
|
+
details = 'Exception iterating responses: {}'.format(exception)
|
|
528
|
+
_LOGGER.exception(details)
|
|
529
|
+
_abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
|
|
530
|
+
_common.encode(details))
|
|
531
|
+
return None, False
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _serialize_response(
|
|
535
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState, response: Any,
|
|
536
|
+
response_serializer: Optional[SerializingFunction]) -> Optional[bytes]:
|
|
537
|
+
serialized_response = _common.serialize(response, response_serializer)
|
|
538
|
+
if serialized_response is None:
|
|
539
|
+
with state.condition:
|
|
540
|
+
_abort(state, rpc_event.call, cygrpc.StatusCode.internal,
|
|
541
|
+
b'Failed to serialize response!')
|
|
542
|
+
return None
|
|
543
|
+
else:
|
|
544
|
+
return serialized_response
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _get_send_message_op_flags_from_state(
|
|
548
|
+
state: _RPCState) -> Union[int, cygrpc.WriteFlag]:
|
|
549
|
+
if state.disable_next_compression:
|
|
550
|
+
return cygrpc.WriteFlag.no_compress
|
|
551
|
+
else:
|
|
552
|
+
return _EMPTY_FLAGS
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _reset_per_message_state(state: _RPCState) -> None:
|
|
556
|
+
with state.condition:
|
|
557
|
+
state.disable_next_compression = False
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _send_response(rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
561
|
+
serialized_response: bytes) -> bool:
|
|
562
|
+
with state.condition:
|
|
563
|
+
if not _is_rpc_state_active(state):
|
|
564
|
+
return False
|
|
565
|
+
else:
|
|
566
|
+
if state.initial_metadata_allowed:
|
|
567
|
+
operations = (
|
|
568
|
+
_get_initial_metadata_operation(state, None),
|
|
569
|
+
cygrpc.SendMessageOperation(
|
|
570
|
+
serialized_response,
|
|
571
|
+
_get_send_message_op_flags_from_state(state)),
|
|
572
|
+
)
|
|
573
|
+
state.initial_metadata_allowed = False
|
|
574
|
+
token = _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN
|
|
575
|
+
else:
|
|
576
|
+
operations = (cygrpc.SendMessageOperation(
|
|
577
|
+
serialized_response,
|
|
578
|
+
_get_send_message_op_flags_from_state(state)),)
|
|
579
|
+
token = _SEND_MESSAGE_TOKEN
|
|
580
|
+
rpc_event.call.start_server_batch(operations,
|
|
581
|
+
_send_message(state, token))
|
|
582
|
+
state.due.add(token)
|
|
583
|
+
_reset_per_message_state(state)
|
|
584
|
+
while True:
|
|
585
|
+
state.condition.wait()
|
|
586
|
+
if token not in state.due:
|
|
587
|
+
return _is_rpc_state_active(state)
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _status(rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
591
|
+
serialized_response: Optional[bytes]) -> None:
|
|
592
|
+
with state.condition:
|
|
593
|
+
if state.client is not _CANCELLED:
|
|
594
|
+
code = _completion_code(state)
|
|
595
|
+
details = _details(state)
|
|
596
|
+
operations = [
|
|
597
|
+
cygrpc.SendStatusFromServerOperation(state.trailing_metadata,
|
|
598
|
+
code, details,
|
|
599
|
+
_EMPTY_FLAGS),
|
|
600
|
+
]
|
|
601
|
+
if state.initial_metadata_allowed:
|
|
602
|
+
operations.append(_get_initial_metadata_operation(state, None))
|
|
603
|
+
if serialized_response is not None:
|
|
604
|
+
operations.append(
|
|
605
|
+
cygrpc.SendMessageOperation(
|
|
606
|
+
serialized_response,
|
|
607
|
+
_get_send_message_op_flags_from_state(state)))
|
|
608
|
+
rpc_event.call.start_server_batch(
|
|
609
|
+
operations,
|
|
610
|
+
_send_status_from_server(state, _SEND_STATUS_FROM_SERVER_TOKEN))
|
|
611
|
+
state.statused = True
|
|
612
|
+
_reset_per_message_state(state)
|
|
613
|
+
state.due.add(_SEND_STATUS_FROM_SERVER_TOKEN)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _unary_response_in_pool(
|
|
617
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
618
|
+
behavior: ArityAgnosticMethodHandler, argument_thunk: Callable[[], Any],
|
|
619
|
+
request_deserializer: Optional[SerializingFunction],
|
|
620
|
+
response_serializer: Optional[SerializingFunction]) -> None:
|
|
621
|
+
cygrpc.install_context_from_request_call_event(rpc_event)
|
|
622
|
+
try:
|
|
623
|
+
argument = argument_thunk()
|
|
624
|
+
if argument is not None:
|
|
625
|
+
response, proceed = _call_behavior(rpc_event, state, behavior,
|
|
626
|
+
argument, request_deserializer)
|
|
627
|
+
if proceed:
|
|
628
|
+
serialized_response = _serialize_response(
|
|
629
|
+
rpc_event, state, response, response_serializer)
|
|
630
|
+
if serialized_response is not None:
|
|
631
|
+
_status(rpc_event, state, serialized_response)
|
|
632
|
+
except Exception: # pylint: disable=broad-except
|
|
633
|
+
traceback.print_exc()
|
|
634
|
+
finally:
|
|
635
|
+
cygrpc.uninstall_context()
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _stream_response_in_pool(
|
|
639
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
640
|
+
behavior: ArityAgnosticMethodHandler, argument_thunk: Callable[[], Any],
|
|
641
|
+
request_deserializer: Optional[DeserializingFunction],
|
|
642
|
+
response_serializer: Optional[SerializingFunction]) -> None:
|
|
643
|
+
cygrpc.install_context_from_request_call_event(rpc_event)
|
|
644
|
+
|
|
645
|
+
def send_response(response: Any) -> None:
|
|
646
|
+
if response is None:
|
|
647
|
+
_status(rpc_event, state, None)
|
|
648
|
+
else:
|
|
649
|
+
serialized_response = _serialize_response(rpc_event, state,
|
|
650
|
+
response,
|
|
651
|
+
response_serializer)
|
|
652
|
+
if serialized_response is not None:
|
|
653
|
+
_send_response(rpc_event, state, serialized_response)
|
|
654
|
+
|
|
655
|
+
try:
|
|
656
|
+
argument = argument_thunk()
|
|
657
|
+
if argument is not None:
|
|
658
|
+
if hasattr(behavior, 'experimental_non_blocking'
|
|
659
|
+
) and behavior.experimental_non_blocking:
|
|
660
|
+
_call_behavior(rpc_event,
|
|
661
|
+
state,
|
|
662
|
+
behavior,
|
|
663
|
+
argument,
|
|
664
|
+
request_deserializer,
|
|
665
|
+
send_response_callback=send_response)
|
|
666
|
+
else:
|
|
667
|
+
response_iterator, proceed = _call_behavior(
|
|
668
|
+
rpc_event, state, behavior, argument, request_deserializer)
|
|
669
|
+
if proceed:
|
|
670
|
+
_send_message_callback_to_blocking_iterator_adapter(
|
|
671
|
+
rpc_event, state, send_response, response_iterator)
|
|
672
|
+
except Exception: # pylint: disable=broad-except
|
|
673
|
+
traceback.print_exc()
|
|
674
|
+
finally:
|
|
675
|
+
cygrpc.uninstall_context()
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _is_rpc_state_active(state: _RPCState) -> bool:
|
|
679
|
+
return state.client is not _CANCELLED and not state.statused
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def _send_message_callback_to_blocking_iterator_adapter(
|
|
683
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
684
|
+
send_response_callback: Callable[[ResponseType], None],
|
|
685
|
+
response_iterator: Iterator[ResponseType]) -> None:
|
|
686
|
+
while True:
|
|
687
|
+
response, proceed = _take_response_from_response_iterator(
|
|
688
|
+
rpc_event, state, response_iterator)
|
|
689
|
+
if proceed:
|
|
690
|
+
send_response_callback(response)
|
|
691
|
+
if not _is_rpc_state_active(state):
|
|
692
|
+
break
|
|
693
|
+
else:
|
|
694
|
+
break
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _select_thread_pool_for_behavior(
|
|
698
|
+
behavior: ArityAgnosticMethodHandler,
|
|
699
|
+
default_thread_pool: futures.ThreadPoolExecutor
|
|
700
|
+
) -> futures.ThreadPoolExecutor:
|
|
701
|
+
if hasattr(behavior, 'experimental_thread_pool') and isinstance(
|
|
702
|
+
behavior.experimental_thread_pool, futures.ThreadPoolExecutor):
|
|
703
|
+
return behavior.experimental_thread_pool
|
|
704
|
+
else:
|
|
705
|
+
return default_thread_pool
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _handle_unary_unary(
|
|
709
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
710
|
+
method_handler: grpc.RpcMethodHandler,
|
|
711
|
+
default_thread_pool: futures.ThreadPoolExecutor) -> futures.Future:
|
|
712
|
+
unary_request = _unary_request(rpc_event, state,
|
|
713
|
+
method_handler.request_deserializer)
|
|
714
|
+
thread_pool = _select_thread_pool_for_behavior(method_handler.unary_unary,
|
|
715
|
+
default_thread_pool)
|
|
716
|
+
return thread_pool.submit(_unary_response_in_pool, rpc_event, state,
|
|
717
|
+
method_handler.unary_unary, unary_request,
|
|
718
|
+
method_handler.request_deserializer,
|
|
719
|
+
method_handler.response_serializer)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _handle_unary_stream(
|
|
723
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
724
|
+
method_handler: grpc.RpcMethodHandler,
|
|
725
|
+
default_thread_pool: futures.ThreadPoolExecutor) -> futures.Future:
|
|
726
|
+
unary_request = _unary_request(rpc_event, state,
|
|
727
|
+
method_handler.request_deserializer)
|
|
728
|
+
thread_pool = _select_thread_pool_for_behavior(method_handler.unary_stream,
|
|
729
|
+
default_thread_pool)
|
|
730
|
+
return thread_pool.submit(_stream_response_in_pool, rpc_event, state,
|
|
731
|
+
method_handler.unary_stream, unary_request,
|
|
732
|
+
method_handler.request_deserializer,
|
|
733
|
+
method_handler.response_serializer)
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _handle_stream_unary(
|
|
737
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
738
|
+
method_handler: grpc.RpcMethodHandler,
|
|
739
|
+
default_thread_pool: futures.ThreadPoolExecutor) -> futures.Future:
|
|
740
|
+
request_iterator = _RequestIterator(state, rpc_event.call,
|
|
741
|
+
method_handler.request_deserializer)
|
|
742
|
+
thread_pool = _select_thread_pool_for_behavior(method_handler.stream_unary,
|
|
743
|
+
default_thread_pool)
|
|
744
|
+
return thread_pool.submit(_unary_response_in_pool, rpc_event, state,
|
|
745
|
+
method_handler.stream_unary,
|
|
746
|
+
lambda: request_iterator,
|
|
747
|
+
method_handler.request_deserializer,
|
|
748
|
+
method_handler.response_serializer)
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def _handle_stream_stream(
|
|
752
|
+
rpc_event: cygrpc.BaseEvent, state: _RPCState,
|
|
753
|
+
method_handler: grpc.RpcMethodHandler,
|
|
754
|
+
default_thread_pool: futures.ThreadPoolExecutor) -> futures.Future:
|
|
755
|
+
request_iterator = _RequestIterator(state, rpc_event.call,
|
|
756
|
+
method_handler.request_deserializer)
|
|
757
|
+
thread_pool = _select_thread_pool_for_behavior(method_handler.stream_stream,
|
|
758
|
+
default_thread_pool)
|
|
759
|
+
return thread_pool.submit(_stream_response_in_pool, rpc_event, state,
|
|
760
|
+
method_handler.stream_stream,
|
|
761
|
+
lambda: request_iterator,
|
|
762
|
+
method_handler.request_deserializer,
|
|
763
|
+
method_handler.response_serializer)
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def _find_method_handler(
|
|
767
|
+
rpc_event: cygrpc.BaseEvent, generic_handlers: List[grpc.GenericRpcHandler],
|
|
768
|
+
interceptor_pipeline: Optional[_interceptor._ServicePipeline]
|
|
769
|
+
) -> Optional[grpc.RpcMethodHandler]:
|
|
770
|
+
|
|
771
|
+
def query_handlers(
|
|
772
|
+
handler_call_details: _HandlerCallDetails
|
|
773
|
+
) -> Optional[grpc.RpcMethodHandler]:
|
|
774
|
+
for generic_handler in generic_handlers:
|
|
775
|
+
method_handler = generic_handler.service(handler_call_details)
|
|
776
|
+
if method_handler is not None:
|
|
777
|
+
return method_handler
|
|
778
|
+
return None
|
|
779
|
+
|
|
780
|
+
handler_call_details = _HandlerCallDetails(
|
|
781
|
+
_common.decode(rpc_event.call_details.method),
|
|
782
|
+
rpc_event.invocation_metadata)
|
|
783
|
+
|
|
784
|
+
if interceptor_pipeline is not None:
|
|
785
|
+
return interceptor_pipeline.execute(query_handlers,
|
|
786
|
+
handler_call_details)
|
|
787
|
+
else:
|
|
788
|
+
return query_handlers(handler_call_details)
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def _reject_rpc(rpc_event: cygrpc.BaseEvent, status: cygrpc.StatusCode,
|
|
792
|
+
details: bytes) -> _RPCState:
|
|
793
|
+
rpc_state = _RPCState()
|
|
794
|
+
operations = (
|
|
795
|
+
_get_initial_metadata_operation(rpc_state, None),
|
|
796
|
+
cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
|
|
797
|
+
cygrpc.SendStatusFromServerOperation(None, status, details,
|
|
798
|
+
_EMPTY_FLAGS),
|
|
799
|
+
)
|
|
800
|
+
rpc_event.call.start_server_batch(operations, lambda ignored_event: (
|
|
801
|
+
rpc_state,
|
|
802
|
+
(),
|
|
803
|
+
))
|
|
804
|
+
return rpc_state
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def _handle_with_method_handler(
|
|
808
|
+
rpc_event: cygrpc.BaseEvent, method_handler: grpc.RpcMethodHandler,
|
|
809
|
+
thread_pool: futures.ThreadPoolExecutor
|
|
810
|
+
) -> Tuple[_RPCState, futures.Future]:
|
|
811
|
+
state = _RPCState()
|
|
812
|
+
with state.condition:
|
|
813
|
+
rpc_event.call.start_server_batch(
|
|
814
|
+
(cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
|
|
815
|
+
_receive_close_on_server(state))
|
|
816
|
+
state.due.add(_RECEIVE_CLOSE_ON_SERVER_TOKEN)
|
|
817
|
+
if method_handler.request_streaming:
|
|
818
|
+
if method_handler.response_streaming:
|
|
819
|
+
return state, _handle_stream_stream(rpc_event, state,
|
|
820
|
+
method_handler, thread_pool)
|
|
821
|
+
else:
|
|
822
|
+
return state, _handle_stream_unary(rpc_event, state,
|
|
823
|
+
method_handler, thread_pool)
|
|
824
|
+
else:
|
|
825
|
+
if method_handler.response_streaming:
|
|
826
|
+
return state, _handle_unary_stream(rpc_event, state,
|
|
827
|
+
method_handler, thread_pool)
|
|
828
|
+
else:
|
|
829
|
+
return state, _handle_unary_unary(rpc_event, state,
|
|
830
|
+
method_handler, thread_pool)
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def _handle_call(
|
|
834
|
+
rpc_event: cygrpc.BaseEvent, generic_handlers: List[grpc.GenericRpcHandler],
|
|
835
|
+
interceptor_pipeline: Optional[_interceptor._ServicePipeline],
|
|
836
|
+
thread_pool: futures.ThreadPoolExecutor, concurrency_exceeded: bool
|
|
837
|
+
) -> Tuple[Optional[_RPCState], Optional[futures.Future]]:
|
|
838
|
+
if not rpc_event.success:
|
|
839
|
+
return None, None
|
|
840
|
+
if rpc_event.call_details.method is not None:
|
|
841
|
+
try:
|
|
842
|
+
method_handler = _find_method_handler(rpc_event, generic_handlers,
|
|
843
|
+
interceptor_pipeline)
|
|
844
|
+
except Exception as exception: # pylint: disable=broad-except
|
|
845
|
+
details = 'Exception servicing handler: {}'.format(exception)
|
|
846
|
+
_LOGGER.exception(details)
|
|
847
|
+
return _reject_rpc(rpc_event, cygrpc.StatusCode.unknown,
|
|
848
|
+
b'Error in service handler!'), None
|
|
849
|
+
if method_handler is None:
|
|
850
|
+
return _reject_rpc(rpc_event, cygrpc.StatusCode.unimplemented,
|
|
851
|
+
b'Method not found!'), None
|
|
852
|
+
elif concurrency_exceeded:
|
|
853
|
+
return _reject_rpc(rpc_event, cygrpc.StatusCode.resource_exhausted,
|
|
854
|
+
b'Concurrent RPC limit exceeded!'), None
|
|
855
|
+
else:
|
|
856
|
+
return _handle_with_method_handler(rpc_event, method_handler,
|
|
857
|
+
thread_pool)
|
|
858
|
+
else:
|
|
859
|
+
return None, None
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
@enum.unique
|
|
863
|
+
class _ServerStage(enum.Enum):
|
|
864
|
+
STOPPED = 'stopped'
|
|
865
|
+
STARTED = 'started'
|
|
866
|
+
GRACE = 'grace'
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
class _ServerState(object):
|
|
870
|
+
lock: threading.RLock
|
|
871
|
+
completion_queue: cygrpc.CompletionQueue
|
|
872
|
+
server: cygrpc.Server
|
|
873
|
+
generic_handlers: List[grpc.GenericRpcHandler]
|
|
874
|
+
interceptor_pipeline: Optional[_interceptor._ServicePipeline]
|
|
875
|
+
thread_pool: futures.ThreadPoolExecutor
|
|
876
|
+
stage: _ServerStage
|
|
877
|
+
termination_event: threading.Event
|
|
878
|
+
shutdown_events: List[threading.Event]
|
|
879
|
+
maximum_concurrent_rpcs: Optional[int]
|
|
880
|
+
active_rpc_count: int
|
|
881
|
+
rpc_states: Set[_RPCState]
|
|
882
|
+
due: Set[str]
|
|
883
|
+
server_deallocated: bool
|
|
884
|
+
|
|
885
|
+
# pylint: disable=too-many-arguments
|
|
886
|
+
def __init__(self, completion_queue: cygrpc.CompletionQueue,
|
|
887
|
+
server: cygrpc.Server,
|
|
888
|
+
generic_handlers: Sequence[grpc.GenericRpcHandler],
|
|
889
|
+
interceptor_pipeline: Optional[_interceptor._ServicePipeline],
|
|
890
|
+
thread_pool: futures.ThreadPoolExecutor,
|
|
891
|
+
maximum_concurrent_rpcs: Optional[int]):
|
|
892
|
+
self.lock = threading.RLock()
|
|
893
|
+
self.completion_queue = completion_queue
|
|
894
|
+
self.server = server
|
|
895
|
+
self.generic_handlers = list(generic_handlers)
|
|
896
|
+
self.interceptor_pipeline = interceptor_pipeline
|
|
897
|
+
self.thread_pool = thread_pool
|
|
898
|
+
self.stage = _ServerStage.STOPPED
|
|
899
|
+
self.termination_event = threading.Event()
|
|
900
|
+
self.shutdown_events = [self.termination_event]
|
|
901
|
+
self.maximum_concurrent_rpcs = maximum_concurrent_rpcs
|
|
902
|
+
self.active_rpc_count = 0
|
|
903
|
+
|
|
904
|
+
# TODO(https://github.com/grpc/grpc/issues/6597): eliminate these fields.
|
|
905
|
+
self.rpc_states = set()
|
|
906
|
+
self.due = set()
|
|
907
|
+
|
|
908
|
+
# A "volatile" flag to interrupt the daemon serving thread
|
|
909
|
+
self.server_deallocated = False
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def _add_generic_handlers(
|
|
913
|
+
state: _ServerState,
|
|
914
|
+
generic_handlers: Iterable[grpc.GenericRpcHandler]) -> None:
|
|
915
|
+
with state.lock:
|
|
916
|
+
state.generic_handlers.extend(generic_handlers)
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def _add_insecure_port(state: _ServerState, address: bytes) -> int:
|
|
920
|
+
with state.lock:
|
|
921
|
+
return state.server.add_http2_port(address)
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def _add_secure_port(state: _ServerState, address: bytes,
|
|
925
|
+
server_credentials: grpc.ServerCredentials) -> int:
|
|
926
|
+
with state.lock:
|
|
927
|
+
return state.server.add_http2_port(address,
|
|
928
|
+
server_credentials._credentials)
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def _request_call(state: _ServerState) -> None:
|
|
932
|
+
state.server.request_call(state.completion_queue, state.completion_queue,
|
|
933
|
+
_REQUEST_CALL_TAG)
|
|
934
|
+
state.due.add(_REQUEST_CALL_TAG)
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
# TODO(https://github.com/grpc/grpc/issues/6597): delete this function.
|
|
938
|
+
def _stop_serving(state: _ServerState) -> bool:
|
|
939
|
+
if not state.rpc_states and not state.due:
|
|
940
|
+
state.server.destroy()
|
|
941
|
+
for shutdown_event in state.shutdown_events:
|
|
942
|
+
shutdown_event.set()
|
|
943
|
+
state.stage = _ServerStage.STOPPED
|
|
944
|
+
return True
|
|
945
|
+
else:
|
|
946
|
+
return False
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
def _on_call_completed(state: _ServerState) -> None:
|
|
950
|
+
with state.lock:
|
|
951
|
+
state.active_rpc_count -= 1
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
def _process_event_and_continue(state: _ServerState,
|
|
955
|
+
event: cygrpc.BaseEvent) -> bool:
|
|
956
|
+
should_continue = True
|
|
957
|
+
if event.tag is _SHUTDOWN_TAG:
|
|
958
|
+
with state.lock:
|
|
959
|
+
state.due.remove(_SHUTDOWN_TAG)
|
|
960
|
+
if _stop_serving(state):
|
|
961
|
+
should_continue = False
|
|
962
|
+
elif event.tag is _REQUEST_CALL_TAG:
|
|
963
|
+
with state.lock:
|
|
964
|
+
state.due.remove(_REQUEST_CALL_TAG)
|
|
965
|
+
concurrency_exceeded = (
|
|
966
|
+
state.maximum_concurrent_rpcs is not None and
|
|
967
|
+
state.active_rpc_count >= state.maximum_concurrent_rpcs)
|
|
968
|
+
rpc_state, rpc_future = _handle_call(event, state.generic_handlers,
|
|
969
|
+
state.interceptor_pipeline,
|
|
970
|
+
state.thread_pool,
|
|
971
|
+
concurrency_exceeded)
|
|
972
|
+
if rpc_state is not None:
|
|
973
|
+
state.rpc_states.add(rpc_state)
|
|
974
|
+
if rpc_future is not None:
|
|
975
|
+
state.active_rpc_count += 1
|
|
976
|
+
rpc_future.add_done_callback(
|
|
977
|
+
lambda unused_future: _on_call_completed(state))
|
|
978
|
+
if state.stage is _ServerStage.STARTED:
|
|
979
|
+
_request_call(state)
|
|
980
|
+
elif _stop_serving(state):
|
|
981
|
+
should_continue = False
|
|
982
|
+
else:
|
|
983
|
+
rpc_state, callbacks = event.tag(event)
|
|
984
|
+
for callback in callbacks:
|
|
985
|
+
try:
|
|
986
|
+
callback()
|
|
987
|
+
except Exception: # pylint: disable=broad-except
|
|
988
|
+
_LOGGER.exception('Exception calling callback!')
|
|
989
|
+
if rpc_state is not None:
|
|
990
|
+
with state.lock:
|
|
991
|
+
state.rpc_states.remove(rpc_state)
|
|
992
|
+
if _stop_serving(state):
|
|
993
|
+
should_continue = False
|
|
994
|
+
return should_continue
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
def _serve(state: _ServerState) -> None:
|
|
998
|
+
while True:
|
|
999
|
+
timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S
|
|
1000
|
+
event = state.completion_queue.poll(timeout)
|
|
1001
|
+
if state.server_deallocated:
|
|
1002
|
+
_begin_shutdown_once(state)
|
|
1003
|
+
if event.completion_type != cygrpc.CompletionType.queue_timeout:
|
|
1004
|
+
if not _process_event_and_continue(state, event):
|
|
1005
|
+
return
|
|
1006
|
+
# We want to force the deletion of the previous event
|
|
1007
|
+
# ~before~ we poll again; if the event has a reference
|
|
1008
|
+
# to a shutdown Call object, this can induce spinlock.
|
|
1009
|
+
event = None
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def _begin_shutdown_once(state: _ServerState) -> None:
|
|
1013
|
+
with state.lock:
|
|
1014
|
+
if state.stage is _ServerStage.STARTED:
|
|
1015
|
+
state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG)
|
|
1016
|
+
state.stage = _ServerStage.GRACE
|
|
1017
|
+
state.due.add(_SHUTDOWN_TAG)
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
def _stop(state: _ServerState, grace: Optional[float]) -> threading.Event:
|
|
1021
|
+
with state.lock:
|
|
1022
|
+
if state.stage is _ServerStage.STOPPED:
|
|
1023
|
+
shutdown_event = threading.Event()
|
|
1024
|
+
shutdown_event.set()
|
|
1025
|
+
return shutdown_event
|
|
1026
|
+
else:
|
|
1027
|
+
_begin_shutdown_once(state)
|
|
1028
|
+
shutdown_event = threading.Event()
|
|
1029
|
+
state.shutdown_events.append(shutdown_event)
|
|
1030
|
+
if grace is None:
|
|
1031
|
+
state.server.cancel_all_calls()
|
|
1032
|
+
else:
|
|
1033
|
+
|
|
1034
|
+
def cancel_all_calls_after_grace():
|
|
1035
|
+
shutdown_event.wait(timeout=grace)
|
|
1036
|
+
with state.lock:
|
|
1037
|
+
state.server.cancel_all_calls()
|
|
1038
|
+
|
|
1039
|
+
thread = threading.Thread(target=cancel_all_calls_after_grace)
|
|
1040
|
+
thread.start()
|
|
1041
|
+
return shutdown_event
|
|
1042
|
+
shutdown_event.wait()
|
|
1043
|
+
return shutdown_event
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
def _start(state: _ServerState) -> None:
|
|
1047
|
+
with state.lock:
|
|
1048
|
+
if state.stage is not _ServerStage.STOPPED:
|
|
1049
|
+
raise ValueError('Cannot start already-started server!')
|
|
1050
|
+
state.server.start()
|
|
1051
|
+
state.stage = _ServerStage.STARTED
|
|
1052
|
+
_request_call(state)
|
|
1053
|
+
|
|
1054
|
+
thread = threading.Thread(target=_serve, args=(state,))
|
|
1055
|
+
thread.daemon = True
|
|
1056
|
+
thread.start()
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def _validate_generic_rpc_handlers(
|
|
1060
|
+
generic_rpc_handlers: Iterable[grpc.GenericRpcHandler]) -> None:
|
|
1061
|
+
for generic_rpc_handler in generic_rpc_handlers:
|
|
1062
|
+
service_attribute = getattr(generic_rpc_handler, 'service', None)
|
|
1063
|
+
if service_attribute is None:
|
|
1064
|
+
raise AttributeError(
|
|
1065
|
+
'"{}" must conform to grpc.GenericRpcHandler type but does '
|
|
1066
|
+
'not have "service" method!'.format(generic_rpc_handler))
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
def _augment_options(
|
|
1070
|
+
base_options: Sequence[ChannelArgumentType],
|
|
1071
|
+
compression: Optional[grpc.Compression]
|
|
1072
|
+
) -> Sequence[ChannelArgumentType]:
|
|
1073
|
+
compression_option = _compression.create_channel_option(compression)
|
|
1074
|
+
return tuple(base_options) + compression_option
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
class _Server(grpc.Server):
|
|
1078
|
+
_state: _ServerState
|
|
1079
|
+
|
|
1080
|
+
# pylint: disable=too-many-arguments
|
|
1081
|
+
def __init__(self, thread_pool: futures.ThreadPoolExecutor,
|
|
1082
|
+
generic_handlers: Sequence[grpc.GenericRpcHandler],
|
|
1083
|
+
interceptors: Sequence[grpc.ServerInterceptor],
|
|
1084
|
+
options: Sequence[ChannelArgumentType],
|
|
1085
|
+
maximum_concurrent_rpcs: Optional[int],
|
|
1086
|
+
compression: Optional[grpc.Compression], xds: bool):
|
|
1087
|
+
completion_queue = cygrpc.CompletionQueue()
|
|
1088
|
+
server = cygrpc.Server(_augment_options(options, compression), xds)
|
|
1089
|
+
server.register_completion_queue(completion_queue)
|
|
1090
|
+
self._state = _ServerState(completion_queue, server, generic_handlers,
|
|
1091
|
+
_interceptor.service_pipeline(interceptors),
|
|
1092
|
+
thread_pool, maximum_concurrent_rpcs)
|
|
1093
|
+
|
|
1094
|
+
def add_generic_rpc_handlers(
|
|
1095
|
+
self,
|
|
1096
|
+
generic_rpc_handlers: Iterable[grpc.GenericRpcHandler]) -> None:
|
|
1097
|
+
_validate_generic_rpc_handlers(generic_rpc_handlers)
|
|
1098
|
+
_add_generic_handlers(self._state, generic_rpc_handlers)
|
|
1099
|
+
|
|
1100
|
+
def add_insecure_port(self, address: str) -> int:
|
|
1101
|
+
return _common.validate_port_binding_result(
|
|
1102
|
+
address, _add_insecure_port(self._state, _common.encode(address)))
|
|
1103
|
+
|
|
1104
|
+
def add_secure_port(self, address: str,
|
|
1105
|
+
server_credentials: grpc.ServerCredentials) -> int:
|
|
1106
|
+
return _common.validate_port_binding_result(
|
|
1107
|
+
address,
|
|
1108
|
+
_add_secure_port(self._state, _common.encode(address),
|
|
1109
|
+
server_credentials))
|
|
1110
|
+
|
|
1111
|
+
def start(self) -> None:
|
|
1112
|
+
_start(self._state)
|
|
1113
|
+
|
|
1114
|
+
def wait_for_termination(self, timeout: Optional[float] = None) -> bool:
|
|
1115
|
+
# NOTE(https://bugs.python.org/issue35935)
|
|
1116
|
+
# Remove this workaround once threading.Event.wait() is working with
|
|
1117
|
+
# CTRL+C across platforms.
|
|
1118
|
+
return _common.wait(self._state.termination_event.wait,
|
|
1119
|
+
self._state.termination_event.is_set,
|
|
1120
|
+
timeout=timeout)
|
|
1121
|
+
|
|
1122
|
+
def stop(self, grace: Optional[float]) -> threading.Event:
|
|
1123
|
+
return _stop(self._state, grace)
|
|
1124
|
+
|
|
1125
|
+
def __del__(self):
|
|
1126
|
+
if hasattr(self, '_state'):
|
|
1127
|
+
# We can not grab a lock in __del__(), so set a flag to signal the
|
|
1128
|
+
# serving daemon thread (if it exists) to initiate shutdown.
|
|
1129
|
+
self._state.server_deallocated = True
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def create_server(thread_pool: futures.ThreadPoolExecutor,
|
|
1133
|
+
generic_rpc_handlers: Sequence[grpc.GenericRpcHandler],
|
|
1134
|
+
interceptors: Sequence[grpc.ServerInterceptor],
|
|
1135
|
+
options: Sequence[ChannelArgumentType],
|
|
1136
|
+
maximum_concurrent_rpcs: Optional[int],
|
|
1137
|
+
compression: Optional[grpc.Compression],
|
|
1138
|
+
xds: bool) -> _Server:
|
|
1139
|
+
_validate_generic_rpc_handlers(generic_rpc_handlers)
|
|
1140
|
+
return _Server(thread_pool, generic_rpc_handlers, interceptors, options,
|
|
1141
|
+
maximum_concurrent_rpcs, compression, xds)
|