
    !ni<                     j   d dl mZ d dlm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  e       Z G d	 d
e      Zd Z G d de      Z G d de      Z G d de      ZeZ G d d      Zej2                  D ]  ZefdZ eee ee              e`[[ G d de      Z G d d      Zy)    )deque)contextmanagerN)Pool)timeout)hubs)Timer)GreenThreadc                       e Zd Zy)ConnectTimeoutN)__name__
__module____qualname__     P/home/homepc/tiktok-worker/venv/lib/python3.12/site-packages/eventlet/db_pool.pyr   r      s    r   r   c                 $    | j                          y N)rollback)conns    r   cleanup_rollbackr      s    MMOr   c                        e Zd Zdddddef fd	Zd Zd Zd	 Zd
 ZddZ	 fdZ
ef fd	Zeefd       Zd Zd Z xZS )BaseConnectionPoolr      
         c                     |sJ || _         || _        |	| _        || _        || _        || _        d| _        || _        t        
| %  ||d       y)a  
        Constructs a pool with at least *min_size* connections and at most
        *max_size* connections.  Uses *db_module* to construct new connections.

        The *max_idle* parameter determines how long pooled connections can
        remain idle, in seconds.  After *max_idle* seconds have elapsed
        without the connection being used, the pool closes the connection.

        *max_age* is how long any particular connection is allowed to live.
        Connections that have been open for longer than *max_age* seconds are
        closed, regardless of idle time.  If *max_age* is 0, all connections are
        closed on return to the pool, reducing it to a concurrency limiter.

        *connect_timeout* is the duration in seconds that the pool will wait
        before timing out on connect() to the database.  If triggered, the
        timeout will raise a ConnectTimeout from get().

        The remainder of the arguments are used as parameters to the
        *db_module*'s connection constructor.
        NT)min_sizemax_sizeorder_as_stack)

_db_module_args_kwargsmax_idlemax_ageconnect_timeout_expiration_timercleanupsuper__init__)self	db_moduler   r   r$   r%   r&   r(   argskwargs	__class__s             r   r*   zBaseConnectionPool.__init__   s[    4 y#
 .!%(XdSr   c                    | j                   dk(  s| j                  dk(  ry| j                  t        | j                  dd      sy	 t	        j                         }| j                  |       | j                  d   d   |z
  | j                  z   }t        | j                  D cg c]  }|d   	 c}      }||z
  | j                   z   }t        ||      }|dkD  rht        |t        t        j                         j                        j                  | j                   g i       | _        | j                  j#                          yyc c}w # t        t        f$ r
 d| _        Y yw xY w)a  Sets up a timer that will call _expire_old_connections when the
        oldest connection currently in the free pool is ready to expire.  This
        is the earliest possible time that a connection could expire, thus, the
        timer will be running as infrequently as possible without missing a
        possible expiration.

        If this function is called when a timer is already scheduled, it does
        nothing.

        If max_age or max_idle is 0, _schedule_expiration likewise does nothing.
        r   NcalledF   )r%   r$   r'   getattrtime_expire_old_connections
free_itemsmin
IndexError
ValueErrorr   r	   r   get_hubgreenletswitch_schedule_expirationschedule)r+   now
idle_delaytoldest	age_delay
next_delays          r   r>   z'BaseConnectionPool._schedule_expiration>   s9    <<1 2 "". 6 6%H	))+C((- //"-a036$--GJ81!A$89F#5IZ3J >%*:{4<<>CZCZ7[7b7b+/+D+Db"&ND"""++-	  9 J' 	%)D"	s%   AE D>+%E >E EEc           
         t        | j                        }| j                  D cg c]  \  }}}| j                  |||      r| }}}}| j                  D cg c]  \  }}}| j                  |||      s|||f  }}}}| j                  j                          | j                  j	                  |       | xj
                  |t        | j                        z
  z  c_        |D ]  }| j                  |d        yc c}}}w c c}}}w )a  Iterates through the open connections contained in the pool, closing
        ones that have remained idle for longer than max_idle seconds, or have
        been in existence for longer than max_age seconds.

        *now* is the current time, as returned by time.time().
        TquietN)lenr7   _is_expiredclearextendcurrent_size_safe_close)r+   r@   original_count	last_used
created_atr   expirednew_frees           r   r6   z*BaseConnectionPool._expire_old_connectionsi   s    T__- 04= =+	:tY
; = = 04A A+	:t##CJ? 
D)A A 	x( 	^c$//.BBB 	/DT.	/!=
As    C<#Dc                     | j                   dk  s3| j                  dk  s$||z
  | j                   kD  s||z
  | j                  kD  ryy)z@Returns true and closes the connection if it's expired.
        r   TF)r$   r%   )r+   r@   rP   rQ   s       r   rJ   zBaseConnectionPool._is_expired   sB     MMQ$,,!"3?T]]2#dll2r   c                 r    d}	 |r|j                   }|j                          |S d}	 |S # t        $ r Y |S w xY w)a$  If the connection was wrapped by a subclass of
        BaseConnectionWrapper and is still functional (as determined
        by the __nonzero__, or __bool__ in python3, method), returns
        the unwrapped connection.  If anything goes wrong with this
        process, returns None.
        N)_base_destroyAttributeError)r+   r   bases      r   _unwrap_connectionz%BaseConnectionPool._unwrap_connection   sQ     	zz
     		s   ) ) 	66c                     	 |j                          y# t        $ r Y yt        $ r* |s%t        dt	        j
                         d   z         Y yY yw xY w)zVCloses the (already unwrapped) connection, squelching any
        exceptions.
        zConnection.close raised: %sr3   N)closerX   	Exceptionprintsysexc_info)r+   r   rH   s      r   rN   zBaseConnectionPool._safe_close   sN    	KJJL 	 	K3s||~a7HIJ 	Ks    	A-AAc                    t         |          }|	 | j                         }t        |t              r|\  }}}nt        j                         }t        ||       }||_	        |S # t        $ r | xj                  dz  c_         w xY w)Nr3   )
r)   getcreater]   rM   
isinstancetupler5   PooledConnectionWrapper_db_pool_created_at)r+   r   
_last_usedrQ   wrappedr/   s        r   rb   zBaseConnectionPool.get   s    w{} <{{} dE"+/(J
DJ *$5 '1#)  
 !!Q&!s   A# # Bc                    t        |dd      }t        j                         }| j                  |      }| j                  |||      r| j	                  |d       d }n!||t
        u r| j                  }	 |r ||       |t        | )  |||f       n8| j                         dkD  rt        | )  d        n| xj                  dz  c_        | j                          y # t        $ r}t        d|d|       d }Y d }~d }~w d } xY w)Nrg   r   FrG   zWARNING: cleanup z	 raised: r3   )r4   r5   rZ   rJ   rN   _MISSINGr(   r]   r^   r)   putwaitingrM   r>   )r+   r   r(   rQ   r@   er/   s         r   rl   zBaseConnectionPool.put   s   T#8!<
iik&&t,Cj1T/D (",,
DM GKj$/0 ||~!D! !!Q&!!!#'   '1EFs   4
C 	D%C==Dc              #      K   | j                         }	 | | j                  ||       y # | j                  ||       w xY ww)N)r(   )rb   rl   )r+   r(   r   s      r   itemzBaseConnectionPool.item   s;     xxz	,JHHT7H+DHHT7H+s   A, AAAc                    | j                   r| j                   j                          | j                  t               c}| _        |D ]A  }t	        |t
              r|d   n|}| j                  |d       | xj                  dz  c_        C y)zuClose all connections that this pool still holds a reference to,
        and removes all references to them.
           TrG   r3   N)r'   cancelr7   r   rd   re   rN   rM   )r+   r7   rp   r   s       r   rK   zBaseConnectionPool.clear   sz     !!""))+&*oouw#
DO 	#D(u5474DT."		#r   c                 $    | j                          y r   )rK   r+   s    r   __del__zBaseConnectionPool.__del__  s    

r   )F)r   r   r   r   r*   r>   r6   rJ   rZ   rN   rb   rk   rl   r   rp   rK   rv   __classcell__r/   s   @r   r   r      sf    ab!")	#TJ).V/6$
K< !) $$L # , ,#r   r   c                   &    e Zd ZdZd Zed        Zy)TpooledConnectionPoolzZA pool which gives out :class:`~eventlet.tpool.Proxy`-based database
    connections.
    c                     t        j                          }|| | j                  | j                  | j                  g| j                  i | j
                  fS r   r5   connectr!   r&   r"   r#   r+   r@   s     r   rc   zTpooledConnectionPool.create  U    iikCOOT11P48JJPBF,,P P 	Pr   c                     t        j                  |t                     }	 ddlm}  |j
                  |j                  g|i |}|j                  |d      |j                          S # |j                          w xY w)Nr   )tpool)cursor)autowrap_names)	r   Timeoutr   eventletr   executer}   Proxyrs   )clsr,   r&   r-   kwrB   r   r   s           r   r}   zTpooledConnectionPool.connect  s`    OOO^-=>	& 5==!2!2@T@R@D;;tK;@HHJAHHJs   8A) )A;Nr   r   r   __doc__rc   classmethodr}   r   r   r   rz   rz     s!    P
  r   rz   c                   &    e Zd ZdZd Zed        Zy)RawConnectionPoolz7A pool which gives out plain database connections.
    c                     t        j                          }|| | j                  | j                  | j                  g| j                  i | j
                  fS r   r|   r~   s     r   rc   zRawConnectionPool.create!  r   r   c                     t        j                  |t                     }	  |j                  |i ||j	                          S # |j	                          w xY wr   )r   r   r   r}   rs   )r   r,   r&   r-   r   rB   s         r   r}   zRawConnectionPool.connect&  sB    OOO^-=>	$9$$d1b1HHJAHHJs   A ANr   r   r   r   r   r     s!    P
  r   r   c                   (    e Zd Zd Zd Zd Zd ZdZy)GenericConnectionWrapperc                     || _         y r   )rV   )r+   baseconns     r   r*   z!GenericConnectionWrapper.__init__4  s	    
r   c                 6    | j                   j                         S r   )rV   	__enter__ru   s    r   r   z"GenericConnectionWrapper.__enter__=  s    zz##%%r   c                 <    | j                   j                  |||      S r   )rV   __exit__)r+   excvaluetbs       r   r   z!GenericConnectionWrapper.__exit__@  s    zz""3r22r   c                 6    | j                   j                         S r   )rV   __repr__ru   s    r   r   z!GenericConnectionWrapper.__repr__C  s    zz""$$r   )!affected_rows
autocommitbeginchange_usercharacter_set_namer\   commitr   dump_debug_infoerrnoerrorerrorhandlerget_server_info	insert_idliteralpingqueryr   	select_dbserver_capabilitiesset_character_setset_isolation_levelset_server_optionset_sql_modeshow_warningsshutdownsqlstatestatstore_resultstring_literal	thread_id
use_resultwarning_countN)r   r   r   r*   r   r   r   _proxy_funcsr   r   r   r   r   3  s    &3%"Lr   r   c                 B      fd} |_          |_        d z   |_        |S )Nc                 <     t        | j                        |i |S r   )r4   rV   )r+   r-   r.   
_proxy_funs      r   _proxy_methodz_wrapper.<locals>._proxy_methodn  s     274::z2DCFCCr   zGenericConnectionWrapper.)	func_namer   r   )r   r   s   ` r   _wrapperr   m  s,    	D",!+%@:%M"r   c                   >     e Zd ZdZ fdZd ZeZd Zd Zd Z	 xZ
S )rf   zA connection wrapper where:
    - the close method returns the connection to the pool instead of closing it directly
    - ``bool(conn)`` returns a reasonable value
    - returns itself to the pool if it gets garbage collected
    c                 2    t         |   |       || _        y r   )r)   r*   _pool)r+   r   poolr/   s      r   r*   z PooledConnectionWrapper.__init__  s    "
r   c                 H    t        | d      xr t        | j                        S )NrV   )hasattrboolrV   ru   s    r   __nonzero__z#PooledConnectionWrapper.__nonzero__  s    g&;4

+;<r   c                 6    d | _         	 | `y # t        $ r Y y w xY wr   )r   rV   rX   ru   s    r   rW   z PooledConnectionWrapper._destroy  s%    
	
 		s    	c                 v    | r'| j                   r| j                   j                  |        | j                          y)zReturn the connection to the pool, and remove the
        reference to it so that you can't use it again through this
        wrapper object.
        N)r   rl   rW   ru   s    r   r\   zPooledConnectionWrapper.close  s&    
 DJJJJNN4 r   c                      y r   r   ru   s    r   rv   zPooledConnectionWrapper.__del__  s    r   )r   r   r   r   r*   r   __bool__rW   r\   rv   rw   rx   s   @r   rf   rf   z  s(    = Hr   rf   c                   &    e Zd ZdZ	 ddZd Zd Zy)DatabaseConnectorzr
    This is an object which will maintain a collection of database
    connection pools on a per-host basis.
    Nc                     |sJ || _         | j                   t        | _         || _        || _        || _        || _        i | _        y)zconstructor
        *module*
            Database module to use.
        *credentials*
            Mapping of hostname to connect arguments (e.g. username and password)
        N)_conn_pool_classConnectionPool_moduler"   r#   _credentials
_databases)r+   modulecredentials	conn_poolr-   r.   s         r   r*   zDatabaseConnector.__init__  sK     v )  ($2D!
'r   c                 t    || j                   v r| j                   |   S | j                   j                  dd       S )Ndefault)r   rb   )r+   hosts     r   credentials_forz!DatabaseConnector.credentials_for  s:    4$$$$$T**$$((D99r   c                 >   ||f}|| j                   vr}| j                  j                         }||d<   ||d<   |j                  | j	                  |              | j
                  | j                  g| j                  i |}|| j                   |<   | j                   |   S )z@Returns a ConnectionPool to the target host and schema.
        dbr   )r   r#   copyupdater   r   r   r"   )r+   r   dbnamekey
new_kwargsdbpools         r   rb   zDatabaseConnector.get  s     Vndoo%**,J%Jt!%Jvd22489*T**9#zz9-79F#)DOOC s##r   r   )r   r   r   r   r*   r   rb   r   r   r   r   r     s      &:$r   r   )collectionsr   
contextlibr   r_   r5   eventlet.poolsr   r   r   r   eventlet.hubs.timerr   eventlet.greenthreadr	   objectrk   r]   r   r   r   rz   r   r   r   r   r   r   setattrrf   r   r   r   r   <module>r      s     % 
     % , 8	Y 	m m`. ** & '5 5p +77 	HJ&  $j(:2FG	H )!6 !L,$ ,$r   