|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
15 | | -"""Bi-directional streaming RPC helpers.""" |
| 15 | +"""Helpers for synchronous bidirectional streaming RPCs.""" |
16 | 16 |
|
17 | 17 | import collections |
18 | 18 | import datetime |
|
22 | 22 | import time |
23 | 23 |
|
24 | 24 | from google.api_core import exceptions |
| 25 | +from google.api_core.bidi_base import BidiRpcBase |
25 | 26 |
|
26 | 27 | _LOGGER = logging.getLogger(__name__) |
27 | 28 | _BIDIRECTIONAL_CONSUMER_NAME = "Thread-ConsumeBidirectionalStream" |
@@ -36,21 +37,6 @@ class _RequestQueueGenerator(object): |
36 | 37 | otherwise open-ended set of requests to send through a request-streaming |
37 | 38 | (or bidirectional) RPC. |
38 | 39 |
|
39 | | - The reason this is necessary is because gRPC takes an iterator as the |
40 | | - request for request-streaming RPCs. gRPC consumes this iterator in another |
41 | | - thread to allow it to block while generating requests for the stream. |
42 | | - However, if the generator blocks indefinitely gRPC will not be able to |
43 | | - clean up the thread as it'll be blocked on `next(iterator)` and not be able |
44 | | - to check the channel status to stop iterating. This helper mitigates that |
45 | | - by waiting on the queue with a timeout and checking the RPC state before |
46 | | - yielding. |
47 | | -
|
48 | | - Finally, it allows for retrying without swapping queues because if it does |
49 | | - pull an item off the queue when the RPC is inactive, it'll immediately put |
50 | | - it back and then exit. This is necessary because yielding the item in this |
51 | | - case will cause gRPC to discard it. In practice, this means that the order |
52 | | - of messages is not guaranteed. If such a thing is necessary it would be |
53 | | - easy to use a priority queue. |
54 | 40 |
|
55 | 41 | Example:: |
56 | 42 |
|
@@ -62,12 +48,6 @@ class _RequestQueueGenerator(object): |
62 | 48 | print(response) |
63 | 49 | q.put(...) |
64 | 50 |
|
65 | | - Note that it is possible to accomplish this behavior without "spinning" |
66 | | - (using a queue timeout). One possible way would be to use more threads to |
67 | | - multiplex the grpc end event with the queue, another possible way is to |
68 | | - use selectors and a custom event/queue object. Both of these approaches |
69 | | - are significant from an engineering perspective for small benefit - the |
70 | | - CPU consumed by spinning is pretty minuscule. |
71 | 51 |
|
72 | 52 | Args: |
73 | 53 | queue (queue_module.Queue): The request queue. |
@@ -96,6 +76,31 @@ def _is_active(self): |
96 | 76 | return self.call is None or self.call.is_active() |
97 | 77 |
|
98 | 78 | def __iter__(self): |
| 79 | + # The reason this is necessary is because gRPC takes an iterator as the |
| 80 | + # request for request-streaming RPCs. gRPC consumes this iterator in |
| 81 | + # another thread to allow it to block while generating requests for |
| 82 | + # the stream. However, if the generator blocks indefinitely gRPC will |
| 83 | + # not be able to clean up the thread as it'll be blocked on |
| 84 | + # `next(iterator)` and not be able to check the channel status to stop |
| 85 | + # iterating. This helper mitigates that by waiting on the queue with |
| 86 | + # a timeout and checking the RPC state before yielding. |
| 87 | + # |
| 88 | + # Finally, it allows for retrying without swapping queues because if |
| 89 | + # it does pull an item off the queue when the RPC is inactive, it'll |
| 90 | + # immediately put it back and then exit. This is necessary because |
| 91 | + # yielding the item in this case will cause gRPC to discard it. In |
| 92 | + # practice, this means that the order of messages is not guaranteed. |
| 93 | + # If such a thing is necessary it would be easy to use a priority |
| 94 | + # queue. |
| 95 | + # |
| 96 | + # Note that it is possible to accomplish this behavior without |
| 97 | + # "spinning" (using a queue timeout). One possible way would be to use |
| 98 | + # more threads to multiplex the grpc end event with the queue, another |
| 99 | + # possible way is to use selectors and a custom event/queue object. |
| 100 | + # Both of these approaches are significant from an engineering |
| 101 | + # perspective for small benefit - the CPU consumed by spinning is |
| 102 | + # pretty minuscule. |
| 103 | + |
99 | 104 | if self._initial_request is not None: |
100 | 105 | if callable(self._initial_request): |
101 | 106 | yield self._initial_request() |
@@ -201,7 +206,7 @@ def __repr__(self): |
201 | 206 | ) |
202 | 207 |
|
203 | 208 |
|
204 | | -class BidiRpc(object): |
| 209 | +class BidiRpc(BidiRpcBase): |
205 | 210 | """A helper for consuming a bi-directional streaming RPC. |
206 | 211 |
|
207 | 212 | This maps gRPC's built-in interface which uses a request iterator and a |
@@ -227,6 +232,8 @@ class BidiRpc(object): |
227 | 232 | rpc.send(example_pb2.StreamingRpcRequest( |
228 | 233 | data='example')) |
229 | 234 |
|
| 235 | + rpc.close() |
| 236 | +
|
230 | 237 | This does *not* retry the stream on errors. See :class:`ResumableBidiRpc`. |
231 | 238 |
|
232 | 239 | Args: |
@@ -240,40 +247,14 @@ class BidiRpc(object): |
240 | 247 | the request. |
241 | 248 | """ |
242 | 249 |
|
243 | | - def __init__(self, start_rpc, initial_request=None, metadata=None): |
244 | | - self._start_rpc = start_rpc |
245 | | - self._initial_request = initial_request |
246 | | - self._rpc_metadata = metadata |
247 | | - self._request_queue = queue_module.Queue() |
248 | | - self._request_generator = None |
249 | | - self._is_active = False |
250 | | - self._callbacks = [] |
251 | | - self.call = None |
252 | | - |
253 | | - def add_done_callback(self, callback): |
254 | | - """Adds a callback that will be called when the RPC terminates. |
255 | | -
|
256 | | - This occurs when the RPC errors or is successfully terminated. |
257 | | -
|
258 | | - Args: |
259 | | - callback (Callable[[grpc.Future], None]): The callback to execute. |
260 | | - It will be provided with the same gRPC future as the underlying |
261 | | - stream which will also be a :class:`grpc.Call`. |
262 | | - """ |
263 | | - self._callbacks.append(callback) |
264 | | - |
265 | | - def _on_call_done(self, future): |
266 | | - # This occurs when the RPC errors or is successfully terminated. |
267 | | - # Note that grpc's "future" here can also be a grpc.RpcError. |
268 | | - # See note in https://github.com/grpc/grpc/issues/10885#issuecomment-302651331 |
269 | | - # that `grpc.RpcError` is also `grpc.call`. |
270 | | - for callback in self._callbacks: |
271 | | - callback(future) |
| 250 | + def _create_queue(self): |
| 251 | + """Create a queue for requests.""" |
| 252 | + return queue_module.Queue() |
272 | 253 |
|
273 | 254 | def open(self): |
274 | 255 | """Opens the stream.""" |
275 | 256 | if self.is_active: |
276 | | - raise ValueError("Can not open an already open stream.") |
| 257 | + raise ValueError("Cannot open an already open stream.") |
277 | 258 |
|
278 | 259 | request_generator = _RequestQueueGenerator( |
279 | 260 | self._request_queue, initial_request=self._initial_request |
@@ -322,7 +303,7 @@ def send(self, request): |
322 | 303 | request (protobuf.Message): The request to send. |
323 | 304 | """ |
324 | 305 | if self.call is None: |
325 | | - raise ValueError("Can not send() on an RPC that has never been open()ed.") |
| 306 | + raise ValueError("Cannot send on an RPC stream that has never been opened.") |
326 | 307 |
|
327 | 308 | # Don't use self.is_active(), as ResumableBidiRpc will overload it |
328 | 309 | # to mean something semantically different. |
@@ -343,20 +324,15 @@ def recv(self): |
343 | 324 | protobuf.Message: The received message. |
344 | 325 | """ |
345 | 326 | if self.call is None: |
346 | | - raise ValueError("Can not recv() on an RPC that has never been open()ed.") |
| 327 | + raise ValueError("Cannot recv on an RPC stream that has never been opened.") |
347 | 328 |
|
348 | 329 | return next(self.call) |
349 | 330 |
|
350 | 331 | @property |
351 | 332 | def is_active(self): |
352 | | - """bool: True if this stream is currently open and active.""" |
| 333 | + """True if this stream is currently open and active.""" |
353 | 334 | return self.call is not None and self.call.is_active() |
354 | 335 |
|
355 | | - @property |
356 | | - def pending_requests(self): |
357 | | - """int: Returns an estimate of the number of queued requests.""" |
358 | | - return self._request_queue.qsize() |
359 | | - |
360 | 336 |
|
361 | 337 | def _never_terminate(future_or_error): |
362 | 338 | """By default, no errors cause BiDi termination.""" |
@@ -544,7 +520,7 @@ def _send(self, request): |
544 | 520 | call = self.call |
545 | 521 |
|
546 | 522 | if call is None: |
547 | | - raise ValueError("Can not send() on an RPC that has never been open()ed.") |
| 523 | + raise ValueError("Cannot send on an RPC that has never been opened.") |
548 | 524 |
|
549 | 525 | # Don't use self.is_active(), as ResumableBidiRpc will overload it |
550 | 526 | # to mean something semantically different. |
@@ -563,7 +539,7 @@ def _recv(self): |
563 | 539 | call = self.call |
564 | 540 |
|
565 | 541 | if call is None: |
566 | | - raise ValueError("Can not recv() on an RPC that has never been open()ed.") |
| 542 | + raise ValueError("Cannot recv on an RPC that has never been opened.") |
567 | 543 |
|
568 | 544 | return next(call) |
569 | 545 |
|
|