
    gil                    N   d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	 ddl
mZ ddlmZ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 ddlmZ ddlmZmZmZ ddlmZm Z  ddlm!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl'm/Z/m0Z0 ddl1m2Z2 	 ddl3Z3 ej4        d          Z5 G d dee         e           Z6 G d dee                   Z7 G d de          Z8 G d de8          Z9 G d d e8          Z: G d! d"e8          Z; G d# d$e8          Z< G d% d&e8          Z=dS )'z1
Psycopg connection pool module (async version).
    )annotationsN)ABCabstractmethod)	monotonic)TracebackType)AnyAsyncIteratorGenericcast)ref)asynccontextmanager)AsyncConnection)errors)TransactionStatus   )ACTAsyncConnectFailedCBAsyncConnectionCB)AttemptWithBackoffBasePool)
PoolClosedPoolTimeoutTooManyRequests)DequeSelf)
AConditionAEventALockAQueueAWorkeragatherasleep)aspawncurrent_task_name)AsyncSchedulerTzpsycopg.poolc                      e Zd ZU ded<   	 dm ede          ddddddddddd	d
dddddn fd(Z	 do fd-Z	 dod/Z	dpdqd0Z
edrdsd3            Zdrdtd5Zdud7Zdvd8Zdwd:Zdxd<Zdod=Zdxd>ZdydAZdzdBZd{d|dDZdodEZdodFZdodGZdodHZd}dqdJZd~dLZddNZddUZdrddVZdodWZ e!dxdX            Z"dodYZ#dd\Z$dd^Z%e&dda            Z'drdtdbZ(	 dddfZ)dydgZ*dxdhZ+dxdiZ,dodjZ-d fdlZ. xZ/S )AsyncConnectionPoolz
Deque[ACT]_pool 	type[ACT]N         >@r   g      @g     @g     r@   )connection_classkwargsmin_sizemax_sizeopen	configurecheckresetnametimeoutmax_waitingmax_lifetimemax_idlereconnect_timeoutreconnect_failednum_workersconninfostrr.   r/   dict[str, Any] | Noner0   intr1   
int | Noner2   bool | Noner3   AsyncConnectionCB[ACT] | Noner4   r5   r6   
str | Noner7   floatr8   r9   r:   r;   r<   AsyncConnectFailedCB | Noner=   c                  || _         || _        || _        |	| _        || _        |  |  |  t          t          t                                        | _        d | _	        d | _
        g | _        t                                          |||||
||||||           	 |r|                                  |	dx}| _        |r|                                  d S d S )N)
r/   r0   r1   r6   r7   r8   r9   r:   r;   r=   T)r.   _check
_configure_reset_reconnect_failedr   WaitingClientr   _waiting_pool_full_event_sched_runner_workerssuper__init___warn_open_async_open_implicit_open)selfr>   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   	__class__s                     g/var/www/html/Pagina-Ingenieria-Requisitos/venv/lib/python3.11/site-packages/psycopg_pool/pool_async.pyrS   zAsyncConnectionPool.__init__'   s   * !1#!1 	#,mC0133 04-1')#%/# 	 	
 	
 	
	( (%%'''<)--D4& 	JJLLLLL	 	    FreturnNonec                r    t          | dd          rd S |                                 }d}t          |d|d d S )N_closedTzNyou can try to call 'close()' explicitly or to use the pool as context manager      @)r7   timeout_hint)getattr_signal_stop_workerr!   )rW   workershints      rY   __del__zAsyncConnectionPool.__del__k   sU     tY-- ..00G8  Wc======rZ   c                    t                                                       | j        rd| _        	 |                                  d S d S NF)	rR   _check_open_getconnrU   rT   warningswarntype__name__DeprecationWarning)rW   rX   s    rY   rh   z'AsyncConnectionPool._check_open_getconnx   sS    ##%%% 	"'D
%%'''''	 	rZ   Tc                    t          j        dt          |           j         dt          |           j         dt                     d S )Nzopening the async pool z in the constructor is deprecated and will not be supported anymore in a future release. Please use `await pool.open()`, or use the pool as context manager using: `async with z(...) as pool: `...)ri   rj   rk   rl   RuntimeWarningrW   s    rY   rT   z$AsyncConnectionPool._warn_open_async   sb    MX$t***= X X 04Dzz/BX X X     rZ   c                  K   |                                   | j        4 d{V  | j        rJ t          | j                  | j        k    r	 ddd          d{V  dS t                      | _        ddd          d{V  n# 1 d{V swxY w Y   t                              d| j	                   | j        
                    |           d{V s-|                                  d{V  t          d| d          | j        4 d{V  | j        sJ d| _        ddd          d{V  n# 1 d{V swxY w Y   t                              d| j	                   dS )a-  
        Wait for the pool to be full (with `min_size` connections) after creation.

        Close the pool, and raise `PoolTimeout`, if not ready within *timeout*
        sec.

        Calling this method is not mandatory: you can try and use the pool
        immediately after its creation. The first client will be served as soon
        as a connection is ready. You can use this method if you prefer your
        program to terminate in case the environment is not configured
        properly, rather than trying to stay up the hardest it can.
        Nz"waiting for pool %r initializationz%pool initialization incomplete after  seczpool %r is ready to use)rh   _lockrO   lenr(   	_min_sizer   loggerinfor6   wait_timeoutcloser   )rW   r7   s     rY   waitzAsyncConnectionPool.wait   s      	  """: 	- 	- 	- 	- 	- 	- 	- 	-,,,,4:$.00	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- %+HHD!		- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	8$)DDD*77@@@@@@@@ 	U**,,SgSSSTTT: 	) 	) 	) 	) 	) 	) 	) 	)(((($(D!	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	-ty99999s)   (BB
BBD22
D<?D<float | NoneAsyncIterator[ACT]c           
    $  K   |                      |           d{V }	 t                      }|4 d{V  |W V  ddd          d{V  n# 1 d{V swxY w Y   |                     |           d{V  t                      }| j        | j        xx         t          d||z
  z            z  cc<   dS # |                     |           d{V  t                      }| j        | j        xx         t          d||z
  z            z  cc<   w xY w)a&  Context manager to obtain a connection from the pool.

        Return the connection immediately if available, otherwise wait up to
        *timeout* or `self.timeout` seconds and throw `PoolTimeout` if a
        connection is not available in time.

        Upon context exit, return the connection to the pool. Apply the normal
        :ref:`connection context behaviour <with-connection>` (commit/rollback
        the transaction in case of success/error). If the connection is no more
        in working state, replace it with a new one.
        r7   N     @@)getconnr   putconn_stats	_USAGE_MSrA   )rW   r7   connt0t1s        rY   
connectionzAsyncConnectionPool.connection   s      \\'\22222222	CB        



                           ,,t$$$$$$$$$BK'''3vb/A+B+BB''''' ,,t$$$$$$$$$BK'''3vb/A+B+BB'''''''s.   B7 AB7 
AB7 AB7 7ADr   c                T  K   || j         }t                      |z   }t                              d| j                   | j        | j        xx         dz  cc<   |                                  	 |                     |           d{V S # t          $ r t          d|dd          dw xY w)a  Obtain a connection from the pool.

        You should preferably use `connection()`. Use this function only if
        it is not possible to use the connection as context manager.

        After using this function you *must* call a corresponding `putconn()`:
        failing to do so will deplete the pool. A depleted pool is a sad pool:
        you don't want a depleted pool.
        Nzconnection requested from %rr    couldn't get a connection after .2frr   )
r7   r   rv   rw   r6   r   _REQUESTS_NUMrh   _getconn_with_check_loopr   )rW   r7   deadlines      rY   r   zAsyncConnectionPool.getconn   s       ?lG;;(2DI>>>D&'''1,'''  """	66x@@@@@@@@@  	 	 	D7DDDD 	s   ,B  B'r   c                &  K   d }	 |                      |t                      z
             d {V }	 |                     |           d {V  t                              d| j                   |S # t          $ r  |                     |d           d {V  Y nw xY wt                      }|st          ||z
            }n|	                    |           |
                    |          rt                      t          |j                   d {V  )NTzconnection given by %rfrom_getconnr~   )_getconn_uncheckedr   _check_connectionrv   rw   r6   	Exception_putconnr   update_delaytime_to_give_upr   r"   delay)rW   r   attemptr   nows        rY   r   z,AsyncConnectionPool._getconn_with_check_loop   sV     -1	,00IKK1GHHHHHHHHD,,T222222222 4di@@@	  = = =mmDtm<<<<<<<<<<<= ++C *,X^DDD$$S)))&&s++ ,!mm#W]++++++++++	,s   A. .'BBc           
       K   | j         4 d {V  |                     |           d {V x}sdt                      }t                      }| j                            |           | j        | j        xx         dz  cc<   |                                  d d d           d {V  n# 1 d {V swxY w Y   |s	 |	                    |           d {V }n)# t          $ r | j        | j        xx         dz  cc<    w xY w	 t                      }| j        | j        xx         t          d||z
  z            z  cc<   n@# t                      }| j        | j        xx         t          d||z
  z            z  cc<   w xY w| |_        |S )Nr   r~   r   )rs   _get_ready_connectionr   rM   rN   appendr   _REQUESTS_QUEUED_maybe_grow_poolrz   r   _REQUESTS_ERRORS_REQUESTS_WAIT_MSrA   r(   )rW   r7   r   r   posr   s         rY   r   z&AsyncConnectionPool._getconn_unchecked  s]      : 		( 		( 		( 		( 		( 		( 		( 		(#'#=#=g#F#FFFFFFFGD ([[*7//$$S)))D1222a7222 %%'''		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		( 		(  	OO XXgX66666666   D1222a7222 
 [[D2333s6R"W;M7N7NN3333 [[D2333s6R"W;M7N7NN3333333
 
s0   BB$$
B.1B.8C D; &C;;D; ;=E8
ACT | Nonec                  K   ||dk    rt                      d}| j        rP| j                                        }t          | j                  | j        k     rt          | j                  | _        nk| j        rdt          | j                  | j        k    rG| j        | j        xx         dz  cc<   t          d| j
        dt          | j                   d          |S )z0Return a connection, if the client deserves one.Ng        r   	the pool z has already z requests waiting)r   r(   popleftrt   _nconns_minr8   rN   r   r   r   r6   )rW   r7   r   s      rY   r   z)AsyncConnectionPool._get_ready_connection#  s      7c>>--: 
	:%%''D4:!111#&tz??  	#dm"4"48H"H"HK-...!3...!:DI : :&&: : :   rZ   r   c                   K   | j         sd S 	 |                      |           d {V  d S # t          $ r!}t                              d|            d }~ww xY w)Nzconnection failed check: %s)rI   r   rv   rw   )rW   r   es      rY   r   z%AsyncConnectionPool._check_connection6  s{      { 	F	++d########### 	 	 	KK5q999	s   * 
AAAc                    | j         | j        k    s| j        rd S | xj         dz  c_         t                              d| j        | j                    d| _        |                     t          | d                     d S )Nr   growing pool %r to %sTgrowing)_nconns	_max_size_growingrv   rw   r6   run_taskAddConnectionrp   s    rY   r   z$AsyncConnectionPool._maybe_grow_pool?  sv     <4>))T])F+TYEEEmD$77788888rZ   c                   K   |                      |           t                              d| j                   |                     |           d{V rdS |                     |d           d{V  dS )zReturn a connection to the loving hands of its pool.

        Use this function only paired with a `getconn()`. You don't need to use
        it if you use the much more comfortable `connection()` context manager.
        zreturning connection to %rNFr   )_check_pool_putconnrv   rw   r6   _maybe_close_connectionr   rW   r   s     rY   r   zAsyncConnectionPool.putconnI  s       	  &&&0$)<<<--d33333333 	FmmDum55555555555rZ   r   boolc                   K   | j         r'|                     t          | ||                     d S |                     ||           d {V  d S Nr   )rK   r   ReturnConnection_return_connectionrW   r   r   s      rY   r   zAsyncConnectionPool._putconnX  sj      ; 	KMM*4LQQQRRRRR))$\)JJJJJJJJJJJrZ   c                ^   K   | j         sdS d|_        |                                 d{V  dS )zgClose a returned connection if necessary.

        Return `!True if the connection was closed.
        FNT)r^   r(   ry   r   s     rY   r   z+AsyncConnectionPool._maybe_close_connection_  sC       | 	5
jjlltrZ   rz   c                   K   |                                   | j        4 d{V  |                                  ddd          d{V  n# 1 d{V swxY w Y   |r|                     |           d{V  dS dS )a`  Open the pool by starting connecting and and accepting clients.

        If *wait* is `!False`, return immediately and let the background worker
        fill the pool if `min_size` > 0. Otherwise wait up to *timeout* seconds
        for the requested number of connections to be ready (see `wait()` for
        details).

        It is safe to call `!open()` again on a pool already open (because the
        method was already called, or because the pool context was entered, or
        because the pool was initialized with *open* = `!True`) but you cannot
        currently re-open a closed pool.
        Nr~   )_ensure_lockrs   rV   rz   )rW   rz   r7   s      rY   r2   zAsyncConnectionPool.openm  s      	: 	 	 	 	 	 	 	 	JJLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	-))G),,,,,,,,,,,	- 	-s   A
AAc                    | j         sd S |                                  |                                  t                      | _        t                      | _        d| _         d| _        |                                  | 	                                 d S )NFT)
r^   _check_openr   r   _tasksr%   _sched_opened_start_workers_start_initial_tasksrp   s    rY   rV   zAsyncConnectionPool._open  s    | 	F 	 hh$&&!!#####rZ   c                    	 	 t          j                     n3# t          $ r& t          t          |           j         d          dw xY w	 | j         dS # t          $ r t                      | _        Y dS w xY w)zmMake sure the pool lock is created.

        In async code, also make sure that the loop is running.
        Tz open with no running loopN)asyncioget_running_loopRuntimeErrorrk   rl   rs   AttributeErrorr   rp   s    rY   r   z AsyncConnectionPool._ensure_lock  s    
	(****   "Dzz*FFF 
	!JJJJ 	! 	! 	!DJJJJ	!s    0AA A54A5c                   t          | j        j        | j         d          | _        | j        rJ t          | j                  D ]C}t          | j        | j	        f| j         d|           }| j        
                    |           Dd S )Nz
-scheduler)r6   z-worker-)argsr6   )r#   r   runr6   rP   rQ   ranger=   workerr   r   )rW   its      rY   r   z"AsyncConnectionPool._start_workers  s    #DKOTY:R:R:RSSS=   t'(( 	$ 	$At{$+>W>WTU>W>WXXXAM  ####	$ 	$rZ   c                    t          | j                  D ]$}|                     t          |                      %|                     t	          | t          |           | j                             d S N)r   r   r   r   Schedule
ShrinkPoolr:   )rW   r   s     rY   r   z(AsyncConnectionPool._start_initial_tasks  sh    t|$$ 	/ 	/AMM---.... 	htZ%5%5t}EEFFFFFrZ   r_   c                  K   | j         rdS | j        4 d{V  d| _         t                              d| j                   t          | j                  }| j                                         t          | j                  }| j                                         | 	                                 d{V }ddd          d{V  n# 1 d{V swxY w Y   t          |d|i d{V  |D ]#}d|_        |                                 d{V  $|D ]3}|                    t          d| j        d                     d{V  4dS )a  Close the pool and make it unavailable to new clients.

        All the waiting and future clients will fail to acquire a connection
        with a `PoolClosed` exception. Currently used connections will not be
        closed until returned to the pool.

        Wait *timeout* seconds for threads to terminate their job, if positive.
        If the timeout expires the pool is closed anyway, although it may raise
        some warnings on exit.
        NTzpool %r closedr7   r   z
 is closed)r^   rs   rv   debugr6   listrN   clearr(   rb   r!   ry   failr   )rW   r7   waitingconnectionsrc   r   r   s          rY   ry   zAsyncConnectionPool.close  s      < 	F: 	7 	7 	7 	7 	7 	7 	7 	7DLLL)49555 4=))GM!!!tz**KJ !4466666666G	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7" w0000000000   	 	DDJ**,,  	L 	LC((:&I$)&I&I&IJJKKKKKKKKKK	L 	Ls   BC
CClist[AWorker]c                  K   | j                             dd            d {V  | j        d d          g c}| _        |D ]$}|                     t	          |                      %| j        r!|                    | j                   d | _        |S )Nr   )r   enterrQ   r   
StopWorkerrP   r   )rW   rc   _s      rY   rb   z'AsyncConnectionPool._signal_stop_worker  s      k4((((((((( "&qqq!12 	, 	,AMM*T**++++ 	&NN4-...!%DrZ   r   c                L   K   d| _         |                                  d {V  | S rg   )rU   r2   rp   s    rY   
__aenter__zAsyncConnectionPool.__aenter__  s3      #iikkrZ   exc_typetype[BaseException] | Noneexc_valBaseException | Noneexc_tbTracebackType | Nonec                >   K   |                                   d {V  d S r   )ry   )rW   r   r   r   s       rY   	__aexit__zAsyncConnectionPool.__aexit__  s.       jjllrZ   c                  K   |                      ||          \  }}t          d|| j        z
            }t                              d| j        ||           | j        4 d{V  || _        || _        | xj        |z  c_        ddd          d{V  n# 1 d{V swxY w Y   t          |          D ]$}| 
                    t          |                      %dS )z+Change the size of the pool during runtime.r   z&resizing %r to min_size=%s max_size=%sN)_check_sizemaxru   rv   rw   r6   rs   r   r   r   r   r   )rW   r0   r1   ngrowr   s        rY   resizezAsyncConnectionPool.resize  sl     !--hAA(Ax$.0114di8	
 	
 	
 : 	" 	" 	" 	" 	" 	" 	" 	"%DN%DNLLE!LL	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"
 u 	/ 	/AMM---....	/ 	/s   #B
B!Bc                P  K   | j         4 d{V  t          | j                  }| j                                         |                                  ddd          d{V  n# 1 d{V swxY w Y   |r.|                                }|j        t                      k    r_t          	                    d|           d|_        |
                                 d{V  |                     t          |                      	 |                     |           d{V  |                     |           d{V  ng# t          $ rZ | j        | j        xx         dz  cc<   t                              d|           |                     t          |                      Y nw xY w|,dS dS )zVerify the state of the connections currently in the pool.

        Test each connection: if it works return it to the pool, otherwise
        dispose of it and create a new one.
        Nz discarding expired connection %sr   z discarding broken connection: %s)rs   r   r(   r   r   pop
_expire_atr   rv   rw   ry   r   r   check_connection_add_to_poolr   r   _CONNECTIONS_LOSTwarning)rW   connsr   s      rY   r4   zAsyncConnectionPool.check  s`      : 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$$$EJ
 !!###	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$  	.99;;D )++-->EEE!
jjll"""""""mD11222.++D111111111 ''----------  3 3 3D2333q8333A4HHHmD11222223  	. 	. 	. 	. 	.s%   AA$$
A.1A.D: :A!FFc                8  K   | j         r|                     d           d{V  dS 	 |                     d           d{V  	 |                     d           d{V  |                     d           d{V  dS # |                     d           d{V  w xY w)a>  
        A simple check to verify that a connection is still working.

        Return quietly if the connection is still working, otherwise raise
        an exception.

        Used internally by `check()`, but also available for client usage,
        for instance as `!check` callback when a pool is created.
        r)   NTF)
autocommitexecuteset_autocommit)r   s    rY   r   z$AsyncConnectionPool.check_connection4  s       ? 	,,,r""""""""""", ))$/////////5,,r*********--e44444444444$--e4444444444s   A< <Bc                   K   | j         sdS 	 ddl}|                    | j                   r|                      |            d{V  dS |                      |            dS )zV
        Called when reconnection failed for longer than `reconnect_timeout`.
        NTr   )rL   inspectiscoroutinefunction)rW   r   s     rY   r<   z$AsyncConnectionPool.reconnect_failedR  s       % 	F	)NNN**4+ABB -,,T22222222222&&t,,,,,rZ   taskMaintenanceTaskc                :    | j                             |           dS )z#Run a maintenance task in a worker.N)r   
put_nowait)rW   r   s     rY   r   zAsyncConnectionPool.run_taskc  s    t$$$$$rZ   r   c                V   K   | j                             ||j                   d{V  dS )z1Run a maintenance task in a worker in the future.N)r   r   tick)rW   r   r   s      rY   schedule_taskz!AsyncConnectionPool.schedule_taskg  s8      kty11111111111rZ   qAQueue[MaintenanceTask]c                n  K   	 t          |                                 d{V x}t                    r)t                              dt                                 dS 	 |                                 d{V  n># t          $ r1}t                              d||j	        j
        |           Y d}~nd}~ww xY w)zRunner to execute pending maintenance task.

        The function is designed to run as a task.

        Block on the queue *q*, run a task received. Finish running if a
        StopWorker is received.
        TNzterminating working task %sztask run %s failed: %s: %s)
isinstancegetr   rv   r   r$   r   r   r   rX   rl   )clsr  r   exs       rY   r   zAsyncConnectionPool.workerk  s      	!%%''MMMMMM24Z@@ :<M<O<OPPPhhjj           0$8Mr       	s   A8 8
B3'B..B3c                  K   | j         | j        xx         dz  cc<   | j        }|r4|                                }t	          t          |          d          |d<   t                      }	  | j        j        | j	        fi | d{V }t                      }| j         | j
        xx         t          d||z
  z            z  cc<   n)# t          $ r | j         | j        xx         dz  cc<    w xY w| |_        | j        rk|                     |           d{V  |j        j        x}t$          j        k    r4t%          |          j        }t+          j        d| d| j         d          |                     |           |S )z0Return a new connection configured for the pool.r   connect_timeoutNr   connection left in status z by configure function : discarded)r   _CONNECTIONS_NUMr/   copyr   roundr   r.   connectr>   _CONNECTIONS_MSrA   r   _CONNECTIONS_ERRORSr(   rJ   pgconntransaction_statusr   IDLEr6   r   ProgrammingError_set_connection_expiry_date)rW   r7   r/   r   r   r   statussnames           rY   _connectzAsyncConnectionPool._connect  s     D)***a/*** 	?[[]]F(+E'NNA(>(>F$%[[	I6.6t}OOOOOOOOOOD
 BK,---VrBw5G1H1HH----  	 	 	K0111Q6111	 
? 	//$'''''''''+88=N=SSS)&116(5 5 55 5 5   	((...s   )C &C)r   AttemptWithBackoff | Noner   c                  K   t                      }|st          | j                  }	 |                                  d{V }n,# t          $ r}t
                              d| j        d|            |                    |          rt
                              d| j        | j                   | j	        4 d{V  | xj
        dz  c_
        |r| j        rd| _        	 ddd          d{V  n# 1 d{V swxY w Y   |                                  d{V  nF|                    |           |                     t          | ||          |j                   d{V  Y d}~dS d}~ww xY wt
                              d	           |                     |           d{V  |r| j	        4 d{V  | j
        | j        k     s| j
        | j        k     rb| j        r[| xj
        dz  c_
        t
                              d
| j        | j
                   |                     t          | d                     nd| _        	 ddd          d{V  dS # 1 d{V swxY w Y   dS dS )zTry to connect and add the connection to the pool.

        If failed, reschedule a new attempt in the future for a few times, then
        give up, decrease the pool connections number and call
        `self.reconnect_failed()`.

        r~   Nzerror connecting in z: z3reconnection attempt in pool %r failed after %s secr   Fr   z!adding new connection to the poolr   T)r   r   r;   r  r   rv   r   r6   r   rs   r   r   r<   r   r  r   r   rw   r   ru   r   rN   r   )rW   r   r   r   r   r  s         rY   _add_connectionz#AsyncConnectionPool._add_connection  s      kk 	I(1GHHHG	((((((DD 	 	 	NNE$)EEEEFFF&&s++ II*  
  : . . . . . . . .LLA%LL .4= .(--	. . . . . . . . . . . . . . . . . . . . . . . . . . .
 ++----------$$S)))((!$AAA7=         FFFFF'	* 	7888%%%%%%%%% 	*z 
* 
* 
* 
* 
* 
* 
* 
* <$.00L4>11dm1LLA%LLKK 7DLQQQMM-d"C"C"CDDDD$)DM)
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
*	* 	*sP   A E.A-E)=!C1E)1
C;	;E)>C;	?A$E))E.5B
I
I Ic                2  K   |                      |           d{V  |rs|j        j        t          j        k    rX| j        | j        xx         dz  cc<   t                              d           | 	                    t          |                      dS ns|j        j        t          j        k    rY| j        | j        xx         dz  cc<   t                              d|           | 	                    t          |                      dS |j        t                      k    r_t                              d           d|_        |                                 d{V  | 	                    t          |                      dS |                     |           d{V  dS )z>
        Return a connection to the pool after usage.
        Nr   z#not serving connection found brokenz discarding closed connection: %szdiscarding expired connection)_reset_connectionr  r  r   UNKNOWNr   r   rv   rw   r   r   _RETURNS_BADr   r   r   r(   ry   r   r   s      rY   r   z&AsyncConnectionPool._return_connection  s      $$T********* 	{-1B1JJJD2333q8333ABBBmD11222 K {-1B1JJJD-...!3...A4HHHmD11222 ?ikk))KK7888DJ**,,MM---...F%%%%%%%%%%%rZ   c                \  K   d|_         | j        r|                                 d{V  dS | j        4 d{V  | j        r.|                                 d{V  	 ddd          d{V  dS | j        r:| j                                                            |           d{V rn^| j        :| j                             |           | j        r6t          | j                   | j
        k    r| j                                         ddd          d{V  dS # 1 d{V swxY w Y   dS )z
        Add a connection to the pool.

        The connection can be a fresh one or one already used in the pool.

        If a client is already waiting for a connection pass it on, otherwise
        put it back into the pool
        N)r(   r^   ry   rs   rN   r   setr   rO   rt   ru   r   s     rY   r   z AsyncConnectionPool._add_to_pool  s      
 < 	**,,F : 	0 	0 	0 	0 	0 	0 	0 	0 | jjll"""""""	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 - 0 ..0044T::::::::  - 0 
!!$''' ( 0S__-N-N)--///-	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0s   #D0BD
D%(D%c                  K   |j         j        x}t          j        k    rn|t          j        k    rdS |t          j        k    s|t          j        k    rt                              d|           	 |	                                 d{V  n# t          $ rR}t                              d|j        j        ||           d|_        |                                 d{V  Y d}~nTd}~ww xY w|t          j        k    r<t                              d|           d|_        |                                 d{V  | j        r	 |                     |           d{V  |j         j        x}t          j        k    r4t          |          j        }t%          j        d| d| j         d          dS # t          $ rI}t                              d|            d|_        |                                 d{V  Y d}~dS d}~ww xY wdS )	z?
        Bring a connection to IDLE state or close it.
        Nz$rolling back returned connection: %sz1rollback failed: %s: %s. Discarding connection %szclosing returned connection: %sr  z by reset function r  zerror resetting connection: )r  r  r   r  r%  INTRANSINERRORrv   r   rollbackr   rX   rl   r(   ry   ACTIVErK   r6   r   r  )rW   r   r  r  r  s        rY   r$  z%AsyncConnectionPool._reset_connection$  s{      k44F9J9OOO(000F(000F>O>W4W4WNNA4HHH
#mmoo%%%%%%%% # # #GL)	   "
jjll""""""""""""# (///NN<dCCCDJ**,,; 	##kk$'''''''''"k<<FARAWWW-f55:E,5U 5 5 K5 5 5   XW  # # #BbBBCCC!
jjll"""""""""""""#	# 	#s2   /B
 

C&AC!!C&=A+F* *
G=4>G88G=c                  K   d }| j         4 d {V  | j        }t          | j                  | _        | j        | j        k    rF|dk    r@| j        r9| j                                        }| xj        dz  c_        | xj        dz  c_        	 d d d           d {V  n# 1 d {V swxY w Y   |rPt                              d| j	        | j        || j
                   d |_        |                                 d {V  d S d S )Nr   r   zHshrinking pool %r to %s because %s unused connections in the last %s sec)rs   r   rt   r(   r   ru   r   rv   rw   r6   r:   ry   )rW   to_close
nconns_mins      rY   _shrink_poolz AsyncConnectionPool._shrink_poolQ  s     #: 		& 		& 		& 		& 		& 		& 		& 		&)J"4:D |dn,,aDJ:--//!  A%   		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		& 		&  
	#KK&	   "HN.."""""""""""
	# 
	#s   A7B
B&)B&dict[str, int]c                    t                                                      }t          | j                  || j        <   |S r   )rR   _get_measuresrt   rN   _REQUESTS_WAITING)rW   rvrX   s     rY   r4  z!AsyncConnectionPool._get_measuresk  s4    WW""$$%(%7%74!"	rZ   )r)   )"r>   r?   r.   r*   r/   r@   r0   rA   r1   rB   r2   rC   r3   rD   r4   rD   r5   rD   r6   rE   r7   rF   r8   rA   r9   rF   r:   rF   r;   rF   r<   rG   r=   rA   r[   r\   )r,   )r7   rF   r[   r\   r   )r7   r{   r[   r|   )r7   r{   r[   r   )r   rF   r[   r   r7   rF   r[   r   )r7   r{   r[   r   )r   r   r[   r\   )r   r   r   r   r[   r\   r   r   r[   r   )Fr,   )rz   r   r7   rF   r[   r\   )r_   )r[   r   )r[   r   )r   r   r   r   r   r   r[   r\   )r0   rA   r1   rB   r[   r\   )r   r  r[   r\   )r   r  r   rF   r[   r\   )r  r  r[   r\   )F)r   r   r   r   r[   r\   )r[   r2  )0rl   
__module____qualname____annotations__r   r   rS   re   rh   rT   rz   r   r   r   r   r   r   r   r   r   r   r   r2   rV   r   r   r   ry   rb   r   r   r   r4   staticmethodr   r<   r   r  classmethodr   r  r"  r   r   r$  r1  r4  __classcell__rX   s   @rY   r'   r'   $   s         @ '+d;&H&H(,# 37/3/3'##+8<'@ @ @ @ @ @ @ @D>     $		 	 	 	: : : : :@ C C C C C,    :, , , ,4   @   &   9 9 9 96 6 6 6K K K K   - - - - -,$ $ $ $(! ! ! !$$ $ $ $G G G G(L (L (L (L (LT      
   / / / / /"". ". ". ".H , , , \,:) ) ) )"% % % %2 2 2 2    [*    B CH2* 2* 2* 2* 2*h& & & &>.0 .0 .0 .0`+# +# +# +#Z# # # #4         rZ   r'   c                  6    e Zd ZdZdZddZdd	ZddZddZdS )rM   z<A position in a queue for a client waiting for a connection.)r   error_condr[   r\   c                H    d | _         d | _        t                      | _        d S r   )r   rB  r   rC  rp   s    rY   rS   zWaitingClient.__init__v  s!     $	+/
  \\


rZ   r7   rF   r   c                r  K   | j         4 d{V  | j        s`| j        sY	 | j                             |           d{V st	          d|dd          | _        n# t
          $ r}|| _        Y d}~nd}~ww xY wddd          d{V  n# 1 d{V swxY w Y   | j        r| j        S | j        sJ | j        )zWait for a connection to be set and return it.

        Raise an exception if the wait times out or if fail() is called.
        Nr   r   rr   )rC  r   rB  rx   r   BaseException)rW   r7   r  s      rY   rz   zWaitingClient.wait  s     
 : 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$I $ $$!%!8!8!A!AAAAAAA %0PwPPPP& &
 % $ $ $!#DJJJJJJ$	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 9 	9:*s:   B
9AB

A5$A0+B
0A55B


BBr   r   c                   K   | j         4 d{V  | j        s| j        r	 ddd          d{V  dS || _        | j                                          	 ddd          d{V  dS # 1 d{V swxY w Y   dS )zSignal the client waiting that a connection is ready.

        Return True if the client has "accepted" the connection, False
        otherwise (typically because wait() has timed out).
        NFTrC  r   rB  
notify_allr   s     rY   r(  zWaitingClient.set  sJ      : 	 	 	 	 	 	 	 	y DJ 	 	 	 	 	 	 	 	 	 	 	 	 	 	 DIJ!!###	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	   A'!A''
A14A1rB  r   c                   K   | j         4 d{V  | j        s| j        r	 ddd          d{V  dS || _        | j                                          	 ddd          d{V  dS # 1 d{V swxY w Y   dS )zSignal the client that, alas, they won't have a connection today.

        Return True if the client has "accepted" the error, False otherwise
        (typically because wait() has timed out).
        NFTrH  )rW   rB  s     rY   r   zWaitingClient.fail  sJ      : 	 	 	 	 	 	 	 	y DJ 	 	 	 	 	 	 	 	 	 	 	 	 	 	 DJJ!!###	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	rJ  Nr7  r8  r9  )rB  r   r[   r   )	rl   r:  r;  __doc__	__slots__rS   rz   r(  r    rZ   rY   rM   rM   q  so        FF*I	" 	" 	" 	"   *        rZ   rM   c                  J    e Zd ZdZddZddZdd	Zdd
Zedd            Z	dS )r  z8A task to run asynchronously to maintain the pool state.poolAsyncConnectionPool[Any]c                .    t          |          | _        d S r   )r   rP  rW   rP  s     rY   rS   zMaintenanceTask.__init__  s    II			rZ   r[   r?   c                    |                                  }|rt          |j                  nd}d| j        j         d| dt          |           ddS )Nz<pool is gone>< z at 0xx>)rP  reprr6   rX   rl   id)rW   rP  r6   s      rY   __repr__zMaintenanceTask.__repr__  sU    yy{{"&<tDI,<F4>*FFTFFDFFFFFrZ   r\   c                  K   |                                  }|r|j        rt                              d|            dS t                              dt	                      |            |                     |           d{V  dS )zRun the task.

        This usually happens in a worker. Call the concrete _run()
        implementation, if the pool is still alive.
        ztask run discarded: %sNztask running in %s: %s)rP  closedrv   r   r$   _runrS  s     rY   r   zMaintenanceTask.run  s       yy{{ 	t{ 	LL14888F-/@/B/BDIIIiioorZ   c                   K   |                                  }|r|j        rt                              d|            dS |                    |            dS )zRun the scheduled task

        This function is called by the scheduler task. Use a worker to
        run the task for real in order to free the scheduler immediately.
        ztask tick discarded: %sN)rP  r]  rv   r   r   rS  s     rY   r  zMaintenanceTask.tick  sX       yy{{ 	t{ 	LL2D999FdrZ   c                
   K   d S r   rN  rS  s     rY   r^  zMaintenanceTask._run  s      BE#rZ   N)rP  rQ  )r[   r?   r7  rP  rQ  r[   r\   )
rl   r:  r;  rL  rS   r[  r   r  r   r^  rN  rZ   rY   r  r    s        BB   G G G G
       EEE ^EEErZ   r  c                      e Zd ZdZddZdS )	r   z+Signal the maintenance worker to terminate.rP  rQ  r[   r\   c                
   K   d S r   rN  rS  s     rY   r^  zStopWorker._run  s      rZ   Nra  rl   r:  r;  rL  r^  rN  rZ   rY   r   r     s.        55     rZ   r   c                  .     e Zd Z	 	 dd fd	ZddZ xZS )r   NFrP  rQ  r   r   r   r   c                f    t                                          |           || _        || _        d S r   )rR   rS   r   r   )rW   rP  r   r   rX   s       rY   rS   zAddConnection.__init__  s/     	rZ   r[   r\   c                X   K   |                     | j        | j                   d {V  d S )Nr   )r"  r   r   rS  s     rY   r^  zAddConnection._run  s;      ""4<"FFFFFFFFFFFrZ   rg   )rP  rQ  r   r   r   r   ra  )rl   r:  r;  rS   r^  r?  r@  s   @rY   r   r     sf         .2	      G G G G G G G GrZ   r   c                  ,     e Zd ZdZd fdZddZ xZS )r   z-Clean up and return a connection to the pool.rP  rQ  r   r   r   r   c                f    t                                          |           || _        || _        d S r   )rR   rS   r   r   )rW   rP  r   r   rX   s       rY   rS   zReturnConnection.__init__  s0    	(rZ   r[   r\   c                X   K   |                     | j        | j                   d {V  d S r   )r   r   r   rS  s     rY   r^  zReturnConnection._run  s<      %%did>O%PPPPPPPPPPPrZ   )rP  rQ  r   r   r   r   ra  rl   r:  r;  rL  rS   r^  r?  r@  s   @rY   r   r     s_        77) ) ) ) ) )
Q Q Q Q Q Q Q QrZ   r   c                      e Zd ZdZddZdS )	r   zIf the pool can shrink, remove one connection.

    Re-schedule periodically and also reset the minimum number of connections
    in the pool.
    rP  rQ  r[   r\   c                   K   |                     | |j                   d {V  |                                 d {V  d S r   )r  r:   r1  rS  s     rY   r^  zShrinkPool._run  s\         t}555555555!!!!!!!!!!!rZ   Nra  rd  rN  rZ   rY   r   r     s2         " " " " " "rZ   r   c                  ,     e Zd ZdZd fdZddZ xZS )r   zSchedule a task in the pool scheduler.

    This task is a trampoline to allow to use a sync call (pool.run_task)
    to execute an async one (pool.schedule_task). It is pretty much no-op
    in sync code.
    rP  rQ  r   r  r   rF   c                f    t                                          |           || _        || _        d S r   )rR   rS   r   r   )rW   rP  r   r   rX   s       rY   rS   zSchedule.__init__  s/     		


rZ   r[   r\   c                V   K   |                     | j        | j                   d {V  d S r   )r  r   r   rS  s     rY   r^  zSchedule._run  s8        DJ77777777777rZ   )rP  rQ  r   r  r   rF   ra  rk  r@  s   @rY   r   r     s[              8 8 8 8 8 8 8 8rZ   r   )>rL  
__future__r   loggingri   abcr   r   timer   typesr   typingr   r	   r
   r   weakrefr   
contextlibr   psycopgr   r   r   
psycopg.pqr   r   r   r   baser   r   r   r   r   _compatr   r   _acompatr   r   r   r   r    r!   r"   r#   r$   sched_asyncr%   r   	getLoggerrv   r'   rM   r  r   r   r   r   r   rN  rZ   rY   <module>r     sb    # " " " " "   # # # # # # # #             4 4 4 4 4 4 4 4 4 4 4 4       * * * * * * # # # # # #       ( ( ( ( ( ( = = = = = = = = = = . . . . . . . . < < < < < < < < < <                 Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q / / / / / / / / ' ' ' ' ' 'NNN		>	*	*J J J J J'#, J J JZ? ? ? ? ?GCL ? ? ?D)F )F )F )F )Fc )F )F )FX       G G G G GO G G G	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q" " " " " " " "8 8 8 8 8 8 8 8 8 8rZ   