|
| 1 | +# Copyright 2021 Google LLC |
| 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 | +"""Helpers for server-side asynchronous streaming in REST.""" |
| 16 | + |
| 17 | +from typing import Union |
| 18 | + |
| 19 | +import proto |
| 20 | +import google.protobuf.message |
| 21 | +import google.auth.aio.transport |
| 22 | +from google.api_core._rest_streaming_base import BaseResponseIterator |
| 23 | + |
| 24 | + |
| 25 | +class AsyncResponseIterator(BaseResponseIterator): |
| 26 | + """Asynchronous Iterator over REST API responses. |
| 27 | +
|
| 28 | + Args: |
| 29 | + response (google.auth.aio.transport.Response): An API response object. |
| 30 | + response_message_cls (Union[proto.Message, google.protobuf.message.Message]): A response |
| 31 | + class expected to be returned from an API. |
| 32 | +
|
| 33 | + Raises: |
| 34 | + ValueError: |
| 35 | + - If `response_message_cls` is not a subclass of `proto.Message` or `google.protobuf.message.Message`. |
| 36 | + - If `response` is not an instance of `google.auth.aio.transport.aiohttp.Response`. |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + response: google.auth.aio.transport.Response, |
| 42 | + response_message_cls: Union[proto.Message, google.protobuf.message.Message], |
| 43 | + ): |
| 44 | + self._response = response |
| 45 | + self._chunk_size = 1024 |
| 46 | + self._response_itr = None |
| 47 | + super(AsyncResponseIterator, self).__init__( |
| 48 | + response_message_cls=response_message_cls |
| 49 | + ) |
| 50 | + |
| 51 | + async def _create_response_iter(self): |
| 52 | + |
| 53 | + if not isinstance(self._response, google.auth.aio.transport.Response): |
| 54 | + raise ValueError( |
| 55 | + "Response must be of type google.auth.aio.transport.Response" |
| 56 | + ) |
| 57 | + |
| 58 | + # TODO (ohmayr): Ideally the response from auth should expose an attribute |
| 59 | + # to read streaming response iterator directly i.e. |
| 60 | + # |
| 61 | + # self -> google.auth.aio.transport.aiohttp.Response: |
| 62 | + # def stream_response_itr(self, chunk_size): |
| 63 | + # return self._response.content.iter_chunked(chunk_size) |
| 64 | + # |
| 65 | + # self -> google.auth.aio.transport.httpx.Response: |
| 66 | + # def stream_response_itr(self, chunk_size): |
| 67 | + # return self._response.aiter_raw(chunk_size) |
| 68 | + # |
| 69 | + # this way we can just call the property directly to get the appropriate |
| 70 | + # response iterator without having to deal with the underlying API differences |
| 71 | + # or alternatively, having to check the type of inherited response types here |
| 72 | + # i.e we could do: self._response_itr = self._response.stream_response_itr(self._chunk_size) |
| 73 | + |
| 74 | + content = self._response.content |
| 75 | + if hasattr(content, "iter_chunked"): |
| 76 | + return content.iter_chunked(self._chunk_size) |
| 77 | + else: |
| 78 | + # TODO (ohmayr): since iter_chunked is only available in an instance of |
| 79 | + # google.auth.aio.transport.aiohttp.Response, we indirectly depend on |
| 80 | + # on the inherited class. |
| 81 | + raise ValueError( |
| 82 | + f"Unsupported Response type: {type(self._response)}. Expected google.auth.aio.transport.aiohttp.Response." |
| 83 | + ) |
| 84 | + |
| 85 | + async def cancel(self): |
| 86 | + """Cancel existing streaming operation.""" |
| 87 | + await self._response.close() |
| 88 | + |
| 89 | + async def __anext__(self): |
| 90 | + while not self._ready_objs: |
| 91 | + try: |
| 92 | + if not self._response_itr: |
| 93 | + self._response_itr = await self._create_response_iter() |
| 94 | + # TODO (ohmayr): cleanup |
| 95 | + # content = await self._response.content |
| 96 | + # self._response_itr = content.iter_chunked(self._chunk_size) |
| 97 | + |
| 98 | + chunk = await self._response_itr.__anext__() |
| 99 | + chunk = chunk.decode("utf-8") |
| 100 | + self._process_chunk(chunk) |
| 101 | + except StopAsyncIteration as e: |
| 102 | + if self._level > 0: |
| 103 | + raise ValueError("i Unfinished stream: %s" % self._obj) |
| 104 | + raise e |
| 105 | + except ValueError as e: |
| 106 | + raise e |
| 107 | + return self._grab() |
| 108 | + |
| 109 | + def __aiter__(self): |
| 110 | + return self |
| 111 | + |
| 112 | + async def __aexit__(self, exc_type, exc, tb): |
| 113 | + """Cancel existing streaming operation.""" |
| 114 | + await self._response.close() |
0 commit comments