o
     ik                     @   s   d Z ddlZddlZddlZddlZddlZddlZddlm	Z	 ddl
mZ eeZdZG dd deZG dd	 d	eZG d
d deZdd ZG dd deZG dd deZdS )z5Helpers for synchronous bidirectional streaming RPCs.    N)
exceptions)BidiRpcBasez!Thread-ConsumeBidirectionalStreamc                   @   s*   e Zd ZdZd
ddZdd Zdd	 ZdS )_RequestQueueGeneratora  A helper for sending requests to a gRPC stream from a Queue.

    This generator takes requests off a given queue and yields them to gRPC.

    This helper is useful when you have an indeterminate, indefinite, or
    otherwise open-ended set of requests to send through a request-streaming
    (or bidirectional) RPC.


    Example::

        requests = request_queue_generator(q)
        call = stub.StreamingRequest(iter(requests))
        requests.call = call

        for response in call:
            print(response)
            q.put(...)


    Args:
        queue (queue_module.Queue): The request queue.
        period (float): The number of seconds to wait for items from the queue
            before checking if the RPC is cancelled. In practice, this
            determines the maximum amount of time the request consumption
            thread will live after the RPC is cancelled.
        initial_request (Union[protobuf.Message,
                Callable[None, protobuf.Message]]): The initial request to
            yield. This is done independently of the request queue to allow fo
            easily restarting streams that require some initial configuration
            request.
       Nc                 C   s   || _ || _|| _d | _d S N)_queue_period_initial_requestcall)selfqueueperiodinitial_request r   t/var/www/snowflake_co_dev_github/snow_flake_back_end_deploy/env/lib/python3.10/site-packages/google/api_core/bidi.py__init__A   s   
z_RequestQueueGenerator.__init__c                 C   s   | j d u p	| j  S r   r
   	is_activer   r   r   r   
_is_activeG   s   z!_RequestQueueGenerator._is_activec                 c   s    | j d urt| j r|   V  n| j V  	 z
| jj| jd}W n tjy6   |  s4t	d Y d S Y qw |d u rBt	d d S |  sS| j
| t	d d S |V  q)NT)timeoutz9Empty queue and inactive call, exiting request generator.z"Cleanly exiting request generator.zEInactive call, replacing item on queue and exiting request generator.)r	   callabler   getr   queue_moduleEmptyr   _LOGGERdebugput)r   itemr   r   r   __iter__N   s6   


z_RequestQueueGenerator.__iter__)r   N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r      s
    
!r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )	_Throttlea  A context manager limiting the total entries in a sliding time window.

    If more than ``access_limit`` attempts are made to enter the context manager
    instance in the last ``time window`` interval, the exceeding requests block
    until enough time elapses.

    The context manager instances are thread-safe and can be shared between
    multiple threads. If multiple requests are blocked and waiting to enter,
    the exact order in which they are allowed to proceed is not determined.

    Example::

        max_three_per_second = _Throttle(
            access_limit=3, time_window=datetime.timedelta(seconds=1)
        )

        for i in range(5):
            with max_three_per_second as time_waited:
                print("{}: Waited {} seconds to enter".format(i, time_waited))

    Args:
        access_limit (int): the maximum number of entries allowed in the time window
        time_window (datetime.timedelta): the width of the sliding time window
    c                 C   sN   |dk rt d|tdkrt d|| _|| _tj|d| _t	 | _
d S )Nr   z&access_limit argument must be positiver   z1time_window argument must be a positive timedelta)maxlen)
ValueErrordatetime	timedelta_time_window_access_limitcollectionsdeque_past_entries	threadingLock_entry_lock)r   access_limittime_windowr   r   r   r      s   z_Throttle.__init__c                 C   s   | j \ tj | j }| jr%| jd |k r%| j  | jr%| jd |k st| j| jk r?| jtj  	 W d    dS | jd | 	 }t
| | jtj  |W  d    S 1 sbw   Y  d S )Nr   g        )r0   r'   nowr)   r-   popleftlenr*   appendtotal_secondstimesleep)r   cutoff_timeto_waitr   r   r   	__enter__   s   

$z_Throttle.__enter__c                 G   s   d S r   r   )r   _r   r   r   __exit__   s   z_Throttle.__exit__c                 C   s   d | jj| jt| jS )Nz#{}(access_limit={}, time_window={}))format	__class__r    r*   reprr)   r   r   r   r   __repr__   s   z_Throttle.__repr__N)r    r!   r"   r#   r   r<   r>   rB   r   r   r   r   r$      s    r$   c                   @   sD   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	dd Z
dS )BidiRpca8  A helper for consuming a bi-directional streaming RPC.

    This maps gRPC's built-in interface which uses a request iterator and a
    response iterator into a socket-like :func:`send` and :func:`recv`. This
    is a more useful pattern for long-running or asymmetric streams (streams
    where there is not a direct correlation between the requests and
    responses).

    Example::

        initial_request = example_pb2.StreamingRpcRequest(
            setting='example')
        rpc = BidiRpc(
            stub.StreamingRpc,
            initial_request=initial_request,
            metadata=[('name', 'value')]
        )

        rpc.open()

        while rpc.is_active():
            print(rpc.recv())
            rpc.send(example_pb2.StreamingRpcRequest(
                data='example'))

        rpc.close()

    This does *not* retry the stream on errors. See :class:`ResumableBidiRpc`.

    Args:
        start_rpc (grpc.StreamStreamMultiCallable): The gRPC method used to
            start the RPC.
        initial_request (Union[protobuf.Message,
                Callable[None, protobuf.Message]]): The initial request to
            yield. This is useful if an initial request is needed to start the
            stream.
        metadata (Sequence[Tuple(str, str)]): RPC metadata to include in
            the request.
    c                 C   s   t  S )zCreate a queue for requests.)r   Queuer   r   r   r   _create_queue   s   zBidiRpc._create_queuec              
   C   s   | j rtdt| j| jd}z| jt|| jd}W n tj	y/ } z| 
|j  d}~ww ||_t|dr@|j| j
 n|| j
 || _|| _dS )zOpens the stream.z#Cannot open an already open stream.)r   )metadataN_wrapped)r   r&   r   _request_queuer	   
_start_rpciter_rpc_metadatar   GoogleAPICallError_on_call_doneresponser
   hasattrrG   add_done_callback_request_generator)r   request_generatorr
   excr   r   r   open   s$   

zBidiRpc.openc                 C   s:   | j du rdS | jd | j   d| _d| _g | _dS )zCloses the stream.N)r
   rH   r   cancelrQ   r	   
_callbacksr   r   r   r   close  s   


zBidiRpc.closec                 C   s:   | j du r	td| j  r| j| dS t| j  dS )zQueue a message to be sent on the stream.

        Send is non-blocking.

        If the underlying RPC has been closed, this will raise.

        Args:
            request (protobuf.Message): The request to send.
        Nz8Cannot send on an RPC stream that has never been opened.)r
   r&   r   rH   r   nextr   requestr   r   r   send'  s
   


zBidiRpc.sendc                 C   s   | j du r	tdt| j S )zWait for a message to be returned from the stream.

        Recv is blocking.

        If the underlying RPC has been closed, this will raise.

        Returns:
            protobuf.Message: The received message.
        Nz8Cannot recv on an RPC stream that has never been opened.)r
   r&   rX   r   r   r   r   recv<  s   


zBidiRpc.recvc                 C      | j duo	| j  S )z1True if this stream is currently open and active.Nr   r   r   r   r   r   K     zBidiRpc.is_activeN)r    r!   r"   r#   rE   rT   rW   r[   r\   propertyr   r   r   r   r   rC      s    (rC   c                 C   s   dS )z-By default, no errors cause BiDi termination.Fr   )future_or_errorr   r   r   _never_terminateQ  s   ra   c                       s   e Zd ZdZedddf fdd	Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Z fddZedd Z  ZS )ResumableBidiRpca5  A :class:`BidiRpc` that can automatically resume the stream on errors.

    It uses the ``should_recover`` arg to determine if it should re-establish
    the stream on error.

    Example::

        def should_recover(exc):
            return (
                isinstance(exc, grpc.RpcError) and
                exc.code() == grpc.StatusCode.UNAVAILABLE)

        initial_request = example_pb2.StreamingRpcRequest(
            setting='example')

        metadata = [('header_name', 'value')]

        rpc = ResumableBidiRpc(
            stub.StreamingRpc,
            should_recover=should_recover,
            initial_request=initial_request,
            metadata=metadata
        )

        rpc.open()

        while rpc.is_active():
            print(rpc.recv())
            rpc.send(example_pb2.StreamingRpcRequest(
                data='example'))

    Args:
        start_rpc (grpc.StreamStreamMultiCallable): The gRPC method used to
            start the RPC.
        initial_request (Union[protobuf.Message,
                Callable[None, protobuf.Message]]): The initial request to
            yield. This is useful if an initial request is needed to start the
            stream.
        should_recover (Callable[[Exception], bool]): A function that returns
            True if the stream should be recovered. This will be called
            whenever an error is encountered on the stream.
        should_terminate (Callable[[Exception], bool]): A function that returns
            True if the stream should be terminated. This will be called
            whenever an error is encountered on the stream.
        metadata Sequence[Tuple(str, str)]: RPC metadata to include in
            the request.
        throttle_reopen (bool): If ``True``, throttling will be applied to
            stream reopen calls. Defaults to ``False``.
    NFc                    sb   t t| ||| || _|| _t | _d| _t	 | _
|r,tdtjddd| _d S d | _d S )NF   
   )seconds)r1   r2   )superrb   r   _should_recover_should_terminater.   RLock_operational_lock
_finalizedr/   _finalize_lockr$   r'   r(   _reopen_throttle)r   	start_rpcshould_recovershould_terminater   rF   throttle_reopenr@   r   r   r     s   	


zResumableBidiRpc.__init__c                 C   s^   | j " | jr	 W d    d S | jD ]}|| qd| _W d    d S 1 s(w   Y  d S )NT)rl   rk   rV   )r   resultcallbackr   r   r   	_finalize  s   

"zResumableBidiRpc._finalizec                 C   s   | j 8 | |r| | n| |s| | ntd |   W d    d S W d    d S W d    d S 1 s>w   Y  d S )Nz%Re-opening stream from gRPC callback.)rj   rh   ru   rg   r   r   _reopenr   futurer   r   r   rM     s   



"zResumableBidiRpc._on_call_donec                 C   s   | j f | jd ur| j rtd 	 W d    d S d | _d | _z!| jr>| j |   W d    n1 s8w   Y  n|   W n ty[ } ztd| | 	|  d }~ww t
d W d    d S 1 slw   Y  d S )Nz"Stream was already re-established.z"Failed to re-open stream due to %szRe-established stream)rj   r
   r   r   r   rQ   rm   rT   	Exceptionru   info)r   rS   r   r   r   rv     s.   



"zResumableBidiRpc._reopenc                 O   s   	 z||i |W S  t yy } zd| jS td|| | |r?|   td|| | | 	 W d   W Y d}~dS | |sV|   td|| | | |td| |   W d   n1 sjw   Y  W Y d}~nd}~ww q)aW  Wraps a method to recover the stream and retry on error.

        If a retryable error occurs while making the call, then the stream will
        be re-opened and the method will be retried. This happens indefinitely
        so long as the error is a retryable one. If an error occurs while
        re-opening the stream, then this method will raise immediately and
        trigger finalization of this object.

        Args:
            method (Callable[..., Any]): The method to call.
            args: The args to pass to the method.
            kwargs: The kwargs to pass to the method.
        TzCall to retryable %r caused %s.zTerminating %r due to %s.NzNot retrying %r due to %s.z$Re-opening stream from retryable %r.)	ry   rj   r   r   rh   rW   ru   rg   rv   )r   methodargskwargsrS   r   r   r   _recoverable  s.   


	

zResumableBidiRpc._recoverablec                 C   s`   | j  | j}W d    n1 sw   Y  |d u rtd| r*| j| d S t| d S )Nz1Cannot send on an RPC that has never been opened.)rj   r
   r&   r   rH   r   rX   )r   rZ   r
   r   r   r   _send  s   zResumableBidiRpc._sendc                 C   s   |  | j|S r   )r~   r   rY   r   r   r   r[     s   zResumableBidiRpc.sendc                 C   sD   | j  | j}W d    n1 sw   Y  |d u rtdt|S )Nz1Cannot recv on an RPC that has never been opened.)rj   r
   r&   rX   )r   r
   r   r   r   _recv  s   zResumableBidiRpc._recvc                 C   s   |  | jS r   )r~   r   r   r   r   r   r\   "  s   zResumableBidiRpc.recvc                    s   |  d  tt|   d S r   )ru   rf   rb   rW   r   rr   r   r   rW   %  s   
zResumableBidiRpc.closec                 C   s<   | j  | jduo| j W  d   S 1 sw   Y  dS )z7bool: True if this stream is currently open and active.N)rj   r
   rk   r   r   r   r   r   )  s   
$zResumableBidiRpc.is_active)r    r!   r"   r#   ra   r   ru   rM   rv   r~   r   r[   r   r\   rW   r_   r   __classcell__r   r   rr   r   rb   V  s$    6
#%	rb   c                   @   sb   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Ze	dd Z
dd Zdd Ze	dd ZdS )BackgroundConsumerau  A bi-directional stream consumer that runs in a separate thread.

    This maps the consumption of a stream into a callback-based model. It also
    provides :func:`pause` and :func:`resume` to allow for flow-control.

    Example::

        def should_recover(exc):
            return (
                isinstance(exc, grpc.RpcError) and
                exc.code() == grpc.StatusCode.UNAVAILABLE)

        initial_request = example_pb2.StreamingRpcRequest(
            setting='example')

        rpc = ResumeableBidiRpc(
            stub.StreamingRpc,
            initial_request=initial_request,
            should_recover=should_recover)

        def on_response(response):
            print(response)

        consumer = BackgroundConsumer(rpc, on_response)
        consumer.start()

    Note that error handling *must* be done by using the provided
    ``bidi_rpc``'s ``add_done_callback``. This helper will automatically exit
    whenever the RPC itself exits and will not provide any error details.

    Args:
        bidi_rpc (BidiRpc): The RPC to consume. Should not have been
            ``open()``ed yet.
        on_response (Callable[[protobuf.Message], None]): The callback to
            be called for every response on the stream.
        on_fatal_exception (Callable[[Exception], None]): The callback to
            be called on fatal errors during consumption. Default None.
    Nc                 C   s6   || _ || _d| _|| _t | _d | _t | _	d S )NF)
	_bidi_rpc_on_response_paused_on_fatal_exceptionr.   	Condition_wake_threadr/   rj   )r   bidi_rpcon_responseon_fatal_exceptionr   r   r   r   _  s   
zBackgroundConsumer.__init__c                 C   s   |    d S r   )resumerw   r   r   r   rM   h  s   z BackgroundConsumer._on_call_donec              
   C   sX  z[|   | j| j | j  | jjrZ| j | jr.t	d | j
  t	d | jsW d    n1 s8w   Y  t	d | j }t	d | jd urV| | | jjsW nH tjy } ztj	dt|dd | jd urw| | W Y d }~n'd }~w ty } ztdt| | jd ur| | W Y d }~nd }~ww td	t d S )
Nzpaused, waiting for waking.zwoken.zwaiting for recv.zrecved response.z%s caught error %s and will exit. Generally this is due to the RPC itself being cancelled and the error will be surfaced to the calling code.T)exc_infoz0%s caught unexpected exception %s and will exit.z
%s exiting)setr   rP   rM   rT   r   r   r   r   r   waitr\   r   r   rL   _BIDIRECTIONAL_CONSUMER_NAMEr   ry   	exceptionrz   )r   readyrN   rS   r   r   r   _thread_mainm  sR   













	zBackgroundConsumer._thread_mainc                 C   sn   | j * t }tjt| j|fdd}|  |  || _t	
d|j W d   dS 1 s0w   Y  dS )z;Start the background thread and begin consuming the thread.T)nametargetr|   daemonzStarted helper thread %sN)rj   r.   EventThreadr   r   startr   r   r   r   r   )r   r   threadr   r   r   r     s   "zBackgroundConsumer.startc                 C   sz   | j 0 | j  | jdur"|   | jd | j r"td d| _d| _	d| _
W d   dS 1 s6w   Y  dS )zStop consuming the stream and shutdown the background thread.

        NOTE: Cannot be called within `_thread_main`, since it is not
        possible to join a thread to itself.
        Ng      ?zBackground thread did not exit.)rj   r   rW   r   r   joinis_aliver   warningr   r   r   r   r   r   stop  s   



"zBackgroundConsumer.stopc                 C   r]   )z.bool: True if the background thread is active.N)r   r   r   r   r   r   r     r^   zBackgroundConsumer.is_activec                 C   s2   | j  d| _W d   dS 1 sw   Y  dS )zWPauses the response stream.

        This does *not* pause the request stream.
        TN)r   r   r   r   r   r   pause  s   "zBackgroundConsumer.pausec                 C   s<   | j  d| _| j   W d   dS 1 sw   Y  dS )zResumes the response stream.FN)r   r   
notify_allr   r   r   r   r     s   "zBackgroundConsumer.resumec                 C   s   | j S )z,bool: True if the response stream is paused.)r   r   r   r   r   	is_paused  s   zBackgroundConsumer.is_pausedr   )r    r!   r"   r#   r   rM   r   r   r   r_   r   r   r   r   r   r   r   r   r   7  s    
'	3
r   )r#   r+   r'   loggingr   r   r.   r8   google.api_corer   google.api_core.bidi_baser   	getLoggerr    r   r   objectr   r$   rC   ra   rb   r   r   r   r   r   <module>   s&   
oC  b