
    i}                     <   d Z ddlmZmZ ddlmZ ddlZddl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mZ ddlmZ ddgZ G d de          Z e            xZZ G d de          Z G d de          ZddZeefZ e!fZ"dZ# G d de          Z$dS )z0
Basic loop implementation for ffi-based cores.
    )absolute_importprint_function)dequeN)_dbg)GEVENT_DEBUG_LEVEL)TRACEcallback)PYPY)HubDestroyed)getswitchintervalAbstractLoopassign_standard_callbacksc                       e Zd Zd ZdS )_EVENTSTypec                     dS )Nzgevent.core.EVENTS selfs    ;/usr/local/lib/python3.11/dist-packages/gevent/_ffi/loop.py__repr__z_EVENTSType.__repr__   s    ##    N)__name__
__module____qualname__r   r   r   r   r   r      s#        $ $ $ $ $r   r   c                       e Zd ZdZd ZdS )_DiscardedSetr   c                     dS )zDoes nothing.Nr   )r   os     r   discardz_DiscardedSet.discard%   s      r   N)r   r   r   	__slots__r    r   r   r   r   r   "   s(        I    r   r   c                   \    e Zd Zd Zd Zd Zd Zd Zd Ze	sd Z
nd Z
d	 Zd
 Zd Zd ZdS )AbstractCallbacksc                 ^    || _         g | _        t          t          k     r|j        | _        d S d S N)ffi	callbacksr   r   from_handle)r   r&   s     r   __init__zAbstractCallbacks.__init__M   s3    %%"D &%r   c                 :    | j                             |          }|S r%   )r&   r(   )r   handlexs      r   r(   zAbstractCallbacks.from_handleS   s    H  ((r   c                    d}d}	 |st          d           dS |                     |          }|j        }|j        }|j        }|t
          }|r|d         t          k    r|f|dd         z   } |j        |  n#  	 | n%# t          $ r |                     |          }Y nw xY wt          j
                    |_        |j        |j        `d}|j        }|`	 | |j        |g|R   n
 | j        |  n5#  t          dt          j                   t#          j                     Y nxY wY dS |j        j                            |           Y dS xY w|j        ||j        j        v r|j        |u rdS dS )	a  
        Returns an integer having one of three values:

        - -1
          An exception occurred during the callback and you must call
          :func:`_python_handle_error` to deal with it. The Python watcher
          object will have the exception tuple saved in ``_exc_info``.
        - 1
          Everything went according to plan. You should check to see if the native
          watcher is still active, and call :func:`python_stop` if it is not. This will
          clean up the memory. Finding the watcher still active at the event loop level,
          but not having stopped itself at the gevent level is a buggy scenario and
          shouldn't happen.
        - 2
          Everything went according to plan, but the watcher has already
          been stopped. Its memory may no longer be valid.

        This function should never return 0, as that's the default value that
        Python exceptions will produce.
        Nzpython_callback got null handle   r   z*WARNING: gevent: Error when handling errorfile   )r   r(   _watcherloopargs_NOARGSGEVENT_CORE_EVENTSr
   UnboundLocalErrorsysexc_info	_exc_info_handlehandle_errorunhandled_onerrorprintstderr	traceback	print_exc_keepalivesetadd)r   r+   reventsorig_ffi_watcher	orig_loopthe_watcherr5   r:   s           r   python_callbackz!AbstractCallbacks.python_callbackW   s   ,  	E	   6777q**622K*3#(I#D|  .Q#555{T!""X- K $'''-	7$ 7 7 7"..v667 %(LNNK!  $,"*2 &0)* ,.	.{FXFFFFF..99*F"z+ + + +')))))qq *..{;;;22(;#3#AAA(,<<< 1qsS   A8 AA8 8E;A>=E>B EB  4EC10E10D#!E)Ec                    t          d|           |sd S 	 	 |                     |          }|j        }|` |j        j        d g|R   	 |                                 np#   |j        j        |gt          j                    R   Y nHxY w# 	 |                                 w #   |j        j        |gt          j                    R   Y w xY wxY wn#  Y nxY wd S )NzHandling error for handle)r   r(   r;   r4   r=   stopr9   r:   )r   r+   _reventswatcherr:   s        r   python_handle_errorz%AbstractCallbacks.python_handle_error   s   (&111 	F 	
H**622",% *)$:::::HLLNNNNH-GL-gGGGGGGGHLLNNNNH-GL-gGGGGGGG	DsG   1B	 	A C &BC 	CB C &CCC Cc                 "   d }||j         j                            d          nd }|r|                     |          }||j                            d |||           dS t          dt          j                   t          j
        |||           d S )Nr+   r.   z0WARNING: gevent: Unhandled error with no watcherr/   )tb_framef_localsgetr(   r4   r=   r?   r9   r@   rA   print_exception)r   tvtbrM   r+   s         r   r>   z#AbstractCallbacks.unhandled_onerror   s     79~%))(3334 	/&&v..GL%%dAq"5551 	@:	 	 	 	!!Q+++++r   c                     |st          dt          j                   d S |                     |          }|                                 d S )NzWARNING: gevent: Unable to dereference handle; not stopping watcher. Native resources may leak. This is most likely a bug in gevent.r/   )r?   r9   r@   r(   rK   )r   r+   rM   s      r   python_stopzAbstractCallbacks.python_stop  sW     		RZ! ! ! ! F""6**r   c                     d S r%   r   r   watcher_ptrs     r   python_check_callbackz'AbstractCallbacks.python_check_callback  s	     Dr   c                 B    	 t                      # t           $ r Y d S w xY wr%   )MemoryErrorrZ   s     r   r\   z'AbstractCallbacks.python_check_callback(  s3    !mm#   s    
c                     |                      |          }|t          d|           d S |                                 d S )NzDWARNING: gevent: running prepare callbacks from a destroyed handle: )_find_loop_from_c_watcherr?   _run_callbacks)r   r[   r4   s      r   python_prepare_callbackz)AbstractCallbacks.python_prepare_callback1  sO    --k::<X  Fr   c                     d }|                      |          }|r|                     |          }||                    d |||           d S |r%   )_find_watcher_ptr_in_tracebackr`   r=   )r   rT   rU   rV   r4   r[   s         r   check_callback_onerrorz(AbstractCallbacks.check_callback_onerror9  sa    99"== 	?11+>>D dAq"---4r   c                     t                      r%   NotImplementedErrorrZ   s     r   r`   z+AbstractCallbacks._find_loop_from_c_watcherE      !###r   c                 .    ||j         j        d         nd S )Nr[   )rP   rQ   )r   rV   s     r   rd   z0AbstractCallbacks._find_watcher_ptr_in_tracebackH  s    68nr{#M22$Nr   N)r   r   r   r)   r(   rI   rN   r>   rX   r   r\   rb   re   r`   rd   r   r   r   r#   r#   J   s        / / /  k k kZ' ' 'R, , ,6    	 	 	 	"	 	 	  
 
 
$ $ $O O O O Or   r#   r   c                 j    ||           d |D             }t          fd|D                       }j        dfj        dfj        dfj        j        fj        j        ff|z   D ]G\  }}|pj        } |                     |          |          }j	        
                    |           HS )a4  
    Given the typical *ffi* and *lib* arguments, and a subclass of :class:`AbstractCallbacks`
    in *callbacks_class*, set up the ``def_extern`` Python callbacks from C
    into an instance of *callbacks_class*.

    :param tuple extras: If given, this is a sequence of ``(name, error_function)``
      additional callbacks to register. Each *name* is an attribute of
      the *callbacks_class* instance. (Each element cas also be just a *name*.)
    :return: The *callbacks_class* instance. This object must be kept alive,
      typically at module scope.
    c                 @    g | ]}t          |          d k    r|n|dfS )r1   N)len).0extras     r   
<listcomp>z-assign_standard_callbacks.<locals>.<listcomp>Z  s.    NNNes5zzQeeUDMNNNr   c              3   B   K   | ]\  }}t          |          |fV  d S r%   )getattr)rn   nameerrorr'   s      r   	<genexpr>z,assign_standard_callbacks.<locals>.<genexpr>[  s6      OOuGIt,,e4OOOOOOr   N)onerror)tuplerI   rN   rX   r\   re   rb   r>   
def_externr'   append)r&   libcallbacks_classextrasfunc
error_funcr
   r'   s          @r   r   r   L  s      $$INNvNNNFOOOOOOOOOF&-*D1"D),i.NO.	0PQ 	 - -z  >9#>
53>>*>55d;;
 	""8,,,,
 r   c                      e Zd ZdZdZdZdZdZdZdZ	dZ
 e            ZdZdBdZdBdZd Zd Zd Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zed             Zed             Zed             Zed             Z d Z!d Z"d Z#dCdZ$d Z%d Z&d Z'dDdZ(d Z)d Z*d  Z+d! Z,d" Z-ed#             Z.ed$             Z/ed%             Z0ed&             Z1ed'             Z2ed(             Z3dEd*Z4d+ Z5dFd-Z6dEd.Z7dEd/Z8dEd0Z9dEd1Z:dEd2Z;dEd3Z<e< e=            d4<   e>j?        d5k    rdGd7Z@d8 ZAdFd9ZBdDd:ZCd; ZDd< ZEd= ZFd> ZGd? ZHd@ ZIedA             ZJdS )Hr   2   NFc                    || _         || _        d | _        | j                             |           | _        || _        d| _        t                      | _        t                      | _
        |                     ||           d S NF)_ffi_lib_ptr
new_handle_handle_to_self	_watchers_in_callbackr   
_callbackssetrC   _init_loop_and_aux_watchers)r   r&   rz   watchersflagsdefaults         r   r)   zAbstractLoop.__init__  sq    			#y33D99!!'' UU((88888r   c                 ^   |                      ||          | _        | j                            | j                  | _        | j        | j        _        |                                  | j                            | j	                  | _
        | j        | j
        _        |                                  | j                            | j                  | _        | j        | j        _        |                                  |                     d          | _        | j                            d            d S )NF)refc                      d S r%   r   r   r   r   <lambda>z:AbstractLoop._init_loop_and_aux_watchers.<locals>.<lambda>  s    T r   )
_init_loopr   r   new_CHECK_POINTER_checkr   data_init_and_start_check_PREPARE_POINTER_prepare_init_and_start_prepare_TIMER_POINTER_timer0_init_callback_timerasync__threadsafe_asyncstartr   r   r   s      r   r   z(AbstractLoop._init_loop_and_aux_watchers  s    OOE733	 immD$788/""$$$ 	d&;<<!1$$&&& y}}T%899 0!!###!%!7!7 	$$\\22222r   c                     t                      )zs
        Called by __init__ to create or find the loop. The return value
        is assigned to self._ptr.
        rg   r   s      r   r   zAbstractLoop._init_loop  s    
 "###r   c                     t                      r%   rg   r   s    r   r   z"AbstractLoop._init_and_start_check  ri   r   c                     t                      r%   rg   r   s    r   r   z$AbstractLoop._init_and_start_prepare  ri   r   c                     t                      r%   rg   r   s    r   r   z!AbstractLoop._init_callback_timer  ri   r   c                     t                      r%   rg   r   s    r   _stop_callback_timerz!AbstractLoop._stop_callback_timer  ri   r   c                     t                      r%   rg   r   s    r   _start_callback_timerz"AbstractLoop._start_callback_timer  ri   r   c                 6    |                      d |||           d S r%   )r=   )r   rT   rU   rV   s       r   _check_callback_handle_errorz)AbstractLoop._check_callback_handle_error  s"    $1b)))))r   c                 f   d| _         	 | j        }|                                 }|t                      z   }|                                  | j        r| j                                        }|dz  }|                                  |j        }d |_        |j	        }||T	  ||  nf#  	  | j
        |gt          j                    R   n>#  	 t          dt          j                   t          j                     n#  Y nxY wY nxY wY nxY wd |_	        n# d |_	        w xY w|dk    r=| j        r6| j        }|                                  |                                 |k    rd}n| j        |dk    r|                                  | j        r|                                  d| _         d S # d| _         w xY w)NTr.   z&Exception while handling another errorr/   r   F)#starting_timer_may_update_loop_timeCALLBACK_CHECK_COUNTnowr   r   r   popleftunrefr
   r5   r=   r9   r:   r?   r@   rA   rB   
update_nowr   )r   countr   
expirationcbr
   r5   s          r   ra   zAbstractLoop._run_callbacks  s    480B	=-E((**C0222J%%'''/ 3_,,..


;"w#t|#HdOOO! !))">s|~~>>>>>!!!"JQTQ[\\\\%/1111! D
 #BGGdBGNNNN
 A::$/: 5EOO%%%xxzzZ//g / 3n axx!!! -**,,,7<D444uD4<<<<sg   BF' B$ #D $D'CDD
.C98D9C=;D DD 
F' 	DBF' '	F0c                 X    | j         "| j                                          d | _         d S d S r%   )r   closer   s    r   _stop_aux_watcherszAbstractLoop._stop_aux_watchers.  s6    !-"((***%)D""" .-r   c                     | j         }|rq	 |                     |          s	 d | _        | `| `| `dS |                                  |                     |           d | _        | `| `| `n# d | _        | `| `| `w xY wdS d S )NFT)ptr_can_destroy_loopr   r   r   rC   r   _destroy_loopr   r   s     r   destroyzAbstractLoop.destroy3  s    h 	'--c22 !  !	(O&&& '')))""3'''
 !	(O&& !	(O&&&&&4	 	s   A' )A' 'A6c                     t                      r%   rg   r   s     r   r   zAbstractLoop._can_destroy_loopF  ri   r   c                     t                      r%   rg   r   s     r   r   zAbstractLoop._destroy_loopI  ri   r   c                     | j         S r%   )r   r   s    r   r   zAbstractLoop.ptrL  s     yr   c                     | j         j        S r%   )r   rM   r   s    r   WatcherTypezAbstractLoop.WatcherTypeQ  s    ~%%r   c                     dS Nr.   r   r   s    r   MAXPRIzAbstractLoop.MAXPRIU      qr   c                     dS r   r   r   s    r   MINPRIzAbstractLoop.MINPRIY  r   r   c                     	 t          j        |          }n#  t          j                     Y nxY w	 |d|}n#  t          j                     Y nxY w|                     d t
          t          |          d            d S )Nz: )osstrerrorrA   rB   r=   SystemError)r   messageerrnos      r   _handle_syserrzAbstractLoop._handle_syserr]  s    	"K&&EE	"!!!!!	"")''551GG	"!!!!!$[-A-A4HHHHHs    .: Ac                     |t           u r/| j                                         |                                  d S d }| j        }|!t          |d|          } |||||           d S |                     ||||           d S )Nr=   )r   r   clearbreak_error_handlerrr   _default_handle_error)r   contexttypevaluerV   r=   r   s          r   r=   zAbstractLoop.handle_errorh  s    <O!!###KKMMMF*$"=.-PPLL$r22222&&weR@@@@@r   c                 2    t          j        |||           d S r%   )rA   rS   )r   r   r   r   rV   s        r   r   z"AbstractLoop._default_handle_errorw  s     	!$r22222r   c                     t                      r%   rg   )r   nowaitonces      r   runzAbstractLoop.run~  ri   r   c                     t                      r%   rg   r   s    r   reinitzAbstractLoop.reinit  ri   r   c                     t                      r%   rg   r   s    r   r   zAbstractLoop.ref  s    !###r   c                     t                      r%   rg   r   s    r   r   zAbstractLoop.unref  ri   r   c                     t                      r%   rg   )r   hows     r   r   zAbstractLoop.break_  ri   r   c                     d S r%   r   r   s    r   verifyzAbstractLoop.verify  s    r   c                     t                      r%   rg   r   s    r   r   zAbstractLoop.now  ri   r   c                     t                      r%   rg   r   s    r   r   zAbstractLoop.update_now  ri   r   c                 p    dd l }|                    dt          d           |                                  d S )Nr   z('update' is deprecated; use 'update_now'r1   )
stacklevel)warningswarnDeprecationWarningr   )r   r   s     r   updatezAbstractLoop.update  sG    @(!" 	 	$ 	$ 	$ 	r   c                 z    d| j         j        | j         j        t          |           |                                 fz  S )Nz<%s.%s at 0x%x %s>)	__class__r   r   id_formatr   s    r   r   zAbstractLoop.__repr__  s8    #N%N#tHHLLNN	'
 
 	
r   c                 "    | j         r| j        ndS r   )r   _defaultr   s    r   r   zAbstractLoop.default  s     $3t}}e3r   c                     dS Nr2   r   r   s    r   	iterationzAbstractLoop.iteration      rr   c                     dS r   r   r   s    r   depthzAbstractLoop.depth  r   r   c                     dS Nr   r   r   s    r   backend_intzAbstractLoop.backend_int  r   r   c                     dS )Nr   r   r   s    r   backendzAbstractLoop.backend  s    yr   c                     dS r   r   r   s    r   
pendingcntzAbstractLoop.pendingcnt  r   r   Tc                 >    | j                             | ||||          S r%   )r   io)r   fdeventsr   prioritys        r   r  zAbstractLoop.io  s     ~  r63AAAr   c                     dS r   r   )r   r  s     r   
closing_fdzAbstractLoop.closing_fd  s    ur           c                 >    | j                             | ||||          S r%   )r   timer)r   afterrepeatr   r  s        r   r  zAbstractLoop.timer  s     ~##D%hGGGr   c                 <    | j                             | |||          S r%   )r   signal)r   signumr   r  s       r   r  zAbstractLoop.signal  s    ~$$T63AAAr   c                 :    | j                             | ||          S r%   )r   idler   r   r  s      r   r  zAbstractLoop.idle      ~""4h777r   c                 :    | j                             | ||          S r%   )r   preparer  s      r   r  zAbstractLoop.prepare  s    ~%%dC:::r   c                 :    | j                             | ||          S r%   )r   checkr  s      r   r  zAbstractLoop.check  s    ~##D#x888r   c                 :    | j                             | ||          S r%   )r   forkr  s      r   r  zAbstractLoop.fork  r  r   c                 :    | j                             | ||          S r%   )r   r   r  s      r   r   zAbstractLoop.async_  s    ~$$T3999r   asyncwin32r   c                 <    | j                             | |||          S r%   )r   child)r   pidtracer   s       r   r   zAbstractLoop.child  s    >''c5#>>>r   c                     d S r%   r   r   s    r   install_sigchldzAbstractLoop.install_sigchld  s    Dr   c                 >    | j                             | ||||          S r%   )r   stat)r   pathintervalr   r  s        r   r&  zAbstractLoop.stat  s     ~""4xhGGGr   c                 "    t          | |          S r%   r	   )r   r  s     r   r
   zAbstractLoop.callback  s    h'''r   c                     t                      r%   rg   r   s    r   _setup_for_run_callbackz$AbstractLoop._setup_for_run_callback  ri   r   c                     t          ||          }| j                            |           |                                  |S r%   )r
   r   ry   r+  r   r}   r5   r   s       r   run_callbackzAbstractLoop.run_callback  s@     dD!!r"""$$&&&	r   c                 T     | j         |g|R  }| j                                         |S r%   )r.  r   sendr-  s       r   run_callback_threadsafez$AbstractLoop.run_callback_threadsafe  s6    Tt+d+++##%%%	r   c                     | j         }|sdS d| j        z   }|dt          |          z   z  }| j        r|dz  }|d| j        z  z  }||                                 z  }|S )N	destroyedzbackend=z ptr=z defaultz pending=%s)r   r   strr   r  _format_details)r   r   msgs      r   r   zAbstractLoop._format  sw    h 	;4<'wS!!< 	:C}t..t##%%%
r   c                    d}|                                  }	 | j        }n# t          $ r d }Y nw xY w||dt          |          z   z  }||dt          |          z   z  }|dt	          t          | j                            z   z  }|S )N z ref=z fileno=z callbacks=)fileno	activecntAttributeErrorreprr4  rm   r   )r   r6  r9  r:  s       r   r5  zAbstractLoop._format_details  s    	II 	 	 	III	 7T)__,,C:V,,C 	}s3t#7#78888
s     //c                     d S r%   r   r   s    r   r9  zAbstractLoop.fileno  s    tr   c                 2    | j         st          d          dS )Nzoperation on destroyed loopr   )r   
ValueErrorr   s    r   r:  zAbstractLoop.activecnt  s     x 	<:;;;qr   )NN)FFr%   )TN)r
  TN)r   T)Kr   r   r   r   r   r   r   _TIMER_CALLBACK_SIGr   r   r   r   rC   r   r)   r   r   r   r   r   r   r   r   ra   r   r   r   r   propertyr   r   r   r   r   r=   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r	  r  r  r  r  r  r  r   localsr9   platformr   r$  r&  r
   r+  r.  r1  r   r5  r9  r:  r   r   r   r   r   z  s       
 MNN*/' H!MOOM
9 
9 
9 
9!3 !3 !3 !3L$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $* * *N= N= N=`* * *
  &$ $ $$ $ $   X & & X&   X   X	I 	I 	IA A A3 3 3$ $ $ $$ $ $$ $ $$ $ $$ $ $ $  $ $ $$ $ $  
 
 
 4 4 X4   X   X   X   X   XB B B B  H H H HB B B B8 8 8 8; ; ; ;9 9 9 98 8 8 8: : : : FFHHW
|w	? 	? 	? 	?	 	 	H H H H( ( ( ($ $ $    

 
 
        X  r   )r   )%__doc__
__future__r   r   collectionsr   r9   r   rA   gevent._ffir   r   r   gevent._ffi.callbackr
   gevent._compatr   gevent.exceptionsr   geventr   __all__objectr   EVENTSr7   	frozensetr   r#   r   bytesr4  
basestringintinteger_typesr6   r   r   r   r   <module>rT     s    7 6 6 6 6 6 6 6       



 				           * * * * * *       ) ) ) ) ) )       * * * * * * $ $ $ $ $ $ $ $ $ $ $& $ $ $ *kmm +	    I   PO O O O O O O OD# # # #N S\
 d d d d d6 d d d d dr   