o
    0׾gW                     @   s<  d Z ddlmZmZm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 ddlmZ ddlmZ ddlmZ g d	ZerBd
ndZdd Zdd ZG dd deZddedfddZddedfddZdd Zdd Zdd ZeZdd ZG dd deZG d d! d!eZG d"d# d#e Z!G d$d% d%eZ"d&d' Z#dS )(z
Low-level utilities.
    )absolute_importprint_functiondivisionN)
getcurrent)perf_counter)PYPY)thread_mod_name)_NONE)format_run_infoprint_run_infoGreenletTreewrap_errorsassert_switches   c                   C      d S N r   r   r   U/var/www/html/backend_erp/backend_erp_env/lib/python3.10/site-packages/gevent/util.py_noop!      r   c                   C   s   dS NFr   r   r   r   r   _ready$   r   r   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )r   a  
    Helper to make function return an exception, rather than raise it.

    Because every exception that is unhandled by greenlet will be logged,
    it is desirable to prevent non-error exceptions from leaving a greenlet.
    This can done with a simple ``try/except`` construct::

        def wrapped_func(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except (TypeError, ValueError, AttributeError) as ex:
                return ex

    This class provides a shortcut to write that in one line::

        wrapped_func = wrap_errors((TypeError, ValueError, AttributeError), func)

    It also preserves ``__str__`` and ``__repr__`` of the original function.
    c                 C   s   || _ || _t| | dS )z
        Calling this makes a new function from *func*, such that it catches *errors* (an
        :exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and
        return it as a value.
        N)_wrap_errors__errors_wrap_errors__func	functoolsupdate_wrapper)selferrorsfuncr   r   r   __init__=   s   zwrap_errors.__init__c              
   O   sB   | j }z||i |W S  | jy  } z|W  Y d }~S d }~ww r   )r   r   )r   argskwargsr   exr   r   r   __call__H   s   zwrap_errors.__call__c                 C   
   t | jS r   )strr   r   r   r   r   __str__O      
zwrap_errors.__str__c                 C   r$   r   )reprr   r&   r   r   r   __repr__R   r(   zwrap_errors.__repr__c                 C      t | j|S r   )getattrr   r   namer   r   r   __getattr__U      zwrap_errors.__getattr__N)	__name__
__module____qualname____doc__r   r#   r'   r*   r/   r   r   r   r   r   '   s    r   Tc                 C   s:   t | ||d}|du rtjn|}|D ]}t||d qdS )z
    Call `format_run_info` and print the results to *file*.

    If *file* is not given, `sys.stderr` will be used.

    .. versionadded:: 1.3b1
    )thread_stacksgreenlet_stackslimitN)file)r
   sysstderrprint)r5   r6   r7   r8   lineslr   r   r   r   Y   s   r   c                 C   sT   |du rddl m} |td }g }|tu rtn|}t|| || t||| |S )a  
    format_run_info(thread_stacks=True, greenlet_stacks=True, limit=None) -> [str]

    Request information about the running threads of the current process.

    This is a debugging utility. Its output has no guarantees other than being
    intended for human consumption.

    :keyword bool thread_stacks: If true, then include the stacks for
       running threads.
    :keyword bool greenlet_stacks: If true, then include the stacks for
       running greenlets. (Spawning stacks will always be printed.)
       Setting this to False can reduce the output volume considerably
       without reducing the overall information if *thread_stacks* is true
       and you can associate a greenlet to a thread (using ``thread_ident``
       printed values).
    :keyword int limit: If given, passed directly to `traceback.format_stack`.
       If not given, this defaults to the whole stack under CPython, and a
       smaller stack under PyPy.

    :return: A sequence of text lines detailing the stacks of running
            threads and greenlets. (One greenlet will duplicate one thread,
            the current thread and greenlet. If there are multiple running threads,
            the stack for the current greenlet may be incorrectly duplicated in multiple
            greenlets.)
            Extra information about
            :class:`gevent.Greenlet` object will also be returned.

    .. versionadded:: 1.3a1
    .. versionchanged:: 1.3a2
       Renamed from ``dump_stacks`` to reflect the fact that this
       prints additional information about greenlets, including their
       spawning stack, parent, locals, and any spawn tree locals.
    .. versionchanged:: 1.3b1
       Added the *thread_stacks*, *greenlet_stacks*, and *limit* params.
    Nr   )monkey	get_ident)geventr>   get_originalr   r	   _STACK_LIMIT_format_thread_info_format_greenlet_info)r5   r6   r7   current_thread_identr>   r<   r   r   r   r
   i   s   (r
   c                 C   s   | j o| j dS )Ngevent_threadpool_worker_idle)f_localsgetframer   r   r   is_idle_threadpool_worker   s   rK   c              	   C   s   dd l }dd | D }| d | d d }d }t  D ]T\}}|}	| d ||}d }
|s>t|r=d}
d}	n|j}
t	|dd rMt
| }
||krVd	|
f }
| d
||
f  |	rn| dt|| q!|su| d q!~~~ ~d S )Nr   c                 S   s   i | ]}|j |qS r   )ident).0thr   r   r   
<dictcomp>       z'_format_thread_info.<locals>.<dictcomp>P********************************************************************************z	* Threadszidle threadpool workerFgevent_monitoring_threadz%s) (CURRENTzThread 0x%x (%s)
 z	...stack elided...)	threading	enumerateappendr9   _current_framesitemsrH   rK   r.   r,   r)   rR   join	tracebackformat_stack)r<   r5   r7   rE   rT   threadsthreadrJ   thread_ident	do_stacksr.   r   r   r   rC      s>   





rC   c                 C   sj   |  d |  d |  d tt dd dD ]}|  d | |j|jr)|nd|dd	 q~ d S )
NrQ   z* Greenletsc                 S   s   | j rdS t| jS NrS   )is_current_treer)   greenlet)tr   r   r   <lambda>   rP   z'_format_greenlet_info.<locals>.<lambda>keyz---- Thread boundaryF)running_stacksrunning_stack_limit)details)rV   sortedr   forestextendformat_linesra   )r<   r6   r7   treer   r   r   rD      s   




rD   c                    s   t   fdd}|S )Nc                    s&    | g|R i |}| j | d S r   )r<   rV   )r   r    r!   rfr   r   w   s   z_line.<locals>.w)r   wraps)rq   rr   r   rp   r   _line   s   rt   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
ddd	Zd
d Zedd ZeefddZdd ZeefddZdd ZeefddZdd Zdd ZdS )_TreeFormatter+-|:      r   c                 C   s(   g | _ || _|| _|sdd | _d S d S )Nc                  _   r   r   r   )r    r!   r   r   r   rd      s    z)_TreeFormatter.__init__.<locals>.<lambda>)r<   depthri   
child_data)r   ri   r|   r   r   r   r      s   z_TreeFormatter.__init__c                 C   s   t | | j| jd S )Nrz   )typeri   r|   r&   r   r   r   deeper   s   z_TreeFormatter.deeperc                 C   s   |S r   r   )r   textr   r   r   
node_label   s   z_TreeFormatter.node_labelc                 C   s(   d| j  | | j| j  d| j  | S N )indent
HORIZONTALhoriz_widthlabel_space)r   labelrightr   r   r   
child_head   s   
z_TreeFormatter.child_headc                 C   s   |  || jS r   )r   UP_AND_RIGHT)r   r   r   r   r   last_child_head  s   z_TreeFormatter.last_child_headc                 C   s   d| j  | d| j  | S r   )r   r   )r   lineverticalr   r   r   
child_tail  s   z_TreeFormatter.child_tailc                 C   s   | j |dt| j dS )Nr   )r   )r   lenVERTICAL)r   r   r   r   r   last_child_tail  s   z_TreeFormatter.last_child_tailc                 C   s2   d| j  | js	|nd d| j  d| j  | fS r   )r   r|   r   r   )r   datadata_markerr   r   r   r}     s   z_TreeFormatter.child_datac                 C   s   |  |dS r   )r}   )r   r   r   r   r   last_child_data!  r0   z_TreeFormatter.last_child_datac                 C   s   |  D ]}| | qd S r   )
splitlinesr}   )r   r   r=   r   r   r   child_multidata$  s   z_TreeFormatter.child_multidataNr   )r1   r2   r3   r   r   r   VERTICAL_AND_RIGHTDATAr   r   r   r   r   rt   r   r   r   r   r   r}   r   r   r   r   r   r   ru      s.    

		ru   c                   @   s   e Zd ZdZdZdZdd Zdd Zedd	 Z	d
d Z
dedddZd&ddZd&ddZdd ZdZedd Zedd Zdd Zdd Zdd Zedd Zed d! Zed"d# Zed$d% ZdS )'r   a  
    Represents a tree of greenlets.

    In gevent, the *parent* of a greenlet is usually the hub, so this
    tree is primarily arganized along the *spawning_greenlet* dimension.

    This object has a small str form showing this hierarchy. The `format`
    method can output more details. The exact output is unspecified but is
    intended to be human readable.

    Use the `forest` method to get the root greenlet trees for
    all threads, and the `current_tree` to get the root greenlet tree for
    the current thread.
    NFc                 C   s   || _ g | _d S r   )rb   child_trees)r   rb   r   r   r   r   @     
zGreenletTree.__init__c                 C   s   || u rd S | j | d S r   )r   rV   )r   rn   r   r   r   	add_childD  s   zGreenletTree.add_childc                 C   s   | j jd u S r   )rb   parentr&   r   r   r   rootI  s   zGreenletTree.rootc                 C   r+   r   )r,   rb   r-   r   r   r   r/   M  r0   zGreenletTree.__getattr__T)rg   rh   spawning_stackslocalsc                 C   s\   t |ts|s
i }n| j }n|}| j }|| t|dd}dd | |D }|S )z
        Return a sequence of lines for the greenlet tree.

        :keyword bool details: If true (the default),
            then include more informative details in the output.
        r   )r|   c                 S   s"   g | ]}t |tr|d  n|qS r   )
isinstancetuple)rM   r=   r   r   r   
<listcomp>h  s    z-GreenletTree.format_lines.<locals>.<listcomp>)r   dictDEFAULT_DETAILScopyupdateru   _render)r   ri   paramsrn   r<   r   r   r   rm   W  s   


zGreenletTree.format_linesc                 C   s   |  |}d|S )z;
        Like `format_lines` but returns a string.
        
)rm   rY   )r   ri   r<   r   r   r   formatl  s   

zGreenletTree.formatc                 C   s
   |  dS r   )r   r&   r   r   r   r'   s  r(   zGreenletTree.__str__c                 C   s6   | | | jrdt||}nd}|| d S r`   )r}   _SUPPORTS_TRACEBACKrY   rZ   r[   r   )clsrn   r   rJ   r7   tbr   r   r   __render_tb~  s
   
zGreenletTree.__render_tbc                 C   s   t | dd pt S )Nspawning_greenlet)r,   r   rb   r   r   r   __spawning_parent  s   zGreenletTree.__spawning_parentc                 C   sn   ddl m} || j}|r3|d |D ] \\}}}|sq|d|t|f  |dt|  qd S d S )Nr   )all_local_dicts_for_greenletzGreenlet Locals:z  Local %s at %sz    )gevent.localr   rb   r}   hexr   pprintpformat)r   rn   r   	gr_localskindidlvalsr   r   r   __render_locals  s   

zGreenletTree.__render_localsc                 C   s  t | j}| jsAt| jdt r=|d7 }| jjd ur)|dt | jjd d  7 }nt| jdd d ur<|dt | jj 7 }n|d7 }|| |dt | jj  t| jd	d d urf|d
t | j	   | jr~|j
r~|j
d r~| |d| jj|j
d  t| jdd }|r|j
r|j
d r| |d|d  | | j}t| jdd }|r|t|dd ur|d |t| | | z	| | W |jS  ty   tdgt R   Y |jS w )Nreadyz
; finishedz with value    	exceptionz with exception z; not runningzParent: rR   zMonitoring Thread:rg   zRunning:rh   spawning_stackr   zSpawned at:spawn_tree_localszSpawn Tree LocalszWhen rendering children)r)   rb   r,   r   valuer   r   r}   r   rR   ri   _GreenletTree__render_tbgr_frame_GreenletTree__spawning_parentr   r   r   _GreenletTree__render_locals_GreenletTree__render_childrenRuntimeErrorr;   r9   exc_infor<   )r   rn   r   r   spawning_parenttree_localsr   r   r   r     sD   



zGreenletTree._renderc           
      C   s   t | jdd d}t|D ]A\}}|| }|j}|j}|j}|t|d kr2|j	}|j
}|j}||d |D ]}	t|	trI||	d  q;||	 q;q|jS )Nc                 S   s"   t | ddt | dt t| jfS )Nminimal_identr   )r,   r   idr   )cr   r   r   rd     s   
z0GreenletTree.__render_children.<locals>.<lambda>re   rz   r   )rj   r   rU   r   r   r   r   r}   r   r   r   r   popr   r   r<   )
r   rn   childrennchild
child_treeheadtailr   r}   r   r   r   __render_children  s&   	

zGreenletTree.__render_childrenc                 C   s6   | j d urt| dds| j } | j d urt| ddr| S )Ngreenlet_tree_is_rootF)r   r,   r   r   r   r   _root_greenlet  s   zGreenletTree._root_greenletc              	   C   s  ddl m} | t }i }i }| | } ||< ||< d|_| j}| }|D ]^}| |}	|	d u r6||}	|	||	u rP|	|vrP|	|vsFJ | |	 ||	< ||	< z||	 }
W n tyg   | |	 }
||	< Y nw z|| }W n ty   | | ||< }Y nw |
| q'||fS )Nr   )get_reachable_greenletsT)gevent._greenlet_primitivesr   r   r   ra   r   KeyErrorr   )r   r   main_greenlettreesrootscurrent_treeroot_greenletgletsobspawn_parentparent_treer   r   r   r   _forest  s6   
zGreenletTree._forestc                 C   s   t |  d  S )z
        forest() -> sequence

        Return a sequence of `GreenletTree`, one for each running
        native thread.
        r   )listr   valuesr   r   r   r   rk     s   	zGreenletTree.forestc                 C   s   |   d S )zl
        current_tree() -> GreenletTree

        Returns the `GreenletTree` for the current thread.
        rz   )r   r   r   r   r   r   #  s   zGreenletTree.current_tree)T)r1   r2   r3   r4   rb   ra   r   r   propertyr   r/   rB   r   rm   r   r'   r   classmethodr   staticmethodr   r   r   r   r   r   rk   r   r   r   r   r   r   *  sB    


	
	
.!

)

r   c                   @   s   e Zd ZdS )_FailedToSwitchN)r1   r2   r3   r   r   r   r   r   ,  s    r   c                   @   s6   e Zd ZdZdZdZdZd
ddZdd Zdd	 Z	dS )r   a|  
    A context manager for ensuring a block of code switches greenlets.

    This performs a similar function as the :doc:`monitoring thread
    </monitoring>`, but the scope is limited to the body of the with
    statement. If the code within the body doesn't yield to the hub
    (and doesn't raise an exception), then upon exiting the
    context manager an :exc:`AssertionError` will be raised.

    This is useful in unit tests and for debugging purposes.

    :keyword float max_blocking_time: If given, the body is allowed
        to block for up to this many fractional seconds before
        an error is raised.
    :keyword bool hub_only: If True, then *max_blocking_time* only
        refers to the amount of time spent between switches into the
        hub. If False, then it refers to the maximum time between
        *any* switches. If *max_blocking_time* is not given, has no
        effect.

    Example::

        # This will always raise an exception: nothing switched
        with assert_switches():
            pass

        # This will never raise an exception; nothing switched,
        # but it happened very fast
        with assert_switches(max_blocking_time=1.0):
            pass

    .. versionadded:: 1.3

    .. versionchanged:: 1.4
        If an exception is raised, it now includes information about
        the duration of blocking and the parameters of this object.
    NFc                 C   s   || _ || _d S r   )max_blocking_timehub_only)r   r   r   r   r   r   r   [  r   zassert_switches.__init__c                 C   st   ddl m} ddl m} |  | _}| js| | _n| jr'||| j| _n|	|| j| _t
 | _| j  | S )Nr   )get_hub)_tracer)r@   r   r   hubr   GreenletTracertracerr   HubSwitchTracerMaxSwitchTracerr   _entered!monitor_current_greenlet_blocking)r   r   r   r   r   r   r   	__enter___  s   
zassert_switches.__enter__c                 C   s   | j   | j}d | _| j }d | _ |d urd S ||}|rZt | j }|d }|||i }	| jr4dnd}
|
d|f 7 }
| j}|
|rHd|f nd7 }
|
d7 }
|
d	|	7 }
t
|
d S )Nrz   z
To the hubzTo any greenletz in %.4f secondsz (max allowed %.4f seconds)rS   r   )r   killr   did_block_hubr   r   did_block_hub_reportr   r   rY   r   )r   rc   vr   r   r   	did_blockexecution_time_sactive_greenletreport_linesmessage	max_blockr   r   r   __exit__s  s$   

zassert_switches.__exit__r   )
r1   r2   r3   r4   r   r   r   r   r   r  r   r   r   r   r   /  s    &
r   c              	   C   sL   | dur$z|    W n ttfy   Y nw | j   | j} | dusdS dS )z>Do our best to clear local variables in all frames in a stack.N)clearr   AttributeErrorrG   f_backrI   r   r   r   clear_stack_frames  s   
r	  )$r4   
__future__r   r   r   r   r   r9   rZ   rb   r   gevent._compatr   r   r   gevent._utilr	   __all__rB   r   r   objectr   r   r
   rK   rC   rD   dump_stacksrt   ru   r   AssertionErrorr   r   r	  r   r   r   r   <module>   sD   
2
4'E  ^