Skip to content

Commit

Permalink
feat: Second batch of AsyncIO integration
Browse files Browse the repository at this point in the history
* Polling future
* Page iterator
* With unit tests
  • Loading branch information
lidizheng committed May 18, 2020
1 parent d2e6ec6 commit 93a8cb8
Show file tree
Hide file tree
Showing 9 changed files with 1,580 additions and 0 deletions.
157 changes: 157 additions & 0 deletions google/api_core/future/async_future.py
@@ -0,0 +1,157 @@
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""AsyncIO implementation of the abstract base Future class."""

import asyncio

from google.api_core import exceptions
from google.api_core import retry
from google.api_core import retry_async
from google.api_core.future import base


class _OperationNotComplete(Exception):
"""Private exception used for polling via retry."""
pass


RETRY_PREDICATE = retry.if_exception_type(
_OperationNotComplete,
exceptions.TooManyRequests,
exceptions.InternalServerError,
exceptions.BadGateway,
)
DEFAULT_RETRY = retry_async.AsyncRetry(predicate=RETRY_PREDICATE)


class AsyncFuture(base.Future):
"""A Future that polls peer service to self-update.
The :meth:`done` method should be implemented by subclasses. The polling
behavior will repeatedly call ``done`` until it returns True.
.. note: Privacy here is intended to prevent the final class from
overexposing, not to prevent subclasses from accessing methods.
Args:
retry (google.api_core.retry.Retry): The retry configuration used
when polling. This can be used to control how often :meth:`done`
is polled. Regardless of the retry's ``deadline``, it will be
overridden by the ``timeout`` argument to :meth:`result`.
"""

def __init__(self, retry=DEFAULT_RETRY):
super().__init__()
self._retry = retry
self._future = asyncio.get_event_loop().create_future()
self._background_task = None

async def done(self, retry=DEFAULT_RETRY):
"""Checks to see if the operation is complete.
Args:
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
Returns:
bool: True if the operation is complete, False otherwise.
"""
# pylint: disable=redundant-returns-doc, missing-raises-doc
raise NotImplementedError()

async def _done_or_raise(self):
"""Check if the future is done and raise if it's not."""
result = await self.done()
if not result:
raise _OperationNotComplete()

async def running(self):
"""True if the operation is currently running."""
result = await self.done()
return not result

async def _blocking_poll(self, timeout=None):
"""Poll and await for the Future to be resolved.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
"""
if self._future.done():
return

retry_ = self._retry.with_deadline(timeout)

try:
await retry_(self._done_or_raise)()
except exceptions.RetryError:
raise asyncio.TimeoutError(
"Operation did not complete within the designated " "timeout."
)

async def result(self, timeout=None):
"""Get the result of the operation.
Args:
timeout (int):
How long (in seconds) to wait for the operation to complete.
If None, wait indefinitely.
Returns:
google.protobuf.Message: The Operation's result.
Raises:
google.api_core.GoogleAPICallError: If the operation errors or if
the timeout is reached before the operation completes.
"""
await self._blocking_poll(timeout=timeout)
return self._future.result()

async def exception(self, timeout=None):
"""Get the exception from the operation.
Args:
timeout (int): How long to wait for the operation to complete.
If None, wait indefinitely.
Returns:
Optional[google.api_core.GoogleAPICallError]: The operation's
error.
"""
await self._blocking_poll(timeout=timeout)
return self._future.exception()

def add_done_callback(self, fn):
"""Add a callback to be executed when the operation is complete.
If the operation is completed, the callback will be scheduled onto the
event loop. Otherwise, the callback will be stored and invoked when the
future is done.
Args:
fn (Callable[Future]): The callback to execute when the operation
is complete.
"""
if self._background_task is None:
self._background_task = asyncio.get_event_loop().create_task(self._blocking_poll())
self._future.add_done_callback(fn)

def set_result(self, result):
"""Set the Future's result."""
self._future.set_result(result)

def set_exception(self, exception):
"""Set the Future's exception."""
self._future.set_exception(exception)
2 changes: 2 additions & 0 deletions google/api_core/gapic_v1/__init__.py
Expand Up @@ -23,4 +23,6 @@

if sys.version_info >= (3, 6):
from google.api_core.gapic_v1 import config_async # noqa: F401
from google.api_core.gapic_v1 import method_async # noqa: F401
__all__.append("config_async")
__all__.append("method_async")
217 changes: 217 additions & 0 deletions google/api_core/operation_async.py
@@ -0,0 +1,217 @@
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Futures for long-running operations returned from Google Cloud APIs.
These futures can be used to synchronously wait for the result of a
long-running operation using :meth:`Operation.result`:
.. code-block:: python
operation = my_api_client.long_running_method()
result = operation.result()
Or asynchronously using callbacks and :meth:`Operation.add_done_callback`:
.. code-block:: python
operation = my_api_client.long_running_method()
def my_callback(future):
result = future.result()
operation.add_done_callback(my_callback)
"""

import functools
import threading

from google.api_core import exceptions
from google.api_core import protobuf_helpers
from google.api_core.future import async_future
from google.longrunning import operations_pb2
from google.rpc import code_pb2


class AsyncOperation(async_future.AsyncFuture):
"""A Future for interacting with a Google API Long-Running Operation.
Args:
operation (google.longrunning.operations_pb2.Operation): The
initial operation.
refresh (Callable[[], ~.api_core.operation.Operation]): A callable that
returns the latest state of the operation.
cancel (Callable[[], None]): A callable that tries to cancel
the operation.
result_type (func:`type`): The protobuf type for the operation's
result.
metadata_type (func:`type`): The protobuf type for the operation's
metadata.
retry (google.api_core.retry.Retry): The retry configuration used
when polling. This can be used to control how often :meth:`done`
is polled. Regardless of the retry's ``deadline``, it will be
overridden by the ``timeout`` argument to :meth:`result`.
"""

def __init__(
self,
operation,
refresh,
cancel,
result_type,
metadata_type=None,
retry=async_future.DEFAULT_RETRY,
):
super().__init__(retry=retry)
self._operation = operation
self._refresh = refresh
self._cancel = cancel
self._result_type = result_type
self._metadata_type = metadata_type
self._completion_lock = threading.Lock()
# Invoke this in case the operation came back already complete.
self._set_result_from_operation()

@property
def operation(self):
"""google.longrunning.Operation: The current long-running operation."""
return self._operation

@property
def metadata(self):
"""google.protobuf.Message: the current operation metadata."""
if not self._operation.HasField("metadata"):
return None

return protobuf_helpers.from_any_pb(
self._metadata_type, self._operation.metadata
)

@classmethod
def deserialize(cls, payload):
"""Deserialize a ``google.longrunning.Operation`` protocol buffer.
Args:
payload (bytes): A serialized operation protocol buffer.
Returns:
~.operations_pb2.Operation: An Operation protobuf object.
"""
return operations_pb2.Operation.FromString(payload)

def _set_result_from_operation(self):
"""Set the result or exception from the operation if it is complete."""
# This must be done in a lock to prevent the async_future thread
# and main thread from both executing the completion logic
# at the same time.
with self._completion_lock:
# If the operation isn't complete or if the result has already been
# set, do not call set_result/set_exception again.
# Note: self._result_set is set to True in set_result and
# set_exception, in case those methods are invoked directly.
if not self._operation.done or self._future.done():
return

if self._operation.HasField("response"):
response = protobuf_helpers.from_any_pb(
self._result_type, self._operation.response
)
self.set_result(response)
elif self._operation.HasField("error"):
exception = exceptions.GoogleAPICallError(
self._operation.error.message,
errors=(self._operation.error,),
response=self._operation,
)
self.set_exception(exception)
else:
exception = exceptions.GoogleAPICallError(
"Unexpected state: Long-running operation had neither "
"response nor error set."
)
self.set_exception(exception)

async def _refresh_and_update(self, retry=async_future.DEFAULT_RETRY):
"""Refresh the operation and update the result if needed.
Args:
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
"""
# If the currently cached operation is done, no need to make another
# RPC as it will not change once done.
if not self._operation.done:
self._operation = await self._refresh(retry=retry)
self._set_result_from_operation()

async def done(self, retry=async_future.DEFAULT_RETRY):
"""Checks to see if the operation is complete.
Args:
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
Returns:
bool: True if the operation is complete, False otherwise.
"""
await self._refresh_and_update(retry)
return self._operation.done

async def cancel(self):
"""Attempt to cancel the operation.
Returns:
bool: True if the cancel RPC was made, False if the operation is
already complete.
"""
result = await self.done()
if result:
return False
else:
await self._cancel()
return True

async def cancelled(self):
"""True if the operation was cancelled."""
await self._refresh_and_update()
return (
self._operation.HasField("error")
and self._operation.error.code == code_pb2.CANCELLED
)


def from_gapic(operation, operations_client, result_type, **kwargs):
"""Create an operation future from a gapic client.
This interacts with the long-running operations `service`_ (specific
to a given API) via a gapic client.
.. _service: https://github.com/googleapis/googleapis/blob/\
050400df0fdb16f63b63e9dee53819044bffc857/\
google/longrunning/operations.proto#L38
Args:
operation (google.longrunning.operations_pb2.Operation): The operation.
operations_client (google.api_core.operations_v1.OperationsClient):
The operations client.
result_type (:func:`type`): The protobuf result type.
kwargs: Keyword args passed into the :class:`Operation` constructor.
Returns:
~.api_core.operation.Operation: The operation future to track the given
operation.
"""
refresh = functools.partial(operations_client.get_operation, operation.name)
cancel = functools.partial(operations_client.cancel_operation, operation.name)
return AsyncOperation(operation, refresh, cancel, result_type, **kwargs)

0 comments on commit 93a8cb8

Please sign in to comment.