
    xj4                    F   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 dd	lmZ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$  ed          Z% ed          Z& G d d          Z' G d d          Z(ddgZ)dS )zEAsync wrapper around :class:`ReadWriteLock` for use with ``asyncio``.    )annotationsN)ThreadPoolExecutor)asynccontextmanager)TYPE_CHECKING	ParamSpecTypeVar   )_append_exception_context_ensure_current_process_fork_transition_register_fork_object)_BackendOutcome_capture_call_drain_future_future_result_raise_cancelled_error_wait_until_done)ReadWriteLock)AsyncGeneratorCallable)futures)TracebackType)AcquireReturnProxy_P_Rc                  p   e Zd ZdZ	 d>dddddd?dZed@d            ZedAd            ZedBd            ZedCd            Z	edDd            Z
edEdddFd            ZedEdddFd             ZdGd#Zd>dddHd%Zd>dddHd&Zd'd(dId*ZdJd+ZdKd.ZdLd6ZdMd8ZdJd9ZedBd:            ZdJd;ZdJd<ZdJd=ZdS )N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executor	lock_filestr | os.PathLike[str]timeoutfloatr   boolr    r!    asyncio.AbstractEventLoop | Noner"   futures.Executor | NonereturnNonec                  t          j                    }|| _        d| _        d| _        t          |            t                      5  t          ||||          | _        || _	        |d u | _
        |pt          d          | _        t          j                    |k    rd}t          |          	 d d d            d S # 1 swxY w Y   d S )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)	selfr#   r%   r   r    r!   r"   creator_pidmsgs	            `/home/agent/.hermes/hermes-agent/venv/lib/python3.11/site-packages/filelock/_async_read_write.py__init__zAsyncReadWriteLock.__init__>   s    ikk'!&d### 	( 	(&y'H[ghhhDJDJ"*d"2D%J);)J)J)JDNy{{k))R"3''' *	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   A(B<<C C strc                    | j         j        S )zThe path to the lock file.)r3   r#   r8   s    r;   r#   zAsyncReadWriteLock.lock_fileV   s     z##    c                    | j         j        S )zThe default timeout.)r3   r%   r?   s    r;   r%   zAsyncReadWriteLock.timeout[   s     z!!r@   c                    | j         j        S )z'Whether blocking is enabled by default.)r3   r   r?   s    r;   r   zAsyncReadWriteLock.blocking`   s     z""r@   c                    | j         S )z2The event loop (or ``None`` for the running loop).)r4   r?   s    r;   r!   zAsyncReadWriteLock.loope   s     zr@   futures.Executorc                    | j         S )z_The executor used for ``run_in_executor`` (a dedicated single-thread one if none was supplied).)r6   r?   s    r;   r"   zAsyncReadWriteLock.executorj   s     ~r@   r   float | Nonebool | NoneAsyncGenerator[None]c              0  K   || j         j        }|| j         j        }|                     ||           d{V  d}	 dW V  n# t          $ r}|} d}~ww xY w	 |                     |           d{V  dS # |                     |           d{V  w xY 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

        NrF   )r3   r%   r   acquire_readBaseException_release_in_contextr8   r%   r   
body_errorerrors        r;   	read_lockzAsyncReadWriteLock.read_locko   s       ?j(Gz*H(;;;;;;;;;+/
	7EEEEE 	 	 	J	 
 **:66666666666$**:6666666666)   A A8 
AAAA8 8Bc              0  K   || j         j        }|| j         j        }|                     ||           d{V  d}	 dW V  n# t          $ r}|} d}~ww xY w	 |                     |           d{V  dS # |                     |           d{V  w xY 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

        NrF   )r3   r%   r   acquire_writerL   rM   rN   s        r;   
write_lockzAsyncReadWriteLock.write_lock   s       ?j(Gz*H  8 <<<<<<<<<+/
	7EEEEE 	 	 	J	 
 **:66666666666$**:6666666666rR   rO   BaseException | Nonec                   K   	 |                                   d {V  d S # t          $ r}|t          ||            d }~ww xY wN)releaserL   r
   )r8   rO   release_errors      r;   rM   z&AsyncReadWriteLock._release_in_context   si      	,,..          	 	 	%)-DDD	s     
A=A AsyncAcquireReadWriteReturnProxyc                  K   |                                   |                     t          j        | j        j        ||                     d{V  t          |           S )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

        rF   Nlock)_raise_if_unusable_run_acquire	functoolspartialr3   rK   r[   r8   r%   r   s      r;   rK   zAsyncReadWriteLock.acquire_read   si       	!!!	 1$*2I7]e f f fggggggggg/T::::r@   c                  K   |                                   |                     t          j        | j        j        ||                     d{V  t          |           S )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

        rF   Nr]   )r_   r`   ra   rb   r3   rT   r[   rc   s      r;   rT   z AsyncReadWriteLock.acquire_write   si       	!!!	 1$*2JG^f g g ghhhhhhhhh/T::::r@   Fforcerf   c                  K   t                       | j        rdS |                     | j        j        |           d{V  dS )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``

        Nre   )r   
_inherited_runr3   rY   )r8   rf   s     r;   rY   zAsyncReadWriteLock.release   sV       	 !!!? 	Fii
*%i88888888888r@   c                F  K   t                       | j        rdS | j        rdS |                     | j        j                  }	 t          |           d{V  nq# t          j        $ r_}	 t          |           d{V  n'# t          $ r}t          ||           Y d}~nd}~ww xY wd| _        |                                   d}~ww xY wt          |           d| _        | j        r:t          j        t!          j        | j        j        d                     d{V  dS dS )z
        Release the lock (if held) and close the underlying SQLite connection.

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

        NTwait)r   rh   r2   _submitr3   closer   asyncioCancelledErrorr   rL   r   _shutdown_owned_executorr   r5   	to_threadra   rb   r6   shutdown)r8   close_futurecancellationrP   s       r;   rn   zAsyncReadWriteLock.close   s      	 !!!? 	F< 	F||DJ$455		"<0000000000% 	 	 	<#L1111111111  < < <&|U;;;;;;;;<DL))+++	 	|$$$  	[#I$5dn6MTX$Y$Y$YZZZZZZZZZZZ	[ 	[s<   A C)A?>C?
B#	BCB##CCacquire Callable[[], AcquireReturnProxy]c                  K   |                      |          }	 t          |           d {V  n# t          j        $ r}	 t	          |           d {V  n'# t
          $ r}t          ||           Y d }~nd }~ww xY w	 t	          |                      | j        j                             d {V  n'# t
          $ r}t          ||           Y d }~nd }~ww xY w d }~ww xY wt          |           d S rX   )
rm   r   ro   rp   r   rL   r   r3   rY   r   )r8   rv   acquire_futureru   rP   s        r;   r`   zAsyncReadWriteLock._run_acquire   sW     g..	">2222222222% 		 		 		<#N3333333333  < < <&|U;;;;;;;;<<#DLL1C$D$DEEEEEEEEEE  < < <&|U;;;;;;;;<		 	~&&&&&sb   / CAC
A9A4/C4A99C=2B0/C0
C:C
CCCCfuncCallable[_P, _R]args_P.argskwargs	_P.kwargsr   c                   K    | j         |g|R i |}	 t          |           d {V  nV# t          j        $ rD}	 t	          |           d {V  n'# t
          $ r}t          ||           Y d }~nd }~ww xY w d }~ww xY wt          |          S rX   )rm   r   ro   rp   r   rL   r   r   )r8   rz   r|   r~   futureru   rP   s          r;   ri   zAsyncReadWriteLock._run  s      d4T444V44	"6**********% 	 	 	<#F++++++++++  < < <&|U;;;;;;;;<	 f%%%s8   + A>AA9
A5A0+A90A55A99A>#asyncio.Future[_BackendOutcome[_R]]c           	         | j         pt          j                                        | j        t
          t          j        |g|R i |          S rX   )r4   ro   get_running_looprun_in_executorr6   r   ra   rb   )r8   rz   r|   r~   s       r;   rm   zAsyncReadWriteLock._submit  sR     
8g688IINd4T444V44
 
 	
r@   c                N    | j         r| j                            d           d S d S )NFrk   )r5   r6   rs   r?   s    r;   rq   z+AsyncReadWriteLock._shutdown_owned_executor"  s6     	0N###/////	0 	0r@   c                H    | j         pt          j                    | j        k    S rX   )r1   r.   r/   r0   r?   s    r;   rh   zAsyncReadWriteLock._inherited&  s    %I8I)IIr@   c                    t                       | j        rd| j         d}t          |          | j        rd}t          j        |          d S )NzAsyncReadWriteLock on z4 was invalidated by fork(); construct a new instancez$Cannot operate on a closed database.)r   rh   r#   r7   r2   sqlite3ProgrammingError)r8   r:   s     r;   r_   z%AsyncReadWriteLock._raise_if_unusable*  sb    !!!? 	$o4>oooCs###< 	08C*3///	0 	0r@   c                    d| _         d S )NT)r1   r?   s    r;   _reset_after_fork_in_childz-AsyncReadWriteLock._reset_after_fork_in_child3  s    !%r@   c                    t          j                    t          | dd           k    r.t          | dd          r| j                            d           d S d S d S )Nr0   r5   Frk   )r.   r/   getattrr6   rs   r?   s    r;   __del__zAsyncReadWriteLock.__del__6  sa     9;;'$===='$P`bgBhBh=N###///// >===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*   rD   rX   )r%   rG   r   rH   r*   rI   )rO   rV   r*   r+   )r%   r&   r   r'   r*   r[   )rf   r'   r*   r+   )r*   r+   )rv   rw   r*   r+   )rz   r{   r|   r}   r~   r   r*   r   )rz   r{   r|   r}   r~   r   r*   r   )__name__
__module____qualname____doc__r<   propertyr#   r%   r   r!   r"   r   rQ   rU   rM   rK   rT   rY   rn   r`   ri   rm   rq   rh   r_   r   r    r@   r;   r   r   (   s        0 (
 !15,0( ( ( ( ( (0 $ $ $ X$ " " " X" # # # X#    X    X 7W[ 7 7 7 7 7 70 7X\ 7 7 7 7 7 70   ;$ ; ; ; ; ; ;&;4 ; ; ; ; ; ;& .3 9 9 9 9 9 9 [ [ [ [<' ' ' ' 
& 
& 
& 
&
 
 
 
0 0 0 0 J J J XJ0 0 0 0& & & &0 0 0 0 0 0r@   r   c                  *    e Zd ZdZddZddZddZdS )r[   zEContext-aware object that releases the async read/write lock on exit.r^   r   r*   r+   c                    || _         d S rX   r]   )r8   r^   s     r;   r<   z)AsyncAcquireReadWriteReturnProxy.__init__@  s    			r@   c                   K   | j         S rX   r]   r?   s    r;   
__aenter__z+AsyncAcquireReadWriteReturnProxy.__aenter__C  s      yr@   exc_typetype[BaseException] | None	exc_valuerV   	tracebackTracebackType | Nonec                H   K   | j                                          d {V  d S rX   )r^   rY   )r8   r   r   r   s       r;   	__aexit__z*AsyncAcquireReadWriteReturnProxy.__aexit__F  s4       i!!!!!!!!!!!r@   N)r^   r   r*   r+   )r*   r   )r   r   r   rV   r   r   r*   r+   )r   r   r   r   r<   r   r   r   r@   r;   r[   r[   =  sV        OO      " " " " " "r@   r[   )*r   
__future__r   ro   ra   r.   r   concurrent.futuresr   
contextlibr   typingr   r   r   _apir
   r   r   r   _asyncr   r   r   r   r   r   _read_writer   collections.abcr   r   
concurrentr   typesr   r   r   r   r   r[   __all__r   r@   r;   <module>r      s   K K " " " " " "      				  1 1 1 1 1 1 * * * * * * 4 4 4 4 4 4 4 4 4 4                           ' & & & & & )88888888""""""######((((((Yt__WT]]R0 R0 R0 R0 R0 R0 R0 R0j" " " " " " " "& 'r@   