
    PfE                     |   d dl Z d dl mZ d dl mZ 	 d dlmZ n# e$ r  G d d          ZY nw xY w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Zd dlZd dlZd dlmZ d dlmZmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ  e            Zd dZej        ej        cZZ  e
j!                    a"da#da$i Z%d Z& G d de          Z'd!dZ(d Z) G d de          Z* G d dej+        e,          Z-d Z.e dfdZ/d Z0d Z1 e,            Z2 G d de,          Z3 e3e          Z4e4j5        Z5e4j6        Z6e4j7        Z7e4j8        Z8e4j9        Z9e4j:        Z:e4j;        Z;e4j<        Z<e4j=        Z=e4j>        Z>e4j?        Z?e4j@        Z@e4jA        ZAe4jB        ZBe4jC        ZCe4jD        ZDe4jE        ZEe4jF        ZFe4jG        ZGe4jH        ZHe4j7        Z7ejI        ZIejJ        ZJdS )"    N)iscoroutine)Future)AsyncGeneratorTypec                       e Zd ZdS )r   N)__name__
__module____qualname__     ;/var/www/html/env/lib/python3.11/site-packages/txaio/aio.pyr   r   !   s        r   r   )datetime)IFailedFutureILogger
log_levels)guess_stream_needs_encoding)_BatchedTimer)_util)_Configc                 N    t                      }| | |_        t          |          S )aQ  
    :return: an instance of the txaio API with the given
        configuration. This won't affect anything using the 'gloabl'
        config nor other instances created using this function.

    If you need to customize txaio configuration separately (e.g. to
    use multiple event-loops in asyncio), you can take code like this:

        import txaio


        class FunTimes(object):

            def something_async(self):
                return txaio.call_later(1, lambda: 'some result')

    and instead do this:

        import txaio


        class FunTimes(object):
            txaio = txaio

            def something_async(self):
                # this will run in the local/new event loop created in the constructor
                return self.txaio.call_later(1, lambda: 'some result')

        fun0 = FunTimes()
        fun1 = FunTimes()
        fun1.txaio = txaio.with_config(loop=asyncio.new_event_loop())

    So `fun1` will run its futures on the newly-created event loop,
    while `fun0` will work just as it did before this `with_config`
    method was introduced (after 2.6.2).
    )r   loop_AsyncioApi)r   cfgs     r   with_configr   9   s)    J ))Csr   infoFc                 :    t                               |            d S N)_categoriesupdate)
categoriess    r   add_log_categoriesr    l   s    z"""""r   c                   4    e Zd ZdZd Zed             Zd ZdS )FailedFuturea?  
    This provides an object with any features from Twisted's Failure
    that we might need in Autobahn classes that use FutureMixin.

    We need to encapsulate information from exceptions so that
    errbacks still have access to the traceback (in case they want to
    print it out) outside of "except" blocks.
    c                 0    || _         || _        || _        dS )z
        These are the same parameters as returned from ``sys.exc_info()``

        :param type_: exception type
        :param value: the Exception instance
        :param traceback: a traceback object
        N)_type_value
_traceback)selftype_value	tracebacks       r   __init__zFailedFuture.__init__z   s     
#r   c                     | j         S r   )r%   r'   s    r   r)   zFailedFuture.value   s
    {r   c                 *    t          | j                  S r   )strr)   r-   s    r   __str__zFailedFuture.__str__   s    4:r   N)r   r   r	   __doc__r+   propertyr)   r0   r
   r   r   r"   r"   p   sW         
$ 
$ 
$   X    r   r"    c                    d|v r/|d         t           v r t                               |d                   }t          j                    |d<   ||d<   ||d<   |dk    rd}d|d<    |j        d	i |} t	          | j        |          |           d S )
Nlog_categorylog_time	log_level
log_formattracedebugTtxaio_tracer
   )r   gettimeformatgetattr_logger)loggerlevelr>   kwargsmsgs        r   _logrE      s     F>$:k$I$I!788F:F;!F<  $}
&-
!
!&
!
!C"GFNE""3'''''r   c                      d S r   r
   )argskws     r   _no_oprI      s    Dr   c                        e Zd Zd Zd Zd ZdS )_TxaioLogWrapperc                 H    || _         |                     t                     d S r   )r@   _set_log_level
_log_level)r'   rA   s     r   r+   z_TxaioLogWrapper.__init__   s#    J'''''r   c                 2    t          | |          } ||i |S r   )r?   )r'   rB   rG   rC   funcs        r   emitz_TxaioLogWrapper.emit   s&    tU##tT$V$$$r   c                     t          j        |          }t          t                     D ]?\  }}||k    rt          j        t
          | |          }nt          }t          | ||           @|| _        d S r   )	r   index	enumerate	functoolspartialrE   rI   setattrrN   )r'   rB   target_levelidxname
log_methods         r   rM   z_TxaioLogWrapper._set_log_level   su    !'.. %Z00 	, 	,KS$l""&.tT4@@

#
D$
++++r   N)r   r   r	   r+   rQ   rM   r
   r   r   rK   rK      sA        ( ( (% % %
  
  
  
  
 r   rK   c                   $     e Zd Z fdZd Z xZS )_TxaioFileHandlerc                 ~     t          t          |           j        di | || _        t	          |          | _        d S )Nr
   )superr]   r+   _filer   _encode)r'   fileobjrH   	__class__s      r   r+   z_TxaioFileHandler.__init__   sA    /&&/55"555
27;;r   c                    t          |j        t                    rt|j                            d|j                            dd                    } |j        d
i |j        }t          j        |j                            dd                    }ni|                                }|j        t          j
        k    r'|j        r |dz  }t          j        |j         D ]}||z   }t          j        |j                  }d                    |                    d          |t           j                  }| j        r|                    d	          }| j                            |           d S )Nr8   log_messager3   r6   r   
z
{0} {1}{2}z%Y-%m-%dT%H:%M:%S%zutf8r
   )
isinstancerG   dictr<   r>   r   fromtimestamp
getMessagelevelnologgingERRORexc_infor*   format_exceptioncreatedstrftimeoslinesepra   encoder`   write)r'   recordfmtmessagedtlinerD   s          r   rQ   z_TxaioFileHandler.emit   sJ   fk4(( 	8+//r22 C !cj//6;//G'
A(F(FGGBB''))G~..6?.4%6H - -D%nGG'77B!!KK-..J
 

 < 	%**V$$C
r   )r   r   r	   r+   rQ   __classcell__)rc   s   @r   r]   r]      sG        < < < < <
      r   r]   c                     t          j                    j        } d| j        v r3| j        d         j        }d                    |j        |j                  }n/| j        d         }| j	        j
        dk    r|dz   | j	        j
        z   }t          t          j        |                    }t                              |           |S )Nr'   z{0}.{1}r   z<module>.)rZ   )inspectcurrentframef_backf_localsrc   r>   r   r   	f_globalsf_codeco_namerK   rm   	getLogger_loggersadd)cfcls	namespacerA   s       r   make_loggerr      s     
				&Bk&!+$$S^S\BB		L,	9
** "C")*;;Ig/Y???@@F LLMr   c                 J   |t           vr;t          d                    |d                    t                                         t          rdS da|at          |           }t          j                    	                    |           dt          _
        t          j        t          j        t          j        t          j        t          j        t          j        d}t          j                                        ||                    t"          D ]}|                    |           dS )z
    Begin logging.

    :param out: if provided, a file-like object to log to. By default, this is
                stdout.
    :param level: the maximum log-level to emit (a string)
    z'Invalid log level '{0}'; valid are: {1}z, NT)criticalerrorwarnr   r:   r9   )r   RuntimeErrorr>   join_started_loggingrN   r]   rm   r   
addHandlerraiseExceptionsCRITICALrn   WARNINGINFODEBUGsetLevelr   rM   )outrB   handlerlevel_to_stdlibrA   s        r   start_loggingr      s    J5<<tyy,, 
 
 	
  J$$G""7+++ #G$ O   !7888  % %e$$$$% %r   c                 H    t           D ]}|                    |            | adS )zH
    Set the global log level on all loggers instantiated by txaio.
    N)r   rM   rN   )rB   rA   s     r   set_global_log_levelr     s3      % %e$$$$JJJr   c                      t           S r   )rN   r
   r   r   get_global_log_levelr   (  s    r   c                       e Zd ZdZdZd Zed             Zd Zd Z	d Z
eeefdZd	 ZddZd Zd Zd ZddZd ZddZddZddZddZd ZddZd Zd
S )r   FTc                     || _         d S r   )_config)r'   configs     r   r+   z_AsyncioApi.__init__7  s    r   c                 X    | j         j        r| j         j        S t          j                    S r   )r   r   asyncioget_event_loopr-   s    r   _loopz_AsyncioApi._loop:  s-     < 	%<$$
 %'''r   c                     	 d                     |j        j        j        t	          |j                            S # t
          $ r d                     |          cY S w xY w)z_
        :param fail: must be an IFailedFuture
        returns a unicode error-message
        z{0}: {1}z+Failed to produce failure message for "{0}")r>   r%   rc   r   r/   	Exceptionr'   fails     r   failure_messagez_AsyncioApi.failure_messageE  ss    
	N$$%.DK      	N 	N 	N@GGMMMMM	Ns   69 AAc                     |j         S )z\
        :param fail: must be an IFailedFuture
        returns a traceback instance
        )r&   r   s     r   failure_tracebackz_AsyncioApi.failure_tracebackR  s    
 r   c                     	 t          j                    }t          j        |j        |j        |j        |           |                                S # t          $ r d	                    |          cY S w xY w)zP
        :param fail: must be an IFailedFuture
        returns a string
        )filez,Failed to format failure traceback for '{0}')
ioStringIOr*   print_exceptionr$   r)   r&   getvaluer   r>   )r'   r   fs      r   failure_format_tracebackz$_AsyncioApi.failure_format_tracebackY  s    

	OA%

	    ::<< 	O 	O 	OAHHNNNNN	Os   AA A21A2c                 (   |t           ur|t           urt          d          | j                                        }|t           urt	          ||           n|t           urt          ||           t           urfd}|                    |           |S )Nz"Cannot have both result and error.c                 t    	 |                                   d S # t          j        $ r  |            Y d S w xY wr   )	exceptionr   CancelledError)r   	cancellers    r   donez'_AsyncioApi.create_future.<locals>.doney  sJ    !KKMMMMM- ! ! !IaLLLLLL!s    77)_unspecified
ValueErrorr   create_futureresolverejectadd_done_callback)r'   resultr   r   r   r   s      `  r   r   z_AsyncioApi.create_futurej  s    %%%|*C*CABBBJ$$&&%%Av,&&1e L((! ! ! ! !
 %%%r   c                 .    |                      |          S )N)r   )r   )r'   r   s     r   create_future_successz!_AsyncioApi.create_future_success  s    !!!000r   Nc                 N    |                                  }t          ||           |S r   )r   r   )r'   r   r   s      r   create_future_errorz_AsyncioApi.create_future_error  s(      q%r   c                    	  ||i |}t          |t                    r|S t          |          r| j                            |          S t          |t
                    r/t          d                    t          |                              t          |          S # t          $ r t          t                                cY S w xY w)Nz_as_future() received an async generator function; does '{}' use 'yield' when you meant 'await'?)rh   r   r   r   create_taskr   r   r>   r/   r   r   r   create_failure)r'   funrG   rC   ress        r   	as_futurez_AsyncioApi.as_future  s    	2#t&v&&C #v&& 2
S!! 
2z--c222C!344 2"??EvC@ @   -S111  	9 	9 	9&~'7'788888	9s   B %CCc                 J    t          |          pt          |t                    S r   )r   rh   r   )r'   objs     r   	is_futurez_AsyncioApi.is_future  s    3::c6#:#::r   c                 b    t          j        |g|R i |}| j                            ||          S r   )rU   rV   r   
call_later)r'   delayr   rG   rC   	real_calls         r   r   z_AsyncioApi.call_later  s:    %c;D;;;F;;	z$$UI666r   d   c                 D      fd}t          |dz  || j                  S )a&  
        Creates and returns an object implementing
        :class:`txaio.IBatchedTimer`.

        :param bucket_seconds: the number of seconds in each bucket. That
            is, a value of 5 means that any timeout within a 5 second
            window will be in the same bucket, and get notified at the
            same time. This is only accurate to "milliseconds".

        :param chunk_size: when "doing" the callbacks in a particular
            bucket, this controls how many we do at once before yielding to
            the reactor.
        c                  6     j                                         S r   )r   r=   r-   s   r   get_secondsz3_AsyncioApi.make_batched_timer.<locals>.get_seconds  s    :??$$$r   g     @@)seconds_providerdelayed_call_creator)r   r   )r'   bucket_seconds
chunk_sizer   s   `   r   make_batched_timerz_AsyncioApi.make_batched_timer  sG    	% 	% 	% 	% 	% V#Z(!%
 
 
 	
r   c                 *    |                                 S r   )r   )r'   futures     r   	is_calledz_AsyncioApi.is_called  s    {{}}r   c                 0    |                     |           d S r   )
set_result)r'   r   r   s      r   r   z_AsyncioApi.resolve  s    &!!!!!r   c                    |t                      }nXt          |t                    rt          t	          |          |d           }n$t          |t
                    st          d          |                    |j                   d S )Nz-reject requires an IFailedFuture or Exception)	r   rh   r   r"   typer   r   set_exceptionr)   )r'   r   r   s      r   r   z_AsyncioApi.reject  s~    ="$$EEy)) 	T eeT::EEe]33 T"#RSSSU[)))))r   c                 |    t           j        dk    r|                    |           d S |                                 d S )N)   	   )sysversion_infocancel)r'   r   rD   s      r   r   z_AsyncioApi.cancel  s9    v%%MM#MMOOOOOr   c                 v    |rt          t          |          |d          S t          t          j                     S )z
        This returns an object implementing IFailedFuture.

        If exception is None (the default) we MUST be called within an
        "except" block (such that sys.exc_info() returns useful
        information).
        N)r"   r   r   ro   )r'   r   s     r   r   z_AsyncioApi.create_failure  s6      	BYDAAAS\^^,,r   c                 <    fd}|                     |          S )z]
        callback or errback may be None, but at least one must be
        non-None.
        c                     	 |                                  }r |           d S d S # t          t          j        f$ r  r t	                                 Y d S Y d S w xY wr   )r   r   r   r   r   )r   r   callbackerrbacks     r   r   z'_AsyncioApi.add_callbacks.<locals>.done  s    .hhjj "HSMMMMM" "w56 . . . .GN,,------. . ..s   !( /AA)r   )r'   r   r   r   r   s     `` r   add_callbacksz_AsyncioApi.add_callbacks  s8    
	. 	. 	. 	. 	. 	. ''---r   c                 $    t          j        |d|iS )a  
        This returns a Future that waits for all the Futures in the list
        ``futures``

        :param futures: a list of Futures (or coroutines?)

        :param consume_exceptions: if True, any errors are eaten and
        returned in the result list.
        return_exceptions)r   gather)r'   futuresconsume_exceptionss      r   r   z_AsyncioApi.gather  s      ~wM:LMMMr   c                 N    t          j        t          j        |                    S )z
        Inline sleep for use in co-routines.

        :param delay: Time to sleep in seconds.
        :type delay: float
        )r   ensure_futuresleep)r'   r   s     r   r   z_AsyncioApi.sleep  s     $W]5%9%9:::r   r   )r   )T)r   r   r	   using_twistedusing_asyncior+   r2   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   3  s       MM   ( ( X(N N N  O O O" $0||    01 1 1   
2 2 2(; ; ;7 7 7

 
 
 
0  " " " "* * * *   
- 
- 
- 
-. . .N N N N$; ; ; ; ;r   r   r   )r3   )Kr   r   r   typesr   ImportErrorr   rs   r   r=   weakrefrU   r*   rm   r   r   txaio.interfacesr   r   r   txaio._iotyper   txaio._commonr   txaior   r   r   r   stderrstdout_stderr_stdoutWeakSetr   rN   r   r   r    r"   rE   rI   rK   Handlerobjectr]   r   r   r   r   r   r   _default_apir   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   time_nsperf_counter_nsr
   r   r   <module>r     s  6             (((((((             
			 				 



                   ? ? ? ? ? ? ? ? ? ? 5 5 5 5 5 5 ' ' ' ' ' '             
( ( ( (X :sz 7?
 # # #    =   B( ( ( ((	 	 	         w      ,       >  , V '% '% '% '%T     vxxU; U; U; U; U;& U; U; U;p {6"" **. 2 '@ *$: "6 "	"	$
!4 "	

				,*		
-'s    ..