
    \j0                    j   d dl m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 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mZ er,d dlZd dlm Z  ddl!m"Z" ejF                  dk\  rd dlm$Z$ nd dl%m$Z$ ed   Z&ed   Z' ed       G d d             Z( G d de      Z)g dZ*y)    )annotationsN)suppress)	dataclass)EventThreadcurrent_thread)TYPE_CHECKINGLiteral   )LeaseSettingsMismatch)owner_is_stale)MarkerSoftFileLock	OwnerModeOwnerRecordparse_marker)_read_lock_file)break_lock_filetouch)Callable)LockOptions)      )Unpack)marker-missingowner-changedrefresh-failed)oklost	transientT)frozenc                  >    e Zd ZU dZded<   ded<   ded<   dZded	<   y)
LeaseCompromisez6Why a held lease stopped being this process's to hold.str	lock_filetokenCompromiseReasonreasonNOSError | Noneerror)__name__
__module____qualname____doc____annotations__r)        B/root/.hermes/venv/lib/python3.12/site-packages/filelock/_lease.pyr"   r"   !   s    @NJ E> r0   r"   c                      e Zd ZU dZdZded<   dZded<   dZd	ed
<   dddd	 	 	 	 	 	 	 	 	 	 	 d fdZe	dd       Z
e	dd       Ze	dd       Zd  fdZd  fdZd! fdZd  fdZd"dZd#dZd dZd#dZd$dZd%dZ xZS )&SoftFileLeasea  
    Existence lock whose claim expires, so a peer may take it while the previous holder still runs.

    A lease trades mutual exclusion for progress. The holder publishes a claim and refreshes it every
    ``heartbeat_interval`` seconds; a contender takes the marker once it is ``lease_duration`` seconds stale. Nothing
    stops the expired holder: it keeps running, and it keeps using whatever the lock protects. Treat the lease as a hint
    about who *should* be working, not as a guarantee that only one worker is.

    To make a protected resource reject a superseded holder, that resource must be linearizable and must fence on a
    monotonic generation it controls. :attr:`token` names a claim; it does not fence one. Where overlap is unacceptable,
    use :class:`StrictSoftFileLock <filelock.StrictSoftFileLock>` instead.

    Every contender for a path must agree on ``lease_duration``. A contender that finds a claim published under a
    different duration raises :class:`LeaseSettingsMismatch <filelock.LeaseSettingsMismatch>` rather than apply its own
    expiry to a peer that never agreed to it.

    Expiry reclaims less on Windows, which refuses to rename or delete a file another process holds open. A peer there
    takes an expired claim only once the previous holder's process exits and its handle closes; a holder that lives on
    but stops refreshing keeps the marker. Unix reclaims the marker either way.

    ``on_compromise`` fires from the heartbeat thread when a refresh fails, or when the marker vanishes or names another
    owner. The holder should stop touching the protected resource when it runs. Because it runs on that thread, a
    ``release()`` inside it only takes effect when the lease was built with ``thread_local=False``; the default
    thread-local context hides the claim from every thread but the one that acquired it, so the release does nothing.
    Signal the acquiring thread instead when the context stays thread-local.

    .. versionadded:: 3.30.0

    leaser   _owner_modeFbool_lifetime_supportedz(lease_duration sets when a lease expiresr#   _lifetime_unsupported_reasong      >@N)lease_durationheartbeat_intervalon_compromisec               
   |dk  rd|}t        |      ||dz  }d|cxk  r|k  sn d|}t        |      t        |   |fi | || _        || _        || _        d| _        d| _        t               | _	        d| _
        y)a  
        Create a lease.

        :param lease_duration: seconds of marker staleness after which a contender may take the claim. Every contender
            for the path must pass the same value.
        :param heartbeat_interval: seconds between refreshes. Defaults to a third of ``lease_duration``, leaving room
            for two missed refreshes before a peer may take the claim. Must be shorter than ``lease_duration``.
        :param on_compromise: called from the heartbeat thread with a :class:`LeaseCompromise` when the claim is lost.
        :param kwargs: every other :class:`BaseFileLock <filelock.BaseFileLock>` option, ``timeout`` and ``mode`` among
            them. The metaclass passes them all by keyword, and taking them here lets
            :class:`AsyncSoftFileLease <filelock.AsyncSoftFileLease>` add the async plumbing a fixed signature would
            hide.

        r   z%lease_duration must be positive, got Nr   zBheartbeat_interval must be positive and below lease_duration, got )
ValueErrorsuper__init___lease_duration_heartbeat_interval_on_compromise_token_compromiser   _heartbeat_stop
_heartbeat)selfr$   r9   r:   r;   kwargsmsg	__class__s          r1   r?   zSoftFileLease.__init__P   s    . Q9.9KLCS/!%!/!!3%66VWiVlmCS/!-f--#5 +"&37$w)-r0   c                    | j                   S )zEThe staleness in seconds after which a contender may take this claim.)r@   rG   s    r1   r9   zSoftFileLease.lease_durationx   s     ###r0   c                    | j                   S )z
        The token naming the claim this process published.

        :returns: the token while the lease is held, ``None`` otherwise. It identifies a claim; it does not fence one.

        )rC   rL   s    r1   r%   zSoftFileLease.token}   s     {{r0   c                    | j                   S )z
        The loss of claim the heartbeat observed.

        :returns: the :class:`LeaseCompromise`, or ``None`` while the claim still holds

        )rD   rL   s    r1   
compromisezSoftFileLease.compromise   s     r0   c                $   | j                          t        j                  d      | _        d | _        t
        |           | j                  j                  x}8| j                  j                  x}	 | j                  ||| j                         y y y )N   )_stop_heartbeatsecrets	token_hexrC   rD   r>   _acquire_contextlock_file_fdlock_file_fd_identity_start_heartbeat)rG   fdidentityrJ   s      r1   rU   zSoftFileLease._acquire   s    ''+ --,,,B9;;;H? !!"h<?9r0   c                P    | j                          d | _        t        |           y N)rR   rC   r>   _releaserG   rJ   s    r1   r^   zSoftFileLease._release   s!    r0   c                j    t         |          j                  | j                  | j                        S )N)r%   r9   )r>   _published_record_replacerC   r@   r_   s    r1   ra   zSoftFileLease._published_record   s,    w(*33$++VZVjVj3kkr0   c                d   | j                         x}t        | 	          y |\  }}}|j                  dk7  ry |j                  | j
                  k7  r4| j                   d|j                  d| j
                  d}t        |      t        t              5  t        |j                  |j                  |j                        r!t        | j                  ||       	 d d d        y t        j                         |z
  | j
                  k\  rt        | j                  ||       d d d        y # 1 sw Y   y xY w)Nr4   z holds a lease of z s but this contender configured z:s; every contender for a path must agree on lease_duration)
_read_peerr>   _try_break_stale_lockmoder9   r@   r$   r   r   OSErrorr   pidhostnamestartr   time)rG   peerownermtimeinorI   rJ   s         r1   re   z#SoftFileLease._try_break_stale_lock   s   OO%%D.
 G)+ uc :: 4#7#77>>""4U5I5I4LLl''**df  (,, g 	< eiiEs;	< 	< yy{U"d&:&::s;	< 	< 	<s   AD&";D&&D/c                    t        t        t              5  t        | j                        \  }}}t        |      x}|||fcd d d        S 	 d d d        y # 1 sw Y   y xY wr]   )r   rg   r=   r   r$   r   )rG   contentrn   ro   rm   s        r1   rd   zSoftFileLease._read_peer   sb    gz* 	)"1$.."AGUC%g..;eS(	) 	);	) 		) s   +AAc                    t               | _        t        | j                  |||fdt	        j
                          d      | _        | j                  j                          y )Nzfilelock-lease-T)targetargsnamedaemon)r   rE   r   _refresh_until_stoppedosgetpidrF   rj   )rG   rZ   r[   r%   s       r1   rY   zSoftFileLease._start_heartbeat   sP    $w ..h&"299;-0	
 	r0   c                    | j                   x}y | j                  j                          d | _         |t               ur|j	                  | j
                         y y )N)timeout)rF   rE   setr   joinrA   )rG   	heartbeats     r1   rR   zSoftFileLease._stop_heartbeat   sQ    (I1  "N,,NN4#;#;N< -r0   c                   t        j                         }| j                  j                  | j                        s| j                  |||      \  }}|dk(  ry |dk(  rt        j                         }nEt        j                         |z
  | j                  | j                  z
  k\  r| j                  d||       y | j                  j                  | j                        sy y )Nr   r   r   )rk   	monotonicrE   waitrA   _refresh_claimr@   _report_compromise)rG   rZ   r[   r%   last_successoutcomer)   s          r1   rw   z$SoftFileLease._refresh_until_stopped   s     ~~'&&++D,D,DE!00XuENGU& $#~~/!L0D4H4H4KcKc4cc''(8%G &&++D,D,DEr0   c                   	 t        j                  | j                        }|j                  |j                  f|k7  r| j	                  dd |       y	 t        | j                  |       y# t        $ r}| j	                  d||       Y d }~yd }~wt
        $ r}d|fcY d }~S d }~ww xY w# t
        $ r}d|fcY d }~S d }~ww xY w)Nr   )r   Nr   r   )rZ   )r   N)	rx   lstatr$   FileNotFoundErrorr   rg   st_devst_inor   )rG   rZ   r[   r%   str)   s         r1   r   zSoftFileLease._refresh_claim   s    	&$..)B IIryy!X-##OT5A	&$..R(  ! 	 ##$4eUC 	&%%	&  	&%%	&sG   A) B' )	B$2B

B$BB$B$'	B>0B93B>9B>c                    t        | j                  |||      | _        | j                  | j                  | j                         y y )N)r$   r%   r'   r)   )r"   r$   rD   rB   )rG   r'   r)   r%   s       r1   r   z SoftFileLease._report_compromise   s@    *T^^5Y_glm* 0 01 +r0   )r$   zstr | os.PathLike[str]r9   floatr:   zfloat | Noner;   z(Callable[[LeaseCompromise], None] | NonerH   zUnpack[LockOptions]returnNone)r   r   )r   z
str | None)r   zLeaseCompromise | None)r   r   )r   r   )r   z%tuple[OwnerRecord, float, int] | None)rZ   intr[   tuple[int, int]r%   r#   r   r   )rZ   r   r[   r   r%   r#   r   z&tuple[_RefreshOutcome, OSError | None])r'   r&   r)   r(   r%   r#   r   r   )r*   r+   r,   r-   r5   r.   r7   r8   r?   propertyr9   r%   rO   rU   r^   ra   re   rd   rY   rR   rw   r   r   __classcell__)rJ   s   @r1   r3   r3   +   s    < %K$ !&%(R #R !%+/BF&.)&. 	&.
 )&. @&. &&. 
&.P $ $      
=
l<< ="$2r0   r3   )r&   r"   r3   )+
__future__r   rx   rS   rk   
contextlibr   dataclassesr   	threadingr   r   r   typingr	   r
   _errorr   	_identityr   _markerr   r   r   r   _softr   _utilr   r   syscollections.abcr   _apir   version_infor   typing_extensionsr&   _RefreshOutcomer"   r3   __all__r/   r0   r1   <module>r      s    " 	    ! 3 3 ) ) % M M " )(!
7"!,NO 34 $! ! !Y2& Y2xr0   