
    \jk5                    8   d Z ddl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mZmZ ddlmZmZmZmZmZ dd	lmZmZmZmZmZ dd
lmZ er ddl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d      Z& ed      Z' G d d      Z( G d d      Z)ddgZ*y)zEAsync wrapper around :class:`ReadWriteLock` for use with ``asyncio``.    )annotationsN)ThreadPoolExecutor)asynccontextmanager)TYPE_CHECKING	ParamSpecTypeVar   )_append_exception_context_ensure_current_process_fork_transition_raise_chained_errors_register_fork_object)_BackendOutcome_capture_call_drain_future_future_result_wait_until_done)ReadWriteLock)AsyncGeneratorCallable)futures)TracebackType)NoReturn)AcquireReturnProxy_P_Rc                  z   e Zd ZdZ	 dddddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZed d       Zed!d       Zed"d       Zed#d	       Z	ed$d
       Z
ed%ddd&d       Zed%ddd&d       Zd'dZdddd(dZdddd(dZddd)dZd*dZd+dZd,dZ	 	 	 	 	 	 	 	 d-dZed.d       Zd*dZed"d       Zd*dZd*dZd*dZy)/AsyncReadWriteLocka  
    Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications.

    This wrapper dispatches every blocking SQLite operation to a thread pool via ``loop.run_in_executor()`` because
    Python's :mod:`sqlite3` module has no async API. It delegates reentrancy, upgrade/downgrade rules, and singleton
    behavior to the underlying :class:`ReadWriteLock`.

    :param lock_file: path to the SQLite database file used as the lock
    :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
    :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
    :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path
    :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop
    :param executor: executor for ``run_in_executor``. When ``None`` this lock creates and owns a dedicated
        single-thread executor so every operation runs on the same thread (SQLite affinity requires this) and shuts it
        down in :meth:`close`. This lock uses a caller-supplied executor as-is and never shuts it down, so after passing
        no executor call :meth:`close` to release the owned one.

    .. versionadded:: 3.21.0

    TN)blockingis_singletonloopexecutorc               f   t        j                         }|| _        d| _        d| _        t        |        t               5  t        ||||      | _        || _	        |d u | _
        |xs t        d      | _        t        j                         |k7  rd}t        |      	 d d d        y # 1 sw Y   y xY w)NF)r   r    r	   )max_workersz:AsyncReadWriteLock construction cannot continue after fork)osgetpid_creator_pid_fork_invalidated_closedr   r   r   _lock_loop_owns_executorr   	_executorRuntimeError)	self	lock_filetimeoutr   r    r!   r"   creator_pidmsgs	            M/root/.hermes/venv/lib/python3.12/site-packages/filelock/_async_read_write.py__init__zAsyncReadWriteLock.__init__9   s     iik'!&d# 	(&y'H[ghDJDJ"*d"2D%J);)JDNyy{k)R"3'' *	( 	( 	(s   AB''B0c                .    | j                   j                  S )zThe path to the lock file.)r*   r0   r/   s    r4   r0   zAsyncReadWriteLock.lock_fileQ   s     zz###    c                .    | j                   j                  S )zThe default timeout.)r*   r1   r7   s    r4   r1   zAsyncReadWriteLock.timeoutV   s     zz!!!r8   c                .    | j                   j                  S )z'Whether blocking is enabled by default.)r*   r   r7   s    r4   r   zAsyncReadWriteLock.blocking[   s     zz"""r8   c                    | j                   S )z2The event loop (or ``None`` for the running loop).)r+   r7   s    r4   r!   zAsyncReadWriteLock.loop`   s     zzr8   c                    | j                   S )z_The executor used for ``run_in_executor`` (a dedicated single-thread one if none was supplied).)r-   r7   s    r4   r"   zAsyncReadWriteLock.executore   s     ~~r8   r   c              T  K   || j                   j                  }|| j                   j                  }| j                  ||       d{    d}	 d 	 | j                  |       d{    y7 '# t        $ r}|} d}~ww xY w7 # | j                  |       d{  7   w xY ww)a  
        Async context manager that acquires and releases a shared read lock.

        Falls back to instance defaults for *timeout* and *blocking* when ``None``.

        :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
        :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default

        Nr=   )r*   r1   r   acquire_readBaseException_release_in_contextr/   r1   r   
body_errorerrors        r4   	read_lockzAsyncReadWriteLock.read_lockj   s      ?jj((Gzz**H(;;;+/
	7
 **:666 	<  	J	 7$**:666`   AB(	A1
B(A3 B(+B,B(3	B<A??BB	 B(	B%B!B%%B(c              T  K   || j                   j                  }|| j                   j                  }| j                  ||       d{    d}	 d 	 | j                  |       d{    y7 '# t        $ r}|} d}~ww xY w7 # | j                  |       d{  7   w xY ww)a  
        Async context manager that acquires and releases an exclusive write lock.

        Falls back to instance defaults for *timeout* and *blocking* when ``None``.

        :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
        :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default

        Nr=   )r*   r1   r   acquire_writer@   rA   rB   s        r4   
write_lockzAsyncReadWriteLock.write_lock   s      ?jj((Gzz**H  8 <<<+/
	7
 **:666 	=  	J	 7$**:666rF   c                   K   	 | j                          d {    y 7 # t        $ r}|t        ||        d }~ww xY wwN)releaser@   r
   )r/   rC   release_errors      r4   rA   z&AsyncReadWriteLock._release_in_context   s<     	,,.   	%)-D	s(   ?  ? 	<7<?c                  K   | j                          | j                  t        j                  | j                  j
                  ||             d{    t        |       S 7 w)a7  
        Acquire a shared read lock.

        See :meth:`ReadWriteLock.acquire_read` for full semantics.

        :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
        :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable

        :returns: a proxy that can be used as an async context manager to release the lock

        :raises RuntimeError: if a write lock is already held on this instance
        :raises Timeout: if the lock cannot be acquired within *timeout* seconds

        r=   Nlock)_raise_if_unusable_run_acquire	functoolspartialr*   r?    AsyncAcquireReadWriteReturnProxyr/   r1   r   s      r4   r?   zAsyncReadWriteLock.acquire_read   sS      	!	 1 1$**2I2I7]e fggg/T:: 	h   AA$A"A$c                  K   | j                          | j                  t        j                  | j                  j
                  ||             d{    t        |       S 7 w)aZ  
        Acquire an exclusive write lock.

        See :meth:`ReadWriteLock.acquire_write` for full semantics.

        :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
        :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable

        :returns: a proxy that can be used as an async context manager to release the lock

        :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
        :raises Timeout: if the lock cannot be acquired within *timeout* seconds

        r=   NrO   )rQ   rR   rS   rT   r*   rH   rU   rV   s      r4   rH   z AsyncReadWriteLock.acquire_write   sS      	!	 1 1$**2J2JG^f ghhh/T:: 	irW   Fforcec                  K   t                | j                  ry| j                  | j                  j                  |       d{    y7 w)a2  
        Release one level of the current lock.

        See :meth:`ReadWriteLock.release` for full semantics.

        :param force: if ``True``, release the lock completely regardless of the current lock level

        :raises RuntimeError: if no lock is currently held and *force* is ``False``

        NrY   )r   
_inherited_runr*   rL   )r/   rZ   s     r4   rL   zAsyncReadWriteLock.release   s8      	 !??ii

**%i888s   AAA
Ac                  K   t                | j                  ry| j                  ry| j                  | j                  j
                        }	 t        |       d{    t        |       d| _        | j                          y7 '# t        j                  $ r[}	 t        |       d{  7   n(# t        $ r}| j                  ||       Y d}~nd}~ww xY wd| _        | j                           d}~ww xY ww)z
        Release the lock (if held) and close the underlying SQLite connection.

        After calling this method, the lock instance is no longer usable.

        NT)r   r\   r)   _submitr*   closer   asyncioCancelledErrorr   r@   _raise_cancelled_error_shutdown_owned_executorr   )r/   close_futurecancellationrD   s       r4   r`   zAsyncReadWriteLock.close   s      	 !??<<||DJJ$4$45		"<000 	|$%%' 1%% 	A#L111  A++L%@@ADL))+	sl   A
C6B BB  #C6B C3B.'B*(B.-C..	C7C	C.CC..C33C6c                >  K   | j                  |      }	 t        |       d {    t        |       y 7 # t        j                  $ r}	 t	        |       d {  7   nU# t        j                  $ r}| j                  ||       Y d }~n+d }~wt        $ r}| j                  ||       Y d }~nd }~ww xY w	 t	        | j                  | j                  j                               d {  7    # t        $ r}| j                  ||       Y d }~ d }~ww xY wd }~ww xY wwrK   )
r_   r   ra   rb   r   rc   r@   r*   rL   r   )r/   acquireacquire_futurerf   acquire_errorrD   s         r4   rR   zAsyncReadWriteLock._run_acquire   s     g.	">222 	~& 3%% 	A#N333)) I++L-HH  A++L%@@AA#DLL1C1C$DEEE  ! A++L%@@A	s   D6 46 D6 D
AAADB12B	D	B1B,'D,B11D51C-&C)'C-,D-	D6DDDDDDc                *  K    | j                   |g|i |}	 t        |       d {    t        |      S 7 # t        j                  $ rC}	 t	        |       d {  7    # t
        $ r}| j                  ||       Y d }~ d }~ww xY wd }~ww xY wwrK   )r_   r   ra   rb   r   r@   rc   r   )r/   funcargskwargsfuturerf   rD   s          r4   r]   zAsyncReadWriteLock._run  s     d4T4V4	"6*** f%% +%% 	A#F+++  ! A++L%@@A	sa   B: 8: B: BA#AA#"B#	B,B>BBBBBc           	         | j                   xs t        j                         j                  | j                  t
        t        j                  |g|i |      S rK   )r+   ra   get_running_looprun_in_executorr-   r   rS   rT   )r/   rl   rm   rn   s       r4   r_   zAsyncReadWriteLock._submit  sK     

8g668IINNd4T4V4
 	
r8   c                    |j                   x}%|| ur!| j                   x}t        ||       || _         | |_         t        |       y rK   )__context__r
   r   )rf   rD   contextcancellation_contexts       r4   rc   z)AsyncReadWriteLock._raise_cancelled_error  sO    (((G5':U(4(@(@@$M)'3GH'.L$(e$r8   c                V    | j                   r| j                  j                  d       y y )NFwait)r,   r-   shutdownr7   s    r4   rd   z+AsyncReadWriteLock._shutdown_owned_executor%  s%    NN###/ r8   c                `    | j                   xs! t        j                         | j                  k7  S rK   )r(   r%   r&   r'   r7   s    r4   r\   zAsyncReadWriteLock._inherited)  s$    %%I8I8I)IIr8   c                    t                | j                  rd| j                   d}t        |      | j                  rd}t        j                  |      y )NzAsyncReadWriteLock on z4 was invalidated by fork(); construct a new instancez$Cannot operate on a closed database.)r   r\   r0   r.   r)   sqlite3ProgrammingError)r/   r3   s     r4   rQ   z%AsyncReadWriteLock._raise_if_unusable-  sP    !??*4>>*::noCs##<<8C**3// r8   c                    d| _         y )NT)r(   r7   s    r4   _reset_after_fork_in_childz-AsyncReadWriteLock._reset_after_fork_in_child6  s
    !%r8   c                    t        j                         t        | dd       k(  r+t        | dd      r| j                  j	                  d       y y y )Nr'   r,   Frx   )r%   r&   getattrr-   rz   r7   s    r4   __del__zAsyncReadWriteLock.__del__9  sG     99;'$=='$P`bgBhNN###/ Ci=r8   ))r0   zstr | os.PathLike[str]r1   floatr   boolr    r   r!    asyncio.AbstractEventLoop | Noner"   zfutures.Executor | NonereturnNone)r   str)r   r   )r   r   )r   r   )r   zfutures.ExecutorrK   )r1   zfloat | Noner   zbool | Noner   zAsyncGenerator[None])rC   BaseException | Noner   r   )r1   r   r   r   r   rU   )rZ   r   r   r   )r   r   )rh   z Callable[[], AcquireReturnProxy]r   r   )rl   Callable[_P, _R]rm   _P.argsrn   	_P.kwargsr   r   )rl   r   rm   r   rn   r   r   z#asyncio.Future[_BackendOutcome[_R]])rf   zasyncio.CancelledErrorrD   r@   r   r   )__name__
__module____qualname____doc__r5   propertyr0   r1   r   r!   r"   r   rE   rI   rA   r?   rH   rL   r`   rR   r]   r_   staticmethodrc   rd   r\   rQ   r   r    r8   r4   r   r   #   s   0 (
 !15,0()( (
 ( ( /( *( 
(0 $ $ " " # #     7W[ 7 70 7X\ 7 70;$ ;&;4 ;& .3 9 (6'$
&
$
-4
@I
	,
 % %0 J J0&0r8   r   c                  8    e Zd ZdZddZddZ	 	 	 	 	 	 	 	 ddZy)	rU   zEContext-aware object that releases the async read/write lock on exit.c                    || _         y rK   rO   )r/   rP   s     r4   r5   z)AsyncAcquireReadWriteReturnProxy.__init__C  s	    	r8   c                "   K   | j                   S wrK   rO   r7   s    r4   
__aenter__z+AsyncAcquireReadWriteReturnProxy.__aenter__F  s     yys   c                T   K   | j                   j                          d {    y 7 wrK   )rP   rL   )r/   exc_type	exc_value	tracebacks       r4   	__aexit__z*AsyncAcquireReadWriteReturnProxy.__aexit__I  s      ii!!!s   (&(N)rP   r   r   r   )r   r   )r   ztype[BaseException] | Noner   r   r   zTracebackType | Noner   r   )r   r   r   r   r5   r   r   r   r8   r4   rU   rU   @  s:    O"," (" (	"
 
"r8   rU   )+r   
__future__r   ra   rS   r%   r}   concurrent.futuresr   
contextlibr   typingr   r   r   _apir
   r   r   r   r   _asyncr   r   r   r   r   _read_writer   collections.abcr   r   
concurrentr   typesr   r   r   r   r   r   rU   __all__r   r8   r4   <module>r      s    K "   	  1 * 4 4  d c &8"#(t_T]Z0 Z0z" "& 'r8   