Ë
    V¼Sf�7  ã            	       óP  — 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"  G d„ dejF                  e	«      Z$ G d„ de«      Z%de!de%fd„Z&de'de(defd„Z)eefde*de*de*de*fd„Z+y)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Ú	Generatorc                   ó,  ‡ — e Zd ZdZedfdˆ fd„Zdeddfˆ fd„Zddeddfd	„Z	dd
„Z
defd„Zej                  j                  dfdedej                   dedeeedf   fd„Zej                  j                  dfdej                   dedeeedf   fd„Zˆ x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`.
    FÚreturnNc                 óZ   •— t         t        | �  |«       t        j                  | ||«       y ©N)Úsuperr   Ú__init__r   )ÚselfÚclientÚmax_attemptsÚ	read_onlyÚ	__class__s       €údC:\Users\user\Documents\project_loop\venv\Lib\site-packages\google/cloud/firestore_v1/transaction.pyr    zTransaction.__init__@   s$   ø€ ÜŒk˜4Ñ)¨&Ô1Ü× Ñ   |°YÕ?ó    Ú	write_pbsc                 ób   •— | j                   rt        t        «      ‚t        t        | �  |«       y)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%   s     €r&   r,   zTransaction._add_write_pbsD   s'   ø€ ð �?Š?ÜÔ-Ó.Ð.äŒk˜4Ñ/°	Õ:r'   Úretry_idc                 óT  — | j                   r*t        j                  | j                  «      }t	        |«      ‚| j
                  j                  j                  | j
                  j                  | j                  |«      dœ| j
                  j                  ¬«      }|j                  | _        y)zìBegin 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_apiÚbegin_transactionÚ_database_stringÚ_options_protobufÚ_rpc_metadataÚtransaction)r!   r-   ÚmsgÚtransaction_responses       r&   Ú_beginzTransaction._beginS   sŠ   € ð ×ÒÜ×$Ñ$ T§X¡XÓ.ˆCÜ˜S“/Ð!à#Ÿ|™|×:Ñ:×LÑLà ŸL™L×9Ñ9Ø×1Ñ1°(Ó;ñð —\‘\×/Ñ/ð  Mó  
Ðð (×3Ñ3ˆ�r'   c                 ó>  — | j                   st        t        «      ‚	 | j                  j                  j                  | j                  j                  | j                  dœ| j                  j                  ¬«       | j                  «        y# | j                  «        w xY w)zÀRoll back the transaction.

        Raises:
            ValueError: If no transaction is in progress.
            google.api_core.exceptions.GoogleAPICallError: If the rollback fails.
        )r/   r=   r1   N)
r4   r+   r	   r7   r8   Úrollbackr:   r6   r<   Ú	_clean_up)r!   s    r&   Ú	_rollbackzTransaction._rollbackj   sy   € ð ×ÒÜœ^Ó,Ð,ð	à�L‰L×'Ñ'×0Ñ0à $§¡× =Ñ =Ø#'§8¡8ñð Ÿ™×3Ñ3ð 1ô ð �N‰NÕøˆD�N‰NÕús   �AB
 Â
Bc                 óØ   — | j                   st        t        «      ‚t        | j                  | 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.
        )
r4   r+   r
   Ú_commit_with_retryr7   Ú
_write_pbsr6   rC   ÚlistÚwrite_results)r!   Úcommit_responses     r&   Ú_commitzTransaction._commit�   sM   € ð ×ÒÜœ\Ó*Ð*ä,¨T¯\©\¸4¿?¹?ÈDÏHÉHÓUˆà�‰ÔÜ�O×1Ñ1Ó2Ð2r'   Ú
referencesr   Útimeoutc                 ól   — t        j                  ||«      } | 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.
        r=   )r   Úmake_retry_timeout_kwargsr7   Úget_all)r!   rL   r   rM   Úkwargss        r&   rP   zTransaction.get_all•   s7   € ô( ×3Ñ3°E¸7ÓCˆØ#ˆt�|‰|×#Ñ# JÑK¸DÐKÀFÑKÐKr'   c                 óì   — t        j                  ||«      }t        |t        «      r  | j                  j
                  |gfd| i|¤ŽS t        |t        «      r |j                  dd| i|¤ŽS t        d«      ‚)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.
        r=   zIValue for argument "ref_or_query" must be a DocumentReference or a Query.© )	r   rO   Ú
isinstancer   r7   rP   r   Ústreamr+   )r!   Úref_or_queryr   rM   rQ   s        r&   ÚgetzTransaction.get¬   sy   € ô& ×3Ñ3°E¸7ÓCˆÜ�lÔ$5Ô6Ø'�4—<‘<×'Ñ'¨¨ÑSÀDÐSÈFÑSÐSÜ˜¤eÔ,Ø&�<×&Ñ&ÑB°4ÐB¸6ÑBÐBäØ[óð r'   ©r   Nr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r    rH   r,   Úbytesr@   rD   rK   r   ÚmethodÚDEFAULTÚretriesÚRetryÚfloatr   r   r   rP   rW   Ú__classcell__©r%   s   @r&   r   r   2   så   ø„ ñð -9ÀEö @ð;¨ð ;°õ ;ñ4˜uð 4°ó 4ó.ð.3˜ó 3ð.  (Ÿ™×6Ñ6Øñ	LàðLð �}‰}ðLð ð	Lð
 
Ð# S¨$Ð.Ñ	/óLð4  (Ÿ™×6Ñ6Øñ	ð �}‰}ðð ð	ð
 
Ð# S¨$Ð.Ñ	/÷r'   r   c                   ó@   ‡ — e Zd ZdZdˆ fd„Zdedefd„Zdefd„Zˆ x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.
    r   c                 ó,   •— t         t        | �  |«       y r   )r   rf   r    )r!   Úto_wrapr%   s     €r&   r    z_Transactional.__init__Õ   s   ø€ ÜŒn˜dÑ,¨WÕ5r'   r=   c                 óâ   — |j                  «        |j                  | j                  ¬«       |j                  | _        | j                  €| j                  | _         | j
                  |g|¢­i |¤ŽS )am  Begin transaction and call the wrapped callable.

        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-   )rC   r@   r-   r6   Ú
current_idrh   )r!   r=   ÚargsrQ   s       r&   Ú_pre_commitz_Transactional._pre_commitØ   sb   € ð& 	×ÑÔØ×Ñ D§M¡MÐÔ2ð &Ÿ/™/ˆŒØ�=‰=Ð Ø ŸO™OˆDŒMØˆt�|‰|˜KÐ9¨$Ò9°&Ñ9Ð9r'   c                 ó¦  — | j                  «        |j                  st        j                  nd}d}	 t	        |j
                  «      D ],  } | j                  |g|¢­i |¤Ž}	 |j                  «        |c S  t        j                  |j
                  «      }	t        |	«      |‚# |$ r}|}Y d}~Œfd}~ww xY w# t        $ r |j                  «        ‚ w xY w)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``.
        rS   N)Ú_resetr*   r   ÚAbortedÚrangeÚ_max_attemptsrl   rK   r   r5   r+   ÚBaseExceptionrD   )
r!   r=   rk   rQ   Úretryable_exceptionsÚlast_excÚattemptÚresultÚexcr>   s
             r&   Ú__call__z_Transactional.__call__ô   sÙ   € ð& 	�‰Œà(3×(>Ò(>ŒZ×ÒÀBð 	ð ˆð	Ü  ×!:Ñ!:Ó;ò #�Ø)˜×)Ñ)¨+ÐG¸ÒGÀÑG�ð#Ø×'Ñ'Ô)Ø!’Mð	#ô ,×2Ñ2°;×3LÑ3LÓMˆCÜ˜S“/ xÐ/øð ,ò #Ø"•Hûð#ûô ò 	ð ×!Ñ!Ô#Øð		ús;   ².B5 Á!B!Á2B5 Á5,B5 Â!B2Â&B-Â(B5 Â-B2Â2B5 Â5CrX   )
rY   rZ   r[   r\   r    r   r   rl   rx   rc   rd   s   @r&   rf   rf   Ê   s,   ø„ ñõ6ð: {ð :Èó :ð8/ K÷ /r'   rf   rh   r   c                 ó   — 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.
    )rf   )rh   s    r&   Útransactionalrz   &  s   € ô ˜'Ó"Ð"r'   r(   Útransaction_idc                 óÆ   — t         }	 	 | j                  j                  | j                  ||dœ| j                  ¬«      S # t
        j                  $ r Y nw xY wt        |«      }Œ[)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/   Úwritesr=   r1   )r   r8   Úcommitr:   r<   r   ÚServiceUnavailableÚ_sleep)r"   r(   r{   Úcurrent_sleeps       r&   rF   rF   5  sy   € ô6 #€MØ
ð	Ø×(Ñ(×/Ñ/à &× 7Ñ 7Ø'Ø#1ñð
  ×-Ñ-ð 0ó ð øô ×,Ñ,ò 	áð	úô ˜}Ó-ˆð s   ‰4> ¾AÁAr�   Ú	max_sleepÚ
multiplierc                 óv   — t        j                  d| «      }t        j                  |«       t	        || z  |«      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)r�   r‚   rƒ   Úactual_sleeps       r&   r€   r€   b  s2   € ô, —>‘> # }Ó5€LÜ‡J�Jˆ|ÔÜˆz˜MÑ)¨9Ó5Ð5r'   ),r\   r…   r‡   Úgoogle.api_corer   r   r`   Ú*google.cloud.firestore_v1.base_transactionr   r   r   r   r	   r
   r   r   r   r   r   r   Úgoogle.cloud.firestore_v1r   Ú"google.cloud.firestore_v1.documentr   r   Úgoogle.cloud.firestore_v1.queryr   Ú'google.cloud.firestore_v1.base_documentr   Úgoogle.cloud.firestore_v1.typesr   Útypingr   r   r   Ú
WriteBatchr   rf   rz   rH   r]   rF   rb   r€   rS   r'   r&   ú<module>r”      sÑ   ðñ Ló Û å $Ý ,÷÷ ÷ ñ õ 'Ý +Ý @Ý .Ý 1õ EÝ :ß +Ñ +ôU�%×"Ñ" Oô UôpYÐ'ô Yðx#˜8ð #¨ó #ð*.Øð*.Ø-2ð*.àó*.ð\ .8È[ñ6Øð6Ø%*ð6ØEJð6à
ô6r'   