U
    h3                     @   s   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ G d	d
 d
ejZdddZdd Zdd ZdddZdd ZdddZdddZdS )a6  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)

    N)
exceptions)protobuf_helpers)polling)operations_pb2)json_format)code_pb2c                       sx   e Zd ZdZdejf fdd	Zedd Zedd Z	e
d	d
 Zdd ZdddZdddZdd Zdd Z  ZS )	OperationaH  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.
        polling (google.api_core.retry.Retry): The configuration used for polling.
            This parameter controls how often :meth:`done` is polled. If the
            ``timeout`` argument is specified in the :meth:`result` method, it will
            override the ``polling.timeout`` property.
        retry (google.api_core.retry.Retry): DEPRECATED: use ``polling`` instead.
            If specified it will override ``polling`` parameter to maintain
            backward compatibility.
    Nc                    sN   t t| jf d|i| || _|| _|| _|| _|| _t	 | _
|   d S )Nr   )superr   __init__
_operation_refresh_cancel_result_type_metadata_type	threadingLock_completion_lock_set_result_from_operation)self	operationrefreshcancelresult_typeZmetadata_typer   kwargs	__class__ =/tmp/pip-unpacked-wheel-eraazoov/google/api_core/operation.pyr
   I   s    

zOperation.__init__c                 C   s   | j S )zAgoogle.longrunning.Operation: The current long-running operation.)r   r   r   r   r   r   ]   s    zOperation.operationc                 C   s"   | j dsdS t| j| j jS )z8google.protobuf.Message: the current operation metadata.metadataN)r   HasFieldr   from_any_pbr   r   r   r   r   r   r   b   s     zOperation.metadatac                 C   s   t j|S )zDeserialize a ``google.longrunning.Operation`` protocol buffer.

        Args:
            payload (bytes): A serialized operation protocol buffer.

        Returns:
            ~.operations_pb2.Operation: An Operation protobuf object.
        )r   r   Z
FromString)r   payloadr   r   r   deserializel   s    
zOperation.deserializec              	   C   s   | j  | jjr| jr$W 5 Q R  dS | jdrNt| j| jj}| 	| nR| jdrt
j| jjj| jjj| jjf| jd}| | nt
d}| | W 5 Q R X dS )zASet the result or exception from the operation if it is complete.Nresponseerror)status_codemessageerrorsr$   zLUnexpected state: Long-running operation had neither response nor error set.)r   r   doneZ_result_setr    r   r!   r   r$   Z
set_resultr   Zfrom_grpc_statusr%   coder'   Zset_exceptionZGoogleAPICallError)r   r$   	exceptionr   r   r   r   x   s*     z$Operation._set_result_from_operationc                 C   s.   | j js*|r| j|dn|  | _ |   dS )zRefresh the operation and update the result if needed.

        Args:
            retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
        )retryN)r   r)   r   r   r   r,   r   r   r   _refresh_and_update   s    zOperation._refresh_and_updatec                 C   s   |  | | jjS )zChecks 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.
        )r.   r   r)   r-   r   r   r   r)      s    	
zOperation.donec                 C   s   |   rdS |   dS )zAttempt to cancel the operation.

        Returns:
            bool: True if the cancel RPC was made, False if the operation is
                already complete.
        FT)r)   r   r   r   r   r   r      s    zOperation.cancelc                 C   s$   |    | jdo"| jjjtjkS )z$True if the operation was cancelled.r%   )r.   r   r    r%   r*   r   Z	CANCELLEDr   r   r   r   	cancelled   s    zOperation.cancelled)N)N)__name__
__module____qualname____doc__r   ZDEFAULT_POLLINGr
   propertyr   r   classmethodr#   r   r.   r)   r   r/   __classcell__r   r   r   r   r   2   s   

	
!

r   c                 C   s6   d |}|dk	r|| } | d|d}t|t S )a  Refresh an operation using a JSON/HTTP client.

    Args:
        api_request (Callable): A callable used to make an API request. This
            should generally be
            :meth:`google.cloud._http.Connection.api_request`.
        operation_name (str): The name of the operation.
        retry (google.api_core.retry.Retry): (Optional) retry policy

    Returns:
        google.longrunning.operations_pb2.Operation: The operation.
    zoperations/{}NGETmethodpath)formatr   	ParseDictr   r   )api_requestoperation_namer,   r:   Zapi_responser   r   r   _refresh_http   s
    
r?   c                 C   s   d |}| d|d dS )a"  Cancel an operation using a JSON/HTTP client.

    Args:
        api_request (Callable): A callable used to make an API request. This
            should generally be
            :meth:`google.cloud._http.Connection.api_request`.
        operation_name (str): The name of the operation.
    zoperations/{}:cancelPOSTr8   N)r;   )r=   r>   r:   r   r   r   _cancel_http   s    	
rA   c                 K   sB   t | t }tt||j}tt||j}t||||f|S )a  Create an operation future using a HTTP/JSON client.

    This interacts with the long-running operations `service`_ (specific
    to a given API) via `HTTP/JSON`_.

    .. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/            v1beta1/operations#Operation

    Args:
        operation (dict): Operation as a dictionary.
        api_request (Callable): A callable used to make an API request. This
            should generally be
            :meth:`google.cloud._http.Connection.api_request`.
        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.
    )	r   r<   r   r   	functoolspartialr?   namerA   )r   r=   r   r   Zoperation_protor   r   r   r   r   from_http_json   s    rE   c                 C   s*   t j|d}| j}|dk	r"||}||S )a{  Refresh an operation using a gRPC client.

    Args:
        operations_stub (google.longrunning.operations_pb2.OperationsStub):
            The gRPC operations stub.
        operation_name (str): The name of the operation.
        retry (google.api_core.retry.Retry): (Optional) retry policy

    Returns:
        google.longrunning.operations_pb2.Operation: The operation.
    rD   N)r   ZGetOperationRequestZGetOperation)operations_stubr>   r,   
request_pbZrpcr   r   r   _refresh_grpc  s
    rI   c                 C   s   t j|d}| | dS )zCancel an operation using a gRPC client.

    Args:
        operations_stub (google.longrunning.operations_pb2.OperationsStub):
            The gRPC operations stub.
        operation_name (str): The name of the operation.
    rF   N)r   ZCancelOperationRequestZCancelOperation)rG   r>   rH   r   r   r   _cancel_grpc  s    rJ   c                 K   s:   t jt|| j|d}t jt|| j|d}t| |||f|S )a  Create an operation future using a gRPC client.

    This interacts with the long-running operations `service`_ (specific
    to a given API) via gRPC.

    .. _service: https://github.com/googleapis/googleapis/blob/                 050400df0fdb16f63b63e9dee53819044bffc857/                 google/longrunning/operations.proto#L38

    Args:
        operation (google.longrunning.operations_pb2.Operation): The operation.
        operations_stub (google.longrunning.operations_pb2.OperationsStub):
            The operations stub.
        result_type (:func:`type`): The protobuf result type.
        grpc_metadata (Optional[List[Tuple[str, str]]]): Additional metadata to pass
            to the rpc.
        kwargs: Keyword args passed into the :class:`Operation` constructor.

    Returns:
        ~.api_core.operation.Operation: The operation future to track the given
            operation.
    r   )rB   rC   rI   rD   rJ   r   )r   rG   r   grpc_metadatar   r   r   r   r   r   	from_grpc&  s    rM   c                 K   s:   t j|j| j|d}t j|j| j|d}t| |||f|S )a  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.
        grpc_metadata (Optional[List[Tuple[str, str]]]): Additional metadata to pass
            to the rpc.
        kwargs: Keyword args passed into the :class:`Operation` constructor.

    Returns:
        ~.api_core.operation.Operation: The operation future to track the given
            operation.
    rK   )rB   rC   Zget_operationrD   Zcancel_operationr   )r   Zoperations_clientr   rL   r   r   r   r   r   r   
from_gapicL  s    rN   )N)N)N)N)r3   rB   r   Zgoogle.api_corer   r   Zgoogle.api_core.futurer   Zgoogle.longrunningr   Zgoogle.protobufr   Z
google.rpcr   ZPollingFuturer   r?   rA   rE   rI   rJ   rM   rN   r   r   r   r   <module>   s"    


&