a
    !f9                     @   s0  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m	Z	m
Z
mZmZmZmZmZmZmZ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 ddlmZ ddlmZ ddlm Z m!Z!m"Z"m#Z# G dd dej$e	Z%G dd deZ&e!e&dddZ'e(e)edddZ*eefe+e+e+e+dddZ,dS )zEHelpers for applying Google Cloud Firestore changes in a transaction.    N)gapic_v1)retry)_BaseTransactionalBaseTransactionMAX_ATTEMPTS_CANT_BEGIN_CANT_ROLLBACK_CANT_COMMIT_WRITE_READ_ONLY_INITIAL_SLEEP
_MAX_SLEEP_MULTIPLIER_EXCEED_ATTEMPTS_TEMPLATE)
exceptions)batch)DocumentReference)_helpers)Query)DocumentSnapshot)CommitResponse)AnyCallable	GeneratorOptionalc                       s   e Zd ZdZedfdd fddZedd fdd	Zdedd
ddZ	ddddZ
edddZejjdfeejeeeedf dddZejjdfejeeeedf dddZ  ZS )TransactionaD  Accumulate read-and-write operations to be sent in a transaction.

    Args:
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            The client that created this transaction.
        max_attempts (Optional[int]): The maximum number of attempts for
            the transaction (i.e. allowing retries). Defaults to
            :attr:`~google.cloud.firestore_v1.transaction.MAX_ATTEMPTS`.
        read_only (Optional[bool]): Flag indicating if the transaction
            should be read-only or should allow writes. Defaults to
            :data:`False`.
    FNreturnc                    s"   t t| | t| || d S N)superr   __init__r   )selfclientZmax_attemptsZ	read_only	__class__ f/var/www/html/python-backend/venv/lib/python3.9/site-packages/google/cloud/firestore_v1/transaction.pyr   @   s    zTransaction.__init__)	write_pbsr   c                    s"   | j rtttt| | dS )a  Add `Write`` protobufs to this transaction.

        Args:
            write_pbs (List[google.cloud.proto.firestore.v1.                write.Write]): A list of write protobufs to be added.

        Raises:
            ValueError: If this transaction is read-only.
        N)
_read_only
ValueErrorr
   r   r   _add_write_pbs)r    r&   r"   r$   r%   r)   D   s    
zTransaction._add_write_pbs)retry_idr   c                 C   sL   | j rt| j}t|| jjj| jj| 	|d| jj
d}|j| _dS )zBegin the transaction.

        Args:
            retry_id (Optional[bytes]): Transaction ID of a transaction to be
                retried.

        Raises:
            ValueError: If the current transaction has already begun.
        )databaseoptionsrequestmetadataN)in_progressr   format_idr(   _client_firestore_apiZbegin_transaction_database_stringZ_options_protobuf_rpc_metadatatransaction)r    r*   msgZtransaction_responser$   r$   r%   _beginS   s    
zTransaction._beginc                 C   sL   | j sttz.| jjj| jj| jd| jjd W | 	  n
| 	  0 dS )znRoll back the transaction.

        Raises:
            ValueError: If no transaction is in progress.
        )r+   r7   r-   N)
r0   r(   r   r3   r4   rollbackr5   r2   r6   	_clean_up)r    r$   r$   r%   	_rollbackj   s    zTransaction._rollbackc                 C   s2   | j sttt| j| j| j}|   t|j	S )a  Transactionally commit the changes accumulated.

        Returns:
            List[:class:`google.cloud.proto.firestore.v1.write.WriteResult`, ...]:
            The write results corresponding to the changes committed, returned
            in the same order as the changes were applied to this transaction.
            A write result contains an ``update_time`` field.

        Raises:
            ValueError: If no transaction is in progress.
        )
r0   r(   r	   _commit_with_retryr3   Z
_write_pbsr2   r;   listZwrite_results)r    Zcommit_responser$   r$   r%   _commit   s
    zTransaction._commit)
referencesr   timeoutr   c                 C   s$   t ||}| jj|fd| i|S )ao  Retrieves multiple documents from Firestore.

        Args:
            references (List[.DocumentReference, ...]): Iterable of document
                references to be retrieved.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.  Defaults to a system-specified policy.
            timeout (float): The timeout for this request.  Defaults to a
                system-specified value.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        r7   )r   make_retry_timeout_kwargsr3   get_all)r    r@   r   rA   kwargsr$   r$   r%   rC      s    zTransaction.get_all)r   rA   r   c                 C   sZ   t ||}t|tr0| jj|gfd| i|S t|trN|jf d| i|S tddS )aO  Retrieve a document or a query result from the database.

        Args:
            ref_or_query: The document references or query object to return.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.  Defaults to a system-specified policy.
            timeout (float): The timeout for this request.  Defaults to a
                system-specified value.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        r7   zIValue for argument "ref_or_query" must be a DocumentReference or a Query.N)	r   rB   
isinstancer   r3   rC   r   streamr(   )r    Zref_or_queryr   rA   rD   r$   r$   r%   get   s    

zTransaction.get)N)__name__
__module____qualname____doc__r   r   r>   r)   bytesr9   r<   r?   r   methodDEFAULTretriesRetryfloatr   r   r   rC   rG   __classcell__r$   r$   r"   r%   r   2   s*   r   c                       sX   e Zd ZdZdd fddZeedddZeee	 dd	d
Z
edddZ  ZS )_TransactionalaY  Provide a callable object to use as a transactional decorater.

    This is surfaced via
    :func:`~google.cloud.firestore_v1.transaction.transactional`.

    Args:
        to_wrap (Callable[[:class:`~google.cloud.firestore_v1.transaction.Transaction`, ...], Any]):
            A callable that should be run (and retried) in a transaction.
    Nr   c                    s   t t| | d S r   )r   rS   r   )r    to_wrapr"   r$   r%   r      s    z_Transactional.__init__)r7   r   c                 O   sf   |   |j| jd |j| _| jdu r0| j| _z| j|g|R i |W S    |   Y n0 dS )a*  Begin transaction and call the wrapped callable.

        If the callable raises an exception, the transaction will be rolled
        back. If not, the transaction will be "ready" for ``Commit`` (i.e.
        it will have staged writes).

        Args:
            transaction
                (:class:`~google.cloud.firestore_v1.transaction.Transaction`):
                A transaction to execute the callable within.
            args (Tuple[Any, ...]): The extra positional arguments to pass
                along to the wrapped callable.
            kwargs (Dict[str, Any]): The extra keyword arguments to pass
                along to the wrapped callable.

        Returns:
            Any: result of the wrapped callable.

        Raises:
            Exception: Any failure caused by ``to_wrap``.
        )r*   N)r;   r9   r*   r2   Z
current_idrT   r<   )r    r7   argsrD   r$   r$   r%   _pre_commit   s    
z_Transactional._pre_commitc              
   C   s^   z|   W dS  tjyX } z0|jr( t|tjrBW Y d}~dS  W Y d}~n
d}~0 0 dS )a  Try to commit the transaction.

        If the transaction is read-write and the ``Commit`` fails with the
        ``ABORTED`` status code, it will be retried. Any other failure will
        not be caught.

        Args:
            transaction
                (:class:`~google.cloud.firestore_v1.transaction.Transaction`):
                The transaction to be ``Commit``-ed.

        Returns:
            bool: Indicating if the commit succeeded.
        TNF)r?   r   ZGoogleAPICallErrorr'   rE   ZAborted)r    r7   excr$   r$   r%   _maybe_commit   s    z_Transactional._maybe_commit)r7   c                 O   sf   |    t|jD ]2}| j|g|R i |}| |}|r|  S q|  t|j}t|dS )a  Execute the wrapped callable within a transaction.

        Args:
            transaction
                (:class:`~google.cloud.firestore_v1.transaction.Transaction`):
                A transaction to execute the callable within.
            args (Tuple[Any, ...]): The extra positional arguments to pass
                along to the wrapped callable.
            kwargs (Dict[str, Any]): The extra keyword arguments to pass
                along to the wrapped callable.

        Returns:
            Any: The result of the wrapped callable.

        Raises:
            ValueError: If the transaction does not succeed in
                ``max_attempts``.
        N)	_resetrangeZ_max_attemptsrV   rX   r<   r   r1   r(   )r    r7   rU   rD   attemptresultZ	succeededr8   r$   r$   r%   __call__  s    

z_Transactional.__call__)rH   rI   rJ   rK   r   r   r   rV   r   boolrX   r]   rR   r$   r$   r"   r%   rS      s
   
&rS   )rT   r   c                 C   s   t | S )a  Decorate a callable so that it runs in a transaction.

    Args:
        to_wrap
            (Callable[[:class:`~google.cloud.firestore_v1.transaction.Transaction`, ...], Any]):
            A callable that should be run (and retried) in a transaction.

    Returns:
        Callable[[:class:`~google.cloud.firestore_v1.transaction.Transaction`, ...], Any]:
        the wrapped callable.
    )rS   )rT   r$   r$   r%   transactional>  s    r_   )r&   transaction_idr   c                 C   sF   t }z| jj| j||d| jdW S  tjy6   Y n0 t|}qdS )a.  Call ``Commit`` on the GAPIC client with retry / sleep.

    Retries the ``Commit`` RPC on Unavailable. Usually this RPC-level
    retry is handled by the underlying GAPICd client, but in this case it
    doesn't because ``Commit`` is not always idempotent. But here we know it
    is "idempotent"-like because it has a transaction ID. We also need to do
    our own retry to special-case the ``INVALID_ARGUMENT`` error.

    Args:
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            A client with GAPIC client and configuration details.
        write_pbs (List[:class:`google.cloud.proto.firestore.v1.write.Write`, ...]):
            A ``Write`` protobuf instance to be committed.
        transaction_id (bytes):
            ID of an existing transaction that this commit will run in.

    Returns:
        :class:`google.cloud.firestore_v1.types.CommitResponse`:
        The protobuf response from ``Commit``.

    Raises:
        ~google.api_core.exceptions.GoogleAPICallError: If a non-retryable
            exception is encountered.
    )r+   Zwritesr7   r-   N)r   r4   commitr5   r6   r   ZServiceUnavailable_sleep)r!   r&   r`   current_sleepr$   r$   r%   r=   M  s    r=   )rc   	max_sleep
multiplierr   c                 C   s$   t d| }t| t||  |S )a  Sleep and produce a new sleep time.

    .. _Exponential Backoff And Jitter: https://www.awsarchitectureblog.com/                                        2015/03/backoff.html

    Select a duration between zero and ``current_sleep``. It might seem
    counterintuitive to have so much jitter, but
    `Exponential Backoff And Jitter`_ argues that "full jitter" is
    the best strategy.

    Args:
        current_sleep (float): The current "max" for sleep interval.
        max_sleep (Optional[float]): Eventual "max" sleep time
        multiplier (Optional[float]): Multiplier for exponential backoff.

    Returns:
        float: Newly doubled ``current_sleep`` or ``max_sleep`` (whichever
        is smaller)
    g        )randomuniformtimesleepmin)rc   rd   re   Zactual_sleepr$   r$   r%   rb   z  s    
rb   )-rK   rf   rh   Zgoogle.api_corer   r   rO   Z*google.cloud.firestore_v1.base_transactionr   r   r   r   r   r	   r
   r   r   r   r   r   Zgoogle.cloud.firestore_v1r   Z"google.cloud.firestore_v1.documentr   r   Zgoogle.cloud.firestore_v1.queryr   Z'google.cloud.firestore_v1.base_documentr   Zgoogle.cloud.firestore_v1.typesr   typingr   r   r   r   Z
WriteBatchr   rS   r_   r>   rL   r=   rQ   rb   r$   r$   r$   r%   <module>   s2   4 v.