o
    tBhof                     @   s  d dl Z d dlZd dlZd dlm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Z	 e eZdZi d	d d
dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+iZd,ZejejejejejejejejfZejfZe d-d.d/gZ!G d0d1 d1e"Z#G d2d3 d3eZ$G d4d5 d5e"Z%G d6d7 d7e"Z&d8d9 Z'd:d; Z(d<d= Z)d>d? Z*G d@dA dAe"Z+dS )B    N)Enum)ResumableBidiRpc)BackgroundConsumer)	firestore)_helpers)
exceptionsiyP  OK	CANCELLED   UNKNOWN   INVALID_ARGUMENT   DEADLINE_EXCEEDED   	NOT_FOUND   ALREADY_EXISTS   PERMISSION_DENIED   UNAUTHENTICATED   RESOURCE_EXHAUSTED   FAILED_PRECONDITION	   ABORTED
   OUT_OF_RANGE   UNIMPLEMENTED   INTERNAL   UNAVAILABLE   	DATA_LOSS   
DO_NOT_USEzThread-OnRpcTerminatedDocTreeEntryvalueindexc                   @   sT   e Z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
dd ZdS )WatchDocTreec                 C   s   i | _ d| _d S )Nr   )_dict_indexself r3   v/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/watch.py__init__L   s   
zWatchDocTree.__init__c                 C   s   t | j S N)listr/   keysr1   r3   r3   r4   r8   P   s   zWatchDocTree.keysc                 C   s"   t  }| j |_| j|_|} | S r6   )r.   r/   copyr0   )r2   wdtr3   r3   r4   _copyS   s
   zWatchDocTree._copyc                 C   s,   |   } t|| j| j|< |  jd7  _| S )Nr
   )r;   r+   r0   r/   )r2   keyr,   r3   r3   r4   insertZ   s   zWatchDocTree.insertc                 C   s
   | j | S r6   r/   r2   r<   r3   r3   r4   find`      
zWatchDocTree.findc                 C   s   |   } | j|= | S r6   )r;   r/   r?   r3   r3   r4   removec   s   zWatchDocTree.removec                 c   s    | j D ]}|V  qd S r6   r>   r2   kr3   r3   r4   __iter__h   s   
zWatchDocTree.__iter__c                 C   s
   t | jS r6   )lenr/   r1   r3   r3   r4   __len__l   rA   zWatchDocTree.__len__c                 C   s
   || j v S r6   r>   rC   r3   r3   r4   __contains__o   rA   zWatchDocTree.__contains__N)__name__
__module____qualname__r5   r8   r;   r=   r@   rB   rE   rG   rH   r3   r3   r3   r4   r.   H   s    r.   c                   @   s   e Zd ZdZdZdZdS )
ChangeTyper
   r   r   N)rI   rJ   rK   ADDEDREMOVEDMODIFIEDr3   r3   r3   r4   rL   s   s    rL   c                   @      e Zd Zdd ZdS )DocumentChangec                 C   s   || _ || _|| _|| _dS )zDocumentChange

        Args:
            type (ChangeType):
            document (document.DocumentSnapshot):
            old_index (int):
            new_index (int):
        N)typedocument	old_index	new_index)r2   rR   rS   rT   rU   r3   r3   r4   r5   z   s   

zDocumentChange.__init__NrI   rJ   rK   r5   r3   r3   r3   r4   rQ   y       rQ   c                   @   rP   )WatchResultc                 C   s   || _ || _|| _d S r6   )snapshotnamechange_type)r2   rY   rZ   r[   r3   r3   r4   r5      s   
zWatchResult.__init__NrV   r3   r3   r3   r4   rX      rW   rX   c                 C   s   t | tjrt| S | S )z(Wraps a gRPC exception class, if needed.)
isinstancegrpcRpcErrorr   from_grpc_error)	exceptionr3   r3   r4   _maybe_wrap_exception   s   
ra   c                 C   s   | |ksJ ddS )Nz+Document watches only support one document.r   r3   )doc1doc2r3   r3   r4   document_watch_comparator   s   rd   c                 C      t | }t|tS r6   )ra   r\   _RECOVERABLE_STREAM_EXCEPTIONSr`   wrappedr3   r3   r4   _should_recover      
ri   c                 C   re   r6   )ra   r\   _TERMINATING_STREAM_EXCEPTIONSrg   r3   r3   r4   _should_terminate   rj   rl   c                   @   s   e Zd ZeZeZ		d*ddZdd Zedd Zd+dd	Z	d
d Z
dd Zedd Zedd Zdd Zdd Z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d&d' Zd(d) ZdS ),WatchNc
                 C   s   || _ || _|j| _|| _|| _|| _|| _|| _t	
 | _d| _d| _| j}
|	du r.| j}	|	| jjjtt|
| jjd| _| j| j t | _i | _i | _d| _d| _|du r[| j}|| j| j| _ | j !  dS )a
  
        Args:
            firestore:
            target:
            comparator:
            snapshot_callback: Callback method to process snapshots.
                Args:
                    docs (List(DocumentSnapshot)): A callback that returns the
                        ordered list of documents stored in this snapshot.
                    changes (List(str)): A callback that returns the list of
                        changed documents since the last snapshot delivered for
                        this watch.
                    read_time (string): The ISO 8601 time at which this
                        snapshot was obtained.

            document_snapshot_cls: instance of DocumentSnapshot
            document_reference_cls: instance of DocumentReference
        FN)should_recovershould_terminateinitial_requestmetadata)"_document_reference
_firestore_firestore_api_api_targets_comparatorDocumentSnapshotDocumentReference_snapshot_callback	threadingLock_closing_closedresume_token_get_rpc_requestr   
_transportlistenri   rl   _rpc_metadata_rpcadd_done_callback_on_rpc_doner.   doc_treedoc_map
change_mapcurrent
has_pushedr   on_snapshot	_consumerstart)r2   document_referencer   target
comparatorsnapshot_callbackdocument_snapshot_clsdocument_reference_clsr   r   rpc_requestr3   r3   r4   r5      s>   
zWatch.__init__c                 C   s*   | j d ur| j | jd< tj| jj| jdS )Nr   )database
add_target)r   rv   r   ListenRequestrs   _database_stringr1   r3   r3   r4   r     s
   

zWatch._get_rpc_requestc                 C   s   | j duo| j jS )zbool: True if this manager is actively streaming.

        Note that ``False`` does not indicate this is complete shut down,
        just that it stopped getting new messages.
        N)r   	is_activer1   r3   r3   r4   r   
  s   zWatch.is_activec                 C   s   | j 4 | jr	 W d   dS | jrtd | j  d| _| j  d| _d| _td W d   n1 s:w   Y  |rStd|  t	|t
rO|t|dS )a  Stop consuming messages and shutdown all helper threads.

        This method is idempotent. Additional calls will have no effect.

        Args:
            reason (Any): The reason to close this. If None, this is considered
                an "intentional" shutdown.
        NzStopping consumer.TzFinished stopping manager.zreason for closing: %s)r}   r~   r   _LOGGERdebugr   stopr   closer\   	ExceptionRuntimeError)r2   reasonr3   r3   r4   r     s&   	



zWatch.closec                 C   s:   t d t|}tjt| jd|id}d|_|  dS )a
  Triggered whenever the underlying RPC terminates without recovery.

        This is typically triggered from one of two threads: the background
        consumer thread (when calling ``recv()`` produces a non-recoverable
        error) or the grpc management thread (when cancelling the RPC).

        This method is *non-blocking*. It will start another thread to deal
        with shutting everything down. This is to prevent blocking in the
        background consumer and preventing it from being ``joined()``.
        z.RPC termination has signaled manager shutdown.r   )rZ   r   kwargsTN)	r   infora   r{   Thread_RPC_ERROR_THREAD_NAMEr   daemonr   )r2   futurethreadr3   r3   r4   r   2  s   
zWatch._on_rpc_donec                 C   s   |    d S r6   )r   r1   r3   r3   r4   unsubscribeE  s   zWatch.unsubscribec                 C   s$   | ||j d|jgitdt|||S )a*  
        Creates a watch snapshot listener for a document. snapshot_callback
        receives a DocumentChange object, but may also start to get
        targetChange and such soon

        Args:
            document_ref: Reference to Document
            snapshot_callback: callback to be called on snapshot
            snapshot_class_instance: instance of DocumentSnapshot to make
                snapshots with to pass to snapshot_callback
            reference_class_instance: instance of DocumentReference to make
                references

        	documents)r   	target_id)_client_document_pathWATCH_TARGET_IDrd   )clsdocument_refr   snapshot_class_instancereference_class_instancer3   r3   r4   for_documentH  s   
zWatch.for_documentc                 C   sB   |j  \}}tjj|| d}| ||j|jtd|j	|||S )N)parentstructured_query)queryr   )
_parent_parent_infor   TargetQueryTarget_to_protobufr   _pbr   rw   )r   r   r   r   r   parent_path_query_targetr3   r3   r4   	for_queryk  s   
zWatch.for_queryc                 C   sX   t d |j}|jd u pt|jdk}|r&|jr(| jr*| |j|j d S d S d S d S )Nz%on_snapshot: target change: NO_CHANGEr   )	r   r   target_change
target_idsrF   	read_timer   pushr   )r2   protochangeno_target_idsr3   r3   r4   $_on_snapshot_target_change_no_change~  s   
z*Watch._on_snapshot_target_change_no_changec                 C   s.   t d |jjd }|tkrtd| d S )Nzon_snapshot: target change: ADDr   z&Unexpected target ID %s sent by server)r   r   r   r   r   r   )r2   r   r   r3   r3   r4   _on_snapshot_target_change_add  s
   
z$Watch._on_snapshot_target_change_addc                 C   sB   t d |j}d}d}|jr|jj}|jj}d||f }t|)Nz"on_snapshot: target change: REMOVEr$   zinternal errorzError %s:  %s)r   r   r   causecodemessager   )r2   r   r   r   r   r3   r3   r4   !_on_snapshot_target_change_remove  s   
z'Watch._on_snapshot_target_change_removec                 C   s   t d |   d S )Nz!on_snapshot: target change: RESET)r   r   _reset_docsr2   r   r3   r3   r4    _on_snapshot_target_change_reset  s   
z&Watch._on_snapshot_target_change_resetc                 C   s   t d d| _d S )Nz#on_snapshot: target change: CURRENTT)r   r   r   r   r3   r3   r4   "_on_snapshot_target_change_current  s   

z(Watch._on_snapshot_target_change_currentc              
   C   s  t j}|jj| j|jj| j|jj| j|jj	| j
|jj| ji}t|dd}t|dd}t|dd}t|dd}t|dd}t|r|j}	tdt|	  ||	}
|
du rjtd	t|	  | jd
t|	 d dS z|
| W dS  ty } z
tdt|   d}~ww t|rtd |jpg }|jpg }d}d}t|v rd}t|v rd}|rtd |j}t|j| j}|j}| jj}|d }| |r|t!|d }| j|}| j"||dd|j#|j$d}|| j%|j< dS |rtd |j}t&j'| j%|j< dS dS t|rtd |j}t&j'| j%|< dS t|r1td |j}t&j'| j%|< dS |rItd |j(| ) krG| *  dS dS |du rT|   dS td | jt+d| d dS )aa  
        Called everytime there is a response from listen. Collect changes
        and 'push' the changes in a batch to the customer when we receive
        'current' from the listen response.

        Args:
            listen_response(`google.cloud.firestore_v1.types.ListenResponse`):
                Callback method that receives a object to
        r    document_changedocument_deletedocument_removefilterzon_snapshot: target change: Nz#on_snapshot: Unknown target change zUnknown target change type: %s )r   zmeth(proto) exc: zon_snapshot: document changeFTz%on_snapshot: document change: CHANGEDz/documents/)	referencedataexistsr   create_timeupdate_timez%on_snapshot: document change: REMOVEDz$on_snapshot: document change: DELETEz$on_snapshot: document change: REMOVEzon_snapshot: filter updatezUNKNOWN TYPE. UHOHz Unknown listen response type: %s),r   TargetChangeTargetChangeType	NO_CHANGEr   ADDr   REMOVEr   RESETr   CURRENTr   getattrstrtarget_change_typer   r   getr   r   r   r   removed_target_idsr   rS   r   decode_dictfieldsrs   rZ   r   
startswithrF   rx   r   r   r   rL   rN   count_current_sizer   
ValueError)r2   r   r   target_changetype_dispatchr   r   r   r   filter_r   methexc2r   r   changedremovedrS   r   document_namedb_strdb_str_documentsr   rY   rZ   r3   r3   r4   r     s   























zWatch.on_snapshotc                 C   s   t | j| j|\}}}| | j| j|||\}}}| jr!t|r9t	| j
}	t| |	d}
| |
|| d| _|| _|| _| j  || _dS )z
        Assembles a new snapshot from the current set of changes and invokes
        the user's callback. Clears the current changes on completion.
        r<   TN)rm   _extract_changesr   r   _compute_snapshotr   r   rF   	functools
cmp_to_keyrw   sortedr8   rz   clearr   )r2   r   next_resume_tokendeletesaddsupdatesupdated_treeupdated_mapappliedChangesr<   r8   r3   r3   r4   r   %  s   




z
Watch.pushc                 C   s   g }g }g }|  D ]0\}}|tjkr|| v r|| q
|| v r.|d ur(||_|| q
|d ur5||_|| q
|||fS r6   )itemsrL   rN   appendr   )r   changesr   r   r   r  rZ   r,   r3   r3   r4   r   @  s    


zWatch._extract_changesc                    s  |}|}t |t |ksJ ddd dd   fdd}g }	t| j}
t|}|D ]}|||\}}}|	| q-t||
d}td	 |D ]}td
  |||\}}}|	| qKt||
d}|D ]}||||\}}}|d ur}|	| qit |t |ksJ d|||	fS )NzJThe document tree and document map should have the same number of entries.c                 S   sP   | |v sJ d| | }||}|j}||}|| = ttj||d||fS )z
            Applies a document delete to the document tree and document map.
            Returns the corresponding DocumentChange event.
            z!Document to delete does not existr*   )r   r@   r-   rB   rQ   rL   rN   )rZ   r  r  old_documentexistingrT   r3   r3   r4   
delete_doc`  s   


z+Watch._compute_snapshot.<locals>.delete_docc                 S   sN   | j j}||vsJ d|| d}|| j}| ||< ttj| d|||fS )z
            Applies a document add to the document tree and the document map.
            Returns the corresponding DocumentChange event.
            zDocument to add already existsNr*   )r   r   r=   r@   r-   rQ   rL   rM   )new_documentr  r  rZ   rU   r3   r3   r4   add_docr  s   z(Watch._compute_snapshot.<locals>.add_docc                    sv   | j j}||v sJ d||}|j| jkr6|||\}}} | ||\}}}ttj| |j|j||fS d||fS )z
            Applies a document modification to the document tree and the
            document map.
            Returns the DocumentChange event for successful modifications.
            z!Document to modify does not existN)	r   r   r   r   rQ   rL   rO   rT   rU   )r  r  r  rZ   r  remove_change
add_changer  r
  r3   r4   
modify_doc  s(   



z+Watch._compute_snapshot.<locals>.modify_docr   zwalk over add_changeszin add_changeszQThe update document tree and document map should have the same number of entries.)rF   r   r   rw   r   r  r   r   )r2   r   r   delete_changesadd_changesupdate_changesr  r  r  r  r<   rZ   r   rY   r3   r  r4   r   U  sH   !






zWatch._compute_snapshotc                 C   s   |d u rdS ||v S )NTr3   )r2   r   
current_idr3   r3   r4   _affects_target  s   zWatch._affects_targetc                 C   s2   t | j| jd\}}}t| jt| t| S )zw
        Returns the current count of all documents, including the changes from
        the current changeMap.
        N)rm   r   r   r   rF   )r2   r   r   r   r3   r3   r4   r     s   zWatch._current_sizec                 C   sH   t d | j  d| _| j D ]}|jj}t	j
| j|< qd| _dS )zG
        Helper to clear the docs on RESET or filter mismatch.
        zresetting documentsNF)r   r   r   r   r   r   r8   r   r   rL   rN   r   )r2   rY   rZ   r3   r3   r4   r     s   


zWatch._reset_docs)NNr6   )rI   rJ   rK   r   r   r5   r   propertyr   r   r   r   classmethodr   r   r   r   r   r   r   r   r   staticmethodr   r   r  r   r   r3   r3   r3   r4   rm      s:    
V


"
~
qrm   ),loggingcollectionsr{   enumr   r   google.api_core.bidir   r   google.cloud.firestore_v1.typesr   google.cloud.firestore_v1r   google.api_corer   r]   	getLoggerrI   r   r   GRPC_STATUS_CODEr   Aborted	CancelledUnknownDeadlineExceededResourceExhaustedInternalServerErrorServiceUnavailableUnauthenticatedrf   rk   
namedtupler+   objectr.   rL   rQ   rX   ra   rd   ri   rl   rm   r3   r3   r3   r4   <module>   s   
	

+