
    (phnd                        S SK r S SKrS SKrS SKrS SKJr  S SKrS SKJr  S SK	J
r
Jr  S SKJr  S SKJrJrJr  \R$                  r\R&                  " \5      rSr0 SS _S	S
_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS _S!S"_S#S$_S%S&_S'S(_S)S*0ErS+r\R2                  \R4                  \R6                  \R8                  \R:                  \R<                  \R>                  \R@                  4r!\R4                  4r"\ RF                  " S,S-S./5      r$ " S/ S0\%5      r& " S1 S2\5      r' " S3 S4\%5      r( " S5 S6\%5      r)S7 r*S8 r+S9 r,S: r- " S; S<\%5      r.g)=    N)Enum)
exceptions)BackgroundConsumerResumableBidiRpc)_helpers)ListenRequestTargetTargetChangeiyP  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                   J    \ rS rSrS rS rS rS rS rS r	S r
S	 rS
 rSrg)WatchDocTreeJ   c                      0 U l         SU l        g )Nr   _dict_indexselfs    R/var/www/html/venv/lib/python3.13/site-packages/google/cloud/firestore_v1/watch.py__init__WatchDocTree.__init__N   s    
    c                 H    [        U R                  R                  5       5      $ N)listr6   keysr8   s    r:   rA   WatchDocTree.keysR   s    DJJOO%&&r=   c                 ~    [        5       nU R                  R                  5       Ul        U R                  Ul        Un U $ r?   )r2   r6   copyr7   )r9   wdts     r:   _copyWatchDocTree._copyU   s0    nJJOO%	[[
r=   c                     U R                  5       n [        X R                  5      U R                  U'   U =R                  S-  sl        U $ )Nr   )rF   r.   r7   r6   )r9   keyr/   s      r:   insertWatchDocTree.insert\   s6    zz|&ukk:

3qr=   c                      U R                   U   $ r?   r6   r9   rI   s     r:   findWatchDocTree.findb   s    zz#r=   c                 @    U R                  5       n U R                  U	 U $ r?   )rF   r6   rN   s     r:   removeWatchDocTree.removee   s    zz|JJsOr=   c              #   :   #    U R                    H  nUv   M	     g 7fr?   rM   r9   ks     r:   __iter__WatchDocTree.__iter__j   s     AG s   c                 ,    [        U R                  5      $ r?   )lenr6   r8   s    r:   __len__WatchDocTree.__len__n   s    4::r=   c                     XR                   ;   $ r?   rM   rU   s     r:   __contains__WatchDocTree.__contains__q   s    JJr=   r5   N)__name__
__module____qualname____firstlineno__r;   rA   rF   rJ   rO   rR   rW   r[   r^   __static_attributes__ r=   r:   r2   r2   J   s/    '
r=   r2   c                        \ rS rSrSrSrSrSrg)
ChangeTypeu   r   r   r   re   N)r`   ra   rb   rc   ADDEDREMOVEDMODIFIEDrd   re   r=   r:   rg   rg   u   s    EGHr=   rg   c                       \ rS rSrS rSrg)DocumentChange{   c                 4    Xl         X l        X0l        X@l        g)zDocumentChange

Args:
    type (ChangeType):
    document (document.DocumentSnapshot):
    old_index (int):
    new_index (int):
N)typedocument	old_index	new_index)r9   rp   rq   rr   rs   s        r:   r;   DocumentChange.__init__|   s     	 ""r=   )rq   rs   rr   rp   Nr`   ra   rb   rc   r;   rd   re   r=   r:   rm   rm   {   s    #r=   rm   c                       \ rS rSrS rSrg)WatchResult   c                 (    Xl         X l        X0l        g r?   )snapshotnamechange_type)r9   rz   r{   r|   s       r:   r;   WatchResult.__init__   s     	&r=   )r|   r{   rz   Nru   re   r=   r:   rw   rw      s    'r=   rw   c                 p    [        U [        R                  5      (       a  [        R                  " U 5      $ U $ )z(Wraps a gRPC exception class, if needed.)
isinstancegrpcRpcErrorr   from_grpc_error)	exceptions    r:   _maybe_wrap_exceptionr      s*    )T]]++)))44r=   c                     X:X  d   S5       eg)Nz+Document watches only support one document.r   re   )doc1doc2s     r:   document_watch_comparatorr      s    <FFF<r=   c                 8    [        U 5      n[        U[        5      $ r?   )r   r   _RECOVERABLE_STREAM_EXCEPTIONSr   wrappeds     r:   _should_recoverr          #I.Gg=>>r=   c                 8    [        U 5      n[        U[        5      $ r?   )r   r   _TERMINATING_STREAM_EXCEPTIONSr   s     r:   _should_terminater      r   r=   c            
       @   \ rS rSrS rS r\S 5       r\S 5       rS r	S r
\S 5       rSS
 jrS rS rS rS rS rS rS r\R,                  \\R.                  \\R0                  \\R2                  \\R4                  \0rS rS rS r\S 5       r S r!S r"S r#Sr$g	)Watch   c                 j   Xl         X l        X0l        X@l        X`l        XPl        UR                  U l        [        R                  " 5       U l
        SU l        U R                  UR                  5        SU l        [        5       U l        0 U l        0 U l        SU l        SU l        U R+                  5         g)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: factory for instances of DocumentSnapshot
FN)_document_reference
_firestore_targets_comparator_document_snapshot_cls_snapshot_callback_firestore_api_api	threadingLock_closing_closed_set_documents_pfx_database_stringresume_tokenr2   doc_treedoc_map
change_mapcurrent
has_pushed_init_stream)r9   document_reference	firestoretarget
comparatorsnapshot_callbackdocument_snapshot_clss          r:   r;   Watch.__init__   s    4 $6 #%&;#"3,,	!(	 : :; 
 %   
  r=   c                 |   U R                   n[        U R                  R                  R                  [
        [        UU R                  R                  S9U l	        U R                  R                  U R                  5        [        U R                  U R                  5      U l        U R                  R                  5         g )N)	start_rpcshould_recovershould_terminateinitial_requestmetadata)_get_rpc_requestr   r   
_transportlistenr   r   r   _rpc_metadata_rpcadd_done_callback_on_rpc_doner   on_snapshot	_consumerstart)r9   rpc_requests     r:   r   Watch._init_stream   s    ++$ii**11*.'__22
	 			##D$5$56 ,DIIt7G7GHr=   c                 `    U " UUR                   SUR                  /0[        S.[        UU5      $ )aq  
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
    document_snapshot_cls: class to make snapshots with
    reference_class_instance: class make references

	documents)r   	target_id)_client_document_pathWATCH_TARGET_IDr   )clsdocument_refr   r   s       r:   for_documentWatch.for_document   sA    &   )L,G,G+HI, &!

 
	
r=   c                     UR                   R                  5       u  pE[        R                  " XAR	                  5       S9nU " UUR
                  UR                  [        S.UR                  UU5      $ )N)parentstructured_query)queryr   )	_parent_parent_infor	   QueryTarget_to_protobufr   _pbr   r   )r   r   r   r   parent_path_query_targets          r:   	for_queryWatch.for_query  sh    335))1C1C1E
 MM"&&_E!
 	
r=   c                     U R                   b  U R                   U R                  S'   OU R                  R                  SS 5        [        U R                  R
                  U R                  S9$ )Nr   )database
add_target)r   r   popr   r   r   r8   s    r:   r   Watch._get_rpc_request(  sV    (,0,=,=DMM.)MMnd3__55$--
 	
r=   c                 L    U S3U l         [        U R                   5      U l        g )Nz/documents/)_documents_pfxrZ   _documents_pfx_len)r9   database_strings     r:   r   Watch._set_documents_pfx2  s%    !0 1="%d&9&9":r=   c                 X    U R                   SL=(       a    U R                   R                  $ )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_activer8   s    r:   r   Watch.is_active6  s"     ~~T)Fdnn.F.FFr=   Nc                    U R                      U R                  (       a
   SSS5        gU R                  (       a/  [        R	                  S5        U R
                  R                  5         SU R
                  l        SU l        SU l        U R                  R                  5         SU R                  l        / U R                  l        SU l	        SU l        [        R	                  S5        SSS5        U(       a:  [        R	                  SU-  5        [        U[        5      (       a  Ue[        U5      eg! , (       d  f       NP= f)zStop 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   stop_on_responser   r   close_initial_request
_callbacksr   	ExceptionRuntimeError)r9   reasons     r:   r   Watch.close?  s     ]]|| ]
 ~~23##%*.DNN'!DN&*D#IIOO)-DII&#%DII DIDLMM67# & MM2V;<&),,v&& ' ]s   D1B>D11
D?c                     [         R                  S5        [        U5      n[        R                  " [
        U R                  SU0S9nSUl        UR                  5         g)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   )r{   r   kwargsTN)	r   infor   r   Thread_RPC_ERROR_THREAD_NAMEr   daemonr   )r9   futurethreads      r:   r   Watch._on_rpc_doneb  sM     	EF&v.!!'

HfCU
 r=   c                 $    U R                  5         g r?   )r   r8   s    r:   unsubscribeWatch.unsubscribeu  s    

r=   c                 ,   [         R                  S5        UR                  S L =(       d    [        UR                  5      S:H  nU(       aK  UR                  (       a9  U R
                  (       a'  U R                  UR                  UR                  5        g g g g )Nz%on_snapshot: target change: NO_CHANGEr   )r   r   
target_idsrZ   	read_timer   pushr   )r9   target_changeno_target_idss      r:   $_on_snapshot_target_change_no_change*Watch._on_snapshot_target_change_no_changex  st    => $$,RM4L4L0MQR0R 	 ]44
 IIm--}/I/IJ :F4=r=   c                 |    [         R                  S5        UR                  S   nU[        :w  a  [	        SU-  5      eg )Nzon_snapshot: target change: ADDr   z&Unexpected target ID %s sent by server)r   r   r  r   r   )r9   r  r   s      r:   _on_snapshot_target_change_add$Watch._on_snapshot_target_change_add  s=    78!,,Q/	'G)STT (r=   c                    [         R                  S5        UR                  R                  (       a-  UR                  R                  nUR                  R                  nOSnSnSU< SU< 3n[        U5      [        R                  " X#5      e)Nz"on_snapshot: target change: REMOVEr'   zinternal errorzError z:  )r   r   causecodemessager   r   from_grpc_status)r9   r  r  r  error_messages        r:   !_on_snapshot_target_change_remove'Watch._on_snapshot_target_change_remove  sr    :;## &&++D#))11GD&G+/9=)z/J/J0
 	
r=   c                 N    [         R                  S5        U R                  5         g )Nz!on_snapshot: target change: RESET)r   r   _reset_docsr9   r  s     r:    _on_snapshot_target_change_reset&Watch._on_snapshot_target_change_reset  s    9:r=   c                 <    [         R                  S5        SU l        g )Nz#on_snapshot: target change: CURRENTT)r   r   r   r  s     r:   "_on_snapshot_target_change_current(Watch._on_snapshot_target_change_current  s    ;<r=   c                 b    UR                  U R                  5      (       a  XR                  S  nU$ r?   )
startswithr   r   )r9   document_names     r:   _strip_document_pfxWatch._strip_document_pfx  s0    ##D$7$788)*A*A*CDMr=   c           	      *   U R                   R                  5       (       a  gUc  U R                  5         gUR                  nUR	                  S5      nUS:X  a  UR
                  R                  n[        R                  SU 35        U R                  R                  U5      nUc5  SU 3n[        R                  SU 35        U R                  [        U5      S9   U" XR
                  5        gUS	:X  Gah  [        R                  S
5        [        UR                  R                   ;   n[        UR                  R"                  ;   n	UR                  R$                  n
U(       a  [        R                  S5        [&        R(                  " U
R*                  U R,                  5      nU R/                  U
R0                  5      nU R,                  R%                  U5      nU R3                  UUSSU
R4                  U
R6                  S9nXR8                  U
R0                  '   gU	(       a=  [        R                  S5        [:        R<                  U R8                  U
R0                  '   ggUS:X  aI  [        R                  S5        UR>                  R$                  n[:        R<                  U R8                  U'   gUS:X  aI  [        R                  S5        UR@                  R$                  n[:        R<                  U R8                  U'   gUS:X  a  [        R                  S5        URB                  RD                  U RG                  5       :w  ay  [        R                  S5        [H        RJ                  " [L        U R                  S9nURO                  5         URQ                  5         U RS                  5         U RU                  5         gg[        R                  S5        SU 3nU R                  [        U5      S9  g! [         a  n[        R                  SU 35        e SnAff = f)a#  Process a response from the bi-directional gRPC stream.

Collect changes and push the changes in a batch to the customer
when we receive 'current' from the listen response.

Args:
    proto(`google.cloud.firestore_v1.types.ListenResponse`):
        Callback method that receives a object to
Nresponse_typer  zon_snapshot: target change: zUnknown target change type: zon_snapshot: )r   zmeth(proto) exc: document_changezon_snapshot: document changez%on_snapshot: document change: CHANGEDT)	referencedataexistsr  create_timeupdate_timez%on_snapshot: document change: REMOVEDdocument_deletez$on_snapshot: document change: DELETEdocument_removez$on_snapshot: document change: REMOVEfilterzon_snapshot: filter updatez%Filter mismatch -- restarting stream.)r{   r   zUNKNOWN TYPE. UHOHzUnknown listen response type: )+r   lockedr   r   
WhichOneofr  target_change_typer   r   _target_changetype_dispatchgetr   
ValueErrorr   r   r#  r  removed_target_idsrq   r   decode_dictfieldsr   r  r{   r   r'  r(  r   rg   rj   r)  r*  r+  count_current_sizer   r   r   r   joinr  r   )r9   protopbwhichr.  methr  exc2changedremovedrq   r%  r  r   rz   r{   r   s                    r:   r   Watch.on_snapshot  sJ    ==!!=JJLYYo.O#!#!1!1!D!DMM89K8LMN33778JKD|89K8LM}WI67

*W"5
6T../ ''MM89 &););)F)FFG%););)N)NNG ,,55HEF++HOOT__M
 !% 8 8 G#77F66*" ( 4 4 ( 4 4 7  2:.EF1;1C1C.  ''MM@A%%..D$.$6$6DOOD!''MM@A%%..D$.$6$6DOOD!hMM67yy$"4"4"66DE"))/::   "!!# 7 MM./6ug>GJJj1J2[   1$89s   O* *
P4PPc                    U R                  U R                  U R                  U5      u  p4nU R                  U R                  U R                  X4U5      u  pgnU R
                  (       a  [        U5      (       aQ  [        R                  " U R                  5      n	[        UR                  5       U	S9n
U R                  XU5        SU l        X`l        Xpl        U R                  R                  5         X l        g)zInvoke the callback with a new snapshot

Build the sntapshot from the current set of changes.

Clear the current changes on completion.
rI   TN)_extract_changesr   r   _compute_snapshotr   r   rZ   	functools
cmp_to_keyr   sortedrA   r   clearr   )r9   r  next_resume_tokendeletesaddsupdatesupdated_treeupdated_mapappliedChangesrI   rA   s              r:   r  
Watch.push"  s     "&!6!6LL$//9"
w 594J4JMM4<<5
1> #n"5"5 &&t'7'78C,++-37D##D)D"DO$"-r=   c                    / n/ n/ nUR                  5        Hn  u  pgU[        R                  :X  a  X`;   a  UR                  U5        M1  M3  X`;   a  Ub  X'l        UR                  U5        MT  Ub  X'l        UR                  U5        Mp     X4U4$ r?   )itemsrg   rj   appendr  )r   changesr  rI  rJ  rK  r{   r/   s           r:   rB  Watch._extract_changes?  s    "==?KD
***?NN4( #(&/Ou%(&/OE" + w''r=   c                 l  ^^ UnUn[        U5      [        U5      :X  d   S5       eS mS mUU4S jn/ n	[        R                  " U R                  5      n
[	        U5      nU H   nT" XU5      u  pnU	R                  U5        M"     [	        XJS9n[        R                  S5        U H5  n[        R                  S5        T" XU5      u  pnU	R                  U5        M7     [	        XZS9nU H%  nU" XU5      u  pnUc  M  U	R                  U5        M'     [        U5      [        U5      :X  d   S5       eXgU	4$ )	NzJThe document tree and document map should have the same number of entries.c                     X;   d   S5       eUR                  U 5      nUR                  U5      nUR                  nUR                  U5      nX 	 [	        [
        R                  X5S5      UU4$ )zr
Applies a document delete to the document tree and document map.
Returns the corresponding DocumentChange event.
z!Document to delete does not existr-   )r0  rO   r0   rR   rm   rg   rj   )r{   rL  rM  old_documentexistingrr   s         r:   
delete_doc+Watch._compute_snapshot.<locals>.delete_doc_  su    
 &K(KK&&??40L#((6H I'..|<L!z11<BO r=   c                     U R                   R                  nX2;  d   S5       eUR                  U S5      nUR                  U 5      R                  nXU'   [        [        R                  U SU5      UU4$ )zs
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   rJ   rO   r0   rm   rg   ri   )new_documentrL  rM  r{   rs   s        r:   add_doc(Watch._compute_snapshot.<locals>.add_docq  s{    
  ))88D*L,LL*'..|TBL$)),7==I ,z//r9M r=   c                 <  > U R                   R                  nX2;   d   S5       eUR                  U5      nUR                  U R                  :w  aK  T" X1U5      u  pQnT" XU5      u  pan[	        [
        R                  U UR                  UR                  5      UU4$ SX4$ )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   r0  r(  rm   rg   rk   rr   rs   )	r\  rL  rM  r{   rW  remove_change
add_changer]  rY  s	          r:   
modify_doc+Watch._compute_snapshot.<locals>.modify_doc  s      ))88D&K(KK&&??40L''<+C+CC;E<8[ 9@ 95
+ #"++$%//",,	 !	 	 22r=   rA  zwalk over add_changeszin add_changeszQThe update document tree and document map should have the same number of entries.)rZ   rD  rE  r   rF  rR  r   r   )r9   r   r   delete_changesadd_changesupdate_changesrL  rM  rb  rN  rI   r{   changerz   r]  rY  s                 @@r:   rC  Watch._compute_snapshotT  s_     8}G, 	
#	
,
	$	 	3B ""4#3#34  /"D0:K1-F+ !!&)	 # [2-.#HMM*+071-F+ !!&) $  8&H0:1-F+ !%%f- ' < C$44 	
6	
4 >::r=   c                     U R                  U R                  U R                  S5      u  pn[        U R                  5      [        U5      -   [        U5      -
  $ )zcReturn the current count of all documents.

Count includes the changes from the current changeMap.
N)rB  r   r   rZ   )r9   rI  rJ  r   s       r:   r6  Watch._current_size  sG    
  00tPTUq4<< 3t9,s7|;;r=   c                 &   [         R                  S5        U R                  R                  5         SU l        U R
                  R                  5        H6  nUR                  R                  n[        R                  U R                  U'   M8     SU l        g)z7
Helper to clear the docs on RESET or filter mismatch.
zresetting documentsNF)r   r   r   rG  r   r   rA   r$  r   rg   rj   r   )r9   rz   r{   s      r:   r  Watch._reset_docs  sp     	+,  **,H%%44D$.$6$6DOOD! - r=   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r?   )%r`   ra   rb   rc   r;   r   classmethodr   r   r   r   propertyr   r   r   r   r  r
  r  r  r  TargetChangeType	NO_CHANGEADDREMOVERESETCURRENTr/  r  r   r  staticmethodrB  rC  r6  r  rd   re   r=   r:   r   r      s    <|" 
 
< 
 

; G G!'F&KU
 

 	""$H<!B @  "D#
o3b.: ( ((o;b<r=   r   )/collectionsrD  loggingr   enumr   r   google.api_corer   google.api_core.bidir   r   google.cloud.firestore_v1r   )google.cloud.firestore_v1.types.firestorer   r	   r
   ro  	getLoggerr`   r   r   GRPC_STATUS_CODEr   Aborted	CancelledUnknownDeadlineExceededResourceExhaustedInternalServerErrorServiceUnavailableUnauthenticatedr   r   
namedtupler.   objectr2   rg   rm   rw   r   r   r   r   r   re   r=   r:   <module>r     s         & E .   00 


H
%! q 	
   a  r ! 1 r B R   2!" #$ "% ( 2   ""!!	"  #-"6"6!8 %%nw6HI(6 (V #V #"'& '
?
?
rF rr=   