
    \jQ?                      U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dl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 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"m#Z# d d
l$m%Z%m&Z& ddl'm(Z(m)Z) ddl*m+Z+ dZ,de-d<   dZ.de-d<   ed   Z/ e0ddh      Z1de-d<   ed   Z2 e0h d      Z3de-d<   erfd dlm4Z4 d dl5m6Z6 d dlm7Z7 ddl8m9Z9 ddl:m;Z;  G d  d!e7      Z< G d" d#e7      Z= G d$ d%e7      Z> G d& d'e7      Z?ej                  d(k\  rd d)lmAZA nd d)lBmAZA  ej                  d*      ZDd+e-d,<    e#d- eEed.d            ZFd/e-d0<   eFduZGd1e-d2<    e"d3      ZH e"d4      ZI e"d5      ZJeKeLz  eMz  eNz  dz  eeLgdf   z  ZO G d6 d7e!d89      ZPdd:ZQdd;	 	 	 	 	 	 	 	 	 	 	 dd<ZRdd=ZSdd>ZTdd?ZUdd@ZVddAZW	 	 	 	 	 	 	 	 ddBZXer G dC dDe7      ZYdddEZZddFZ[ddGZ\	 	 	 	 	 	 	 	 ddHZ]ej                  dIk(  rej                  j                  nej                  j                  ZbdJe-dK<   ddLZc G dM dNe      Zd ed       ZedOe-dP<    e"dQdRS      Zf G dT dUe      Zg e%       ZhdVe-dW<   ddYZi edZ[       G d\ dX             Zjdd]Zkdd^Zldd_Zmdd`Zn	 	 	 	 	 	 	 	 ddaZo G db dRej                  egc      Zq G dd de      Zre G df dg             Zs G dh diese      Zt edZ[       G dj dk             Zu G dl dme      Zv G dn do      Zw e&       Zxdpe-dq<    e&       Zydre-ds<   i Zzdte-du<    e       Z{dve-dw<    e       Z|dve-dx<    ew       Z}dye-dz<    e0d{d|h      Z~de-d}<   dd~Zeddd       ZddZddZdddZddZddZddZddZddZddZddZddZddZddZddZ	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 ddZ e        g dZy)    )annotationsN)ABCMetaabstractmethod)CallableHashable)contextmanager)	dataclass)countstarmap)	ConditionRLock	get_identlocal)TYPE_CHECKINGFinalLiteralNoReturn	TypedDictTypeVarcast)WeakKeyDictionaryWeakValueDictionary   )SoftFileLockLifetimeWarningTimeout)break_lock_filez
Final[int]_UNSET_FILE_MODE   _MAX_BACKOFF_EXPONENT)chaingroupr!   r"   zFinal[frozenset[str]]_CONTEXT_ERROR_POLICIES)defaultraisesuppress>   r%   r$   r&   _CLOSE_ERROR_POLICIES)	Generator)TracebackType)Protocol)ReadWriteLock)SoftReadWriteLockc                      e Zd ZddZy)_ForkResettablec                     y N selfs    @/root/.hermes/venv/lib/python3.12/site-packages/filelock/_api.py_reset_after_fork_in_childz*_ForkResettable._reset_after_fork_in_child0           NreturnNone)__name__
__module____qualname__r5   r1   r7   r4   r.   r.   /   s    9r7   r.   c                      e Zd ZddZy)_ForkDescriptorOwnerc                     y r0   r1   r2   s    r4   _descriptors_for_forkz*_ForkDescriptorOwner._descriptors_for_fork3   r6   r7   Nr9   z.tuple[tuple[int, tuple[int, int] | None], ...])r;   r<   r=   rA   r1   r7   r4   r?   r?   2   s    ^r7   r?   c                      e Zd ZddZy)_ForkResettableClassc                     y r0   r1   r2   s    r4   _reset_class_after_forkz,_ForkResettableClass._reset_class_after_fork8   r6   r7   Nr8   )r;   r<   r=   rF   r1   r7   r4   rD   rD   7   s    6r7   rD   c                  ,    e Zd Zdddd	 	 	 	 	 	 	 ddZy)_RegisterAtForkNbeforeafter_in_parentafter_in_childc                    y r0   r1   )r3   rJ   rK   rL   s       r4   __call__z_RegisterAtFork.__call__;   s     r7   )rJ   Callable[[], None] | NonerK   rO   rL   rO   r9   r:   )r;   r<   r=   rN   r1   r7   r4   rH   rH   :   s:     159=8<	 .	 7		
 6	 	r7   rH         )SelffilelockzFinal[logging.Logger]_LOGGERz_RegisterAtFork | Noneregister_at_forkzFinal[_RegisterAtFork | None]_REGISTER_AT_FORKzFinal[bool]_HAS_REGISTER_AT_FORK_ExtraValue_MarkerValue_SubclassValuec                      e Zd ZU dZded<   ded<   ded<   ded<   ded	<   ded
<   ded<   ded<   ded<   ded<   ded<   ded<   y)LockOptionszhEvery option the metaclass forwards, so a subclass adding its own can still type what it passes through.floattimeoutintmodeboolthread_localblockingis_singletonpoll_intervalfloat | NonelifetimeContextErrorPolicycontext_error_policyCloseErrorPolicyclose_error_policyfallback_to_softpreserve_lock_fileCallable[[int], None] | Noneon_acquiredN)r;   r<   r=   __doc____annotations__r1   r7   r4   r]   r]   R   sJ    rN
IN,,((--r7   r]   F)totalc                 D    t         j                  dk\  rt        S ddlm}  | S )NrP   r   )BaseExceptionGroup)sysversion_inforu   exceptiongroup)	_Backports    r4   _exception_group_clsrz   c   s%     7"!! r7   )markerc               x    ||g|}t        |        t               | |      }|t        ||d   |d          |d )Nr   r   )_detach_grouped_contextsrz   setattr)messagefirst_errorsecond_errorr{   additional_errorserrorsr"   s          r4   _raise_grouped_errorsr   p   sP     <<*;<FV$" "7F3Evay&),
Tr7   c                   t               }t        |       }|r|j                         }t        |      |v r |j	                  t        |             |j
                  x,|u s t        |      st        fd| D              rd |_        n|j                         |j                  |j                  |j                         t        |t                     r%|j                  t        d|      j                         |ry y )Nc              3  B   K   | ]  }|u xs t        |        y wr0   )_contains_exception).0rootcontexts     r4   	<genexpr>z+_detach_grouped_contexts.<locals>.<genexpr>   s%     \T7d?H&9$&HH\s   _ExceptionGroupProtocol)setlistpopidadd__context___same_exception_treeanyappend	__cause__
isinstancerz   extendr   
exceptions)r   seenpendingerrorr   s       @r4   r}   r}      s    UD6lG
e9E(((G5u#E73\U[\\ $E NN7#??&NN5??+e134NN4 95ALLM! r7   c                R   | |fg}t               }|r|j                         \  }}||u rt        |      t        |      fx}|v r6|j                  |       t	        |      t	        |      us(t        |t                     rt        |t                     syt        d|      }t        d|      }|j                  |j                  k7  s+t        |j                        t        |j                        k7  ry|j                  t        |j                  |j                  d             |ry)NFr   T)strict)r   r   r   r   typer   rz   r   r   lenr   r   zip)	firstsecondr   r   r   r   pairfirst_groupsecond_groups	            r4   r   r      s	   vG!$D
$+KKM!\,&_b&677DD@T,%77k+?+ABl,@,BC4kB5|D,"6"66#k>T>T:UY\]i]t]tYu:us;11<3J3JSWXY# $ r7   c                z   |t        | t                     syt        t        d|       j                        }t               }|ry|j                         }||u ryt        |      |v r%|j                  t        |             t        |t                     r%|j                  t        d|      j                         |ryy)NFr   T)
r   rz   r   r   r   r   r   r   r   r   )r   targetr   r   childs        r4   r   r      s    ~Z/C/EF4159DDEGUD
F?e9Ee134NN4 95ALLM  r7   c                B   t        | |      st        ||       ry | j                  || _        y | }t               }t        |      |vrY|j	                  t        |             |j
                  |j
                  n|j                  x}||_        y |}t        |      |vrXy y r0   )_exception_graph_containsr   r   r   r   r   )r   r   tailr   
next_errors        r4   _append_exception_contextr      s     04MgW\4] #DUD
T($
D,0NN,F$..DL\L\\Je&D T($
r7   c                   | g}t               }|r|j                         }||u ryt        |      |v r%|j                  t        |             |j                  |j                  |j                         |j                  |j                  |j                         t        |t                     r%|j                  t        d|      j                         |ry)NTr   F)r   r   r   r   r   r   r   r   rz   r   r   r   r   r   r   r   currents        r4   r   r      s    gGUD
++-fg;$G(NN7,,-*NN7../g356NN4 97CNNO  r7   c                    t        | t                     sy t        d|       }|j                  |k(  r!t	        ||d   d       |d   u r|j
                  S d S )Nr   r   r   )r   rz   r   r   getattrr   )r   r   r{   r"   s       r4   _grouped_errorsr      s\     e134*E2E$}}7GE6RS9VZ<[_efg_h<h5rnrrr7   c                  0    e Zd Zedd       Zedd       Zy)r   c                     y r0   r1   r2   s    r4   r   z_ExceptionGroupProtocol.message   s    "%r7   c                     y r0   r1   r2   s    r4   r   z"_ExceptionGroupProtocol.exceptions   s    ;>r7   Nr9   str)r9   tuple[BaseException, ...])r;   r<   r=   propertyr   r   r1   r7   r4   r   r      s    	% 
%	> 
>r7   r   c                &   || j                   }	 | |j                   x}|| urt        ||        t        | |       | j                   }	 | # t        $ r	 || _          w xY w# t        $ r' || _         	 |# t        $ r | |_         || _          w xY ww xY wr0   )r   BaseException_detach_exception_contextr   )r   r   first_contextsecond_contexts       r4   _raise_chained_errorsr      s    #//	 '222?NZeDe!.+>!+~>++M	  	&3K#	  "/	 	'2L$&3K#		s)   A 	A  A B1A33BBc                   | g}t               }|r|j                         }t        |      |v r |j                  t        |             |j                  |u rd |_        n'|j                  |j                  |j                         |j                  |j                  |j                         t        |t                     r%|j                  t        d|      j                         |ry y )Nr   )r   r   r   r   r   r   r   r   rz   r   r   r   r   s        r4   r   r     s    gGUD
++-g;$G&("&G  ,NN7../(NN7,,-g356NN4 97CNNO r7   c                    t        d| |       y )Nz!lock body and release both failedr   )
body_errorrelease_errors     r4   _raise_body_and_releaser     s    
 =z=Yr7   c                ,    t        | |gd |D          y )Nc              3  &   K   | ]	  }||  y wr0   r1   )r   r   s     r4   r   z(_raise_cleanup_errors.<locals>.<genexpr>.  s     	AEu/@%	As   r   )r   primary_errorcleanup_errorss      r4   _raise_cleanup_errorsr   &  s"    
  
B^	Ar7   win32zFinal[Callable[[str], str]]_resolve_dirc                    t         j                  j                  t        j                  |             \  }}t         j                  j	                  t        |xs t         j                        |      S )a  
    Return one stable key for *path*, collapsing equivalent spellings without following a final symlink.

    Relative, absolute, and ``./`` spellings of one lock file must map to a single singleton instance, deadlock-registry
    entry, and removal key. Resolving the whole path with ``realpath`` would follow a final symlink and alias a lock
    target the backend deliberately rejects, so the registry identity would differ from the backend's. Resolving only
    the parent directory and re-appending the literal final component collapses the equivalent spellings while keeping a
    final symlink a distinct key. On Windows the parent is resolved with ``abspath`` so junctions and reparse points are
    not followed either.
    )ospathsplitfspathjoinr   curdir)r   parentnames      r4   
_canonicalr   7  sE     77==41LFD77<<V%8ryy94@@r7   c                        e Zd Zd fdZ xZS )_ThreadLocalRegistryc                0    t         |           i | _        y r0   )super__init__held)r3   	__class__s    r4   r   z_ThreadLocalRegistry.__init__G  s    )+	r7   r8   )r;   r<   r=   r   __classcell__r   s   @r4   r   r   F  s    , ,r7   r   zFinal[_ThreadLocalRegistry]	_registry_TBaseFileLock)boundc                       e Zd ZU ded<   ded<   ded<   dedfdd	d
ddddd	dd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 d fdZ xZS )FileLockMeta&WeakValueDictionary[str, BaseFileLock]
_instancesr   _instances_lockset[str]_instances_under_constructionr   TF皙?Nr!   r$   	rd   re   rf   rh   rj   rl   rm   rn   rp   c       	           t                t        || | j                        }t        |	      }	t	        |
      }
t        || j                  | j                        }t        || j                  | j                        }||||||||	|
|||d|}|s| j                  ||      S t        |      }| j                  5  | j                  j                  |      x}|| j                  v rd|}t!        |      | j                  }t#        j$                         }|j'                  |       	 | j                  ||      }|j)                  |       t#        j$                         |k7  rd}t!        |      || j                  |<   |cd d d        S 	 d d d        |j+                         f||j,                  f||j.                  j0                  f||j2                  f||j4                  f||j6                  f|	|j8                  f|
|j:                  f||j<                  f||j>                  fd
}|jA                         D ci c]  \  }\  }}||k7  r|||f }}}}||jB                  u}|s|s|S d}|d	z  }|jA                         D ]  \  }\  }}|d
| d| d| dz  } |r|d|jB                   d| dz  }tE        |      # |j)                  |       w xY w# 1 sw Y   JxY wc c}}}w )N
stacklevel)preserve	supportedcls_name)r   r   )r_   ra   rc   rd   re   rf   rh   rj   rl   rm   rn   rp   z2Singleton lock construction is already active for zOLock construction cannot continue after fork; construct a new lock in the child)
rc   r_   ra   rd   rf   rh   rj   rl   rm   rn   zGSingleton lock instances cannot be initialized with differing argumentsz
Non-matching arguments: z
	z (existing lock has z but z was passed)z!
	on_acquired (existing lock has )#_ensure_current_process_resolve_lifetime(_constructor_lifetime_warning_stacklevel_resolve_context_error_policy_resolve_close_error_policy_resolve_preserve_lock_file_preserve_lock_file_supportedr;   _resolve_on_acquired_on_acquired_supported_create_instancer   r   r   getr   RuntimeErrorr   getpidr   discardis_thread_localr_   _contextra   rd   rf   rh   rj   rl   rm   rn   itemsrp   
ValueError)cls	lock_filer_   ra   rc   rd   re   rf   rh   rj   rl   rm   rn   rp   kwargsparamssingleton_keyinstancemsgconstruction_registryconstruction_pidparams_to_checkr   passed_param	set_paramnon_matching_paramshook_mismatch
param_names                               r4   rN   zFileLockMeta.__call__W  sT   $ 	 !$Xss?k?kl  ==QR89KL8'33T3T_b_k_k
 +;#B\B\gjgsgst( (* $8"4 0"4&;
 ;
 ''	6:: #9-   	 NN..}==F C$E$EENym\C&s++(+(I(I%#%99; %))-8A"33IvFH)11-@99;"22kC&s++08}-!	  	 F	 & *8+C+C+EF!1!128,,112!8#4#45+X-C-CD!8#4#45%98;X;X$Y#5x7R7R"S!183L3L M#5x7R7R"S
 4C3H3H3J
 
//|Yy( <++
 
 $8+?+??"=OW++5H5N5N5P 	e1J1yT*%9)E,WcddC	e89M9M8NeT_S``lmmCoI *11-@	  	 <
s,   9A-K'J;9AK8K;KKKc           
        t        |       j                  rt        	|   |fi |S t	        fd|j                         D              }|r+| j                   ddj                  |       }t        |      t        	|   |fi |j                         D ci c]  \  }}|j                  v s|| c}}S c c}}w )Nc              3     K   | ]C  \  }}|j                   vr0j                  j                  |      x|j                  k7  r| E y wr0   )accepted_paramsdefault_paramsr   r$   )r   r   valuemodel	parameters      r4   r   z0FileLockMeta._create_instance.<locals>.<genexpr>  sU      
e5000$3377==)F%S\SdSdJd 
s   A	Az, does not support non-default lock options: z, )
_init_parameter_modelaccepts_kwargsr   rN   sortedr  r;   r   	TypeErrorr  )
r  r  r
  unsupportedr  r   r  r  r  r   s
          @@r4   r   zFileLockMeta._create_instance  s     &c*7#I888 
%||~
 
 \\N"NtyyYdOeNfgCC. w
.4lln^{tUH]H]@]tU{^
 	
^s   B<1B<) r  type[_T]r  str | os.PathLike[str]r_   r^   ra   r`   rc   rb   rd   rb   re   rb   rf   r^   rh   rg   rj   ri   rl   rk   rm   rb   rn   rb   rp   ro   r	  rY   r9   r   )r  r"  r  r#  r
  z'dict[str, _LockInitValue | _ExtraValue]r9   r   )r;   r<   r=   rr   r   rN   r   r   r   s   @r4   r   r   R  s    66#++
 $!e "#!%3:/8!%#(48ee)e e 	e
 e e e e e 1e -e e !e 2e  !e" 
#eN

"8
Bi
	
 
r7   r   zAFinal[WeakKeyDictionary[type[BaseFileLock], _InitParameterModel]]_INIT_PARAMETER_MODELS_InitParameterModelc                   t               5  t        j                  5  t        j	                  |       x}t        j                  | j                        j                  j                         }t        t        d |D              t        d |D              t        j                  t        |       j                        j                  j                         D ci c].  \  }}|j                   t
        j"                  j$                  ur||0 c}}      }|t        | <   |cd d d        cd d d        S c c}}w # 1 sw Y   nxY wd d d        y # 1 sw Y   y xY w)Nc              3     K   | ]P  }|j                   t        j                  j                  t        j                  j                  hv r|j
                   R y wr0   )kindinspect	ParameterPOSITIONAL_OR_KEYWORDKEYWORD_ONLYr   r   r  s     r4   r   z(_init_parameter_model.<locals>.<genexpr>  sF      *! ~~'*;*;*Q*QSZSdSdSqSq)rr NN*s   AAc              3  h   K   | ]*  }|j                   t        j                  j                  u  , y wr0   )r(  r)  r*  VAR_KEYWORDr-  s     r4   r   z(_init_parameter_model.<locals>.<genexpr>  s&     "oW`9>>W5F5F5R5R#R"os   02)r  r  r  )_fork_transition_FORK_STATEparameter_models_lockr$  r   r)  	signaturer   
parametersvaluesr%  	frozensetr   r   rN   r  r$   r*  empty)r  r  r4  r   r  s        r4   r  r    s    		 [>> +//44E= **3<<8CCJJLJ' ) *%/* !
  #"odn"oo ,3+<+<T#Y=O=O+P+[+[+a+a+c 'i ((0A0A0G0GG )O E +0"3'#       s5   E	B9D43D.D4	E	.D44D=	9E		ET)frozenc                  ,    e Zd ZU ded<   ded<   ded<   y)r%  zfrozenset[str]r  rb   r  zdict[str, inspect.Parameter]r  Nr;   r<   r=   rr   r1   r7   r4   r%  r%    s    ##00r7   c               *   | t        | t              st        | t        t        f      s#dt	        |       j
                   }t        |      | dk  s%t        | t              r%t        j                  |       sd| }t        |      | ?|j                  s3t        j                  d|j
                   d|j                   d|       y| J|j                  >|j                  \  }}t        j                  |j
                   d	| d
| dt        |       | S )ar  
    Validate ``lifetime`` and drop a value the backend cannot honor.

    ``lifetime`` is a deliberate age-based lease: a lock file older than ``lifetime`` is broken even while its holder is
    still alive. Existence locks (:class:`SoftFileLock`) implement that behavior by unlinking a reclaimable pathname,
    which can overlap a live holder. A native OS lock lives on the inode, so unlinking the pathname by age cannot revoke
    the kernel lock; a contender would lock a fresh inode and overlap the live holder (#590). Ignore the request with a
    warning rather than accept a setting that breaks mutual exclusion.
    Nz;lifetime must be a finite non-negative number or None, not r   z.lifetime must be finite and non-negative, not zlifetime is ignored for z: z2; only SoftFileLock supports lifetime-based expiryr   zH(lifetime=...) uses age-based expiry and can overlap a live holder; use z for expiry or z for fail-closed locking)r   rb   r`   r^   r   r;   r   mathisfiniter  _lifetime_supportedwarningswarn_lifetime_unsupported_reason_lifetime_replacementsr   )rh   r  r   r  strict_lockleases         r4   r   r     s    h%Z3,-OOPTU]P^PgPgOhiCC. a<Jx7h@WB8,OCS/!C$;$;&s||nBs7W7W6X Y? @!	

  : : F 77U||n '5MO'!		
 Or7   c                    | t         vrd| }t        |      | dk(  r	 t                t	        d|       S # t        $ r}d}t        |      |d }~ww xY w)Nz5context_error_policy must be 'chain' or 'group', got r"   z]context_error_policy='group' requires Python 3.11+ or the 'exceptiongroup' backport installedri   )r#   r  rz   ImportErrorr   )policyr  excs      r4   r   r     sg    ,,EfZPo	+ " $f--  	+qCS/s*	+s   
5 	AAAc                J    | t         vrd| }t        |      t        d|       S )NzBclose_error_policy must be 'default', 'raise', or 'suppress', got rk   )r'   r  r   )rG  r  s     r4   r   r   %  s1    **RSYR\]o"F++r7   c                0    | r|sd| d}t        |      | S )Nz,preserve_lock_file=True is not supported by z): unlinking its marker is how it releases)r  )r   r   r   r  s       r4   r   r   ,  s'     	<XJFopoOr7   c                   | y |sd| d}t        |      	 t                | S # t        $ r}d}t        |      |d }~ww xY w)Nz on_acquired is not supported by z.: only native locks expose the lock descriptorz^on_acquired requires Python 3.11+ or the 'exceptiongroup' backport for its rollback error path)r  rz   rF  )rp   r   r   r  rH  s        r4   r   r   5  sa      0
:hio'   'no3&'s   
$ 	A ;A c                      e Zd ZU dZded<   ded<   ded<   dZd	ed
<   dZded<   dZded<   dZd	ed<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   d_ fdZed`d       Zdedfddd dd!d"dddd#		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dad$Zdbd%Zedbd&       Zedcd'       Zeddd(       Zded)Zedbd*       Zedbd+       Zedfd,       Zedgd-       Zedhd.       Zej<                  did/       Zedbd0       Zej<                  djd1       Zedhd2       Z e j<                  dkd3       Z edld4       Z!e!j<                  dmd5       Z!ednd6       Z"edbd7       Z#dnd8Z$edbd9       Z%ednd:       Z&dod;Z'	 	 	 	 	 	 	 	 dpd<Z(dqd=Z)d`d>Z*	 	 drdddd?	 	 	 	 	 	 	 	 	 	 	 dsd@Z+e,jZ                  	 	 	 	 	 	 	 	 	 	 	 	 dtdA       Z.dudvdBZ/d`dCZ0dwdxdDZ1dwdxdEZ2d`dFZ3d`dGZ4dydHZ5dzdIZ6d{dJZ7e8d|dK       Z9	 	 	 	 	 	 	 	 	 	 	 	 d}dLZ:d~dMZ;ddNZ<d`dOZ=d`dPZ>ddQZ?ddRZ@d`dSZAd`dTZBd`dUZCd`dVZDd`dWZEddXZFd`dYZGd`dZZHd`d[ZI	 	 	 	 	 	 	 	 	 	 dd\ZJeKd`d]       ZLeKd`d^       ZM xZNS )r   a;  
    Abstract base class for a file lock object.

    Provides the common reentrant API and state management. Subclasses implement the locking mechanism
    (:class:`UnixFileLock <filelock.UnixFileLock>`, :class:`WindowsFileLock <filelock.WindowsFileLock>`,
    :class:`SoftFileLock <filelock.SoftFileLock>`).

    r   r   r   r   r   r   z FileLock instance in this threadr   _deadlock_holder_descFrb   r>  Nztuple[str, str] | NonerB  z4a native OS lock cannot be broken safely by file agerA  rQ   r`   r   Tr   r   _serialize_transitionsg        r^   _poll_backoff_capc                    t        |   di | t               | _        t	               | _        t               | _        t        |        y)z<Give each lock subclass its own singleton registry and lock.Nr1   )	r   __init_subclass__r   r   r   r   r   r   _register_fork_class)r  r	  r   s     r4   rQ  zBaseFileLock.__init_subclass__w  s9    !+F+,.#g,/E)S!r7   c                ^    t               | _        t               | _        t	               | _        y r0   )r   r   r   r   r   r   r  s    r4   rF   z$BaseFileLock._reset_class_after_fork  s     ,.#g,/E)r7   r   r   r!   r$   r   c       	        0   t        j                         | _        t               | _        || _        || _        |	| _        |
| _        || _	        || _
        || _         |rt        nt        t        j                  |      |||||      | _        t!        |        y)a  
        Create a new lock object.

        :param lock_file: path to the file
        :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
            acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
            negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
        :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
            default ACLs, preserving POSIX default ACL inheritance in shared directories.
        :param thread_local: Whether this object's internal context should be thread local or not. If this is set to
            ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the
            lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``,
            ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change
            the value seen by another thread; threads that did not perform the write continue to see the value supplied
            at construction time. If you need configuration values to be visible across threads, construct the lock
            with ``thread_local=False``.
        :param blocking: whether the lock should be blocking or not
        :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
            file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
            same object around.
        :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
            in the acquire method, if no poll_interval value (``None``) is given.
        :param lifetime: for :class:`SoftFileLock`, the age in seconds after which a waiting process may delete the
            marker, even while its holder remains alive. This legacy expiry mode does not provide strict mutual
            exclusion. ``None`` (the default) disables age-based expiry. Native OS locks (:class:`FileLock`) cannot be
            revoked by file age and ignore a non-``None`` ``lifetime`` with a warning.
        :param context_error_policy: how a context manager reconciles a failure in its body with a failure while
            releasing on exit. ``"chain"`` (the default) keeps Python's behavior: the release error propagates with the
            body error in its ``__context__``. ``"group"`` raises a :class:`BaseExceptionGroup` holding the body error
            first and the release error second, so neither hides the other.
        :param close_error_policy: what to do with an ``os.close`` failure after relinquishing descriptor ownership.
            ``"default"`` keeps each backend's historical behavior (Unix native locks drop a FUSE/Docker ``EIO``;
            Windows native locks and :class:`SoftFileLock` propagate); ``"raise"`` always propagates the ``OSError``;
            ``"suppress"`` always ignores it. Held state is released either way. It does not affect unlock failures or
            lock-file deletion.
        :param fallback_to_soft: for :class:`UnixFileLock`, whether to switch to :class:`SoftFileLock` when the
            filesystem's ``flock`` returns ``ENOSYS``. ``True`` (the default) keeps the historical fallback;
            ``False`` fails closed, letting the ``ENOSYS`` propagate so a caller that needs kernel-enforced
            locking is never silently downgraded. It has no effect on Windows or :class:`SoftFileLock`.
        :param preserve_lock_file: for native locks (:class:`FileLock`), whether filelock promises not to unlink the
            lock pathname on release. ``False`` (the default) keeps each backend's cleanup: Windows removes the lock
            file, Unix already leaves it. ``True`` keeps a stable file identity for ACLs, auditing, and holder metadata:
            Windows skips its post-release unlink and Unix refuses to enter the ``ENOSYS`` soft fallback (which releases
            by unlinking). :class:`SoftFileLock` rejects ``True``. The promise covers filelock's own release path only;
            it cannot stop another process or the filesystem from removing the pathname.
        :param on_acquired: for native locks (:class:`FileLock`), a callable invoked with the borrowed lock descriptor
            once per physical acquisition, after filelock holds the native lock and finished backend initialization but
            before :meth:`~BaseFileLock.acquire` returns. Recursive acquisitions do not call it again. The callback may
            read, write, seek, truncate, or set metadata through ``os`` on the descriptor, but must not close, unlock,
            or take ownership of it, and filelock does not fsync its writes. If it raises, filelock releases the lock
            and re-raises. :class:`SoftFileLock` rejects the hook.

        )r  r_   ra   rd   rf   rh   N)r   r  _creator_pidr   _transition_lock_is_thread_local_is_singleton_context_error_policy_close_error_policy_fallback_to_soft_preserve_lock_file_on_acquiredThreadLocalFileContextFileLockContextr   r  _register_fork_object)r3   r  r_   ra   rc   rd   re   rf   rh   rj   rl   rm   rn   rp   s                 r4   r   zBaseFileLock.__init__  s    L IIK % ,)%9"#5 !1#5 '*eL*@Veii	*'*
 	d#r7   c                    | j                   S )z?:returns: a flag indicating if this lock is thread local or not)rX  r2   s    r4   r  zBaseFileLock.is_thread_local  s    $$$r7   c                    | j                   S )zh
        A flag indicating if this lock is singleton or not.

        .. versionadded:: 3.13.0

        )rY  r2   s    r4   re   zBaseFileLock.is_singleton  s     !!!r7   c                    | j                   S )z
        How a context manager reconciles a body failure with a release failure on exit.

        .. versionadded:: 3.30.0

        )rZ  r2   s    r4   rj   z!BaseFileLock.context_error_policy  s     )))r7   c                    | j                   S )z
        What a lock does with an ``os.close`` failure after relinquishing descriptor ownership.

        .. versionadded:: 3.30.0

        )r[  r2   s    r4   rl   zBaseFileLock.close_error_policy  s     '''r7   c                   	 t        j                  |       y # t        $ r$ | j                  dk(  s| j                  dk(  r|rY y  w xY w)Nr&   r$   )r   closeOSErrorr[  )r3   fddefault_suppressess      r4   _close_released_fdzBaseFileLock._close_released_fd  sF    	HHRL 	'':5$:R:RV_:_dv	s    )AAc                    | j                   S )a:  
        Whether a :class:`FileLock` falls back to :class:`SoftFileLock` when the filesystem lacks ``flock``.

        Only :class:`UnixFileLock` acts on it: when ``False`` an ``ENOSYS`` from ``flock`` propagates instead of
        switching to existence-lock semantics.

        .. versionadded:: 3.30.0

        )r\  r2   s    r4   rm   zBaseFileLock.fallback_to_soft  s     %%%r7   c                    | j                   S )aG  
        Whether filelock promises not to unlink the lock pathname on release.

        When ``True``, Windows skips its post-release unlink and Unix refuses the ``ENOSYS`` soft fallback.
        :class:`SoftFileLock` rejects ``True`` because unlinking its marker is how it releases.

        .. versionadded:: 3.30.0

        )r]  r2   s    r4   rn   zBaseFileLock.preserve_lock_file  s     '''r7   c                    | j                   S )av  
        The callback run with the borrowed lock descriptor once per physical acquisition, or ``None``.

        Native locks only. It runs after the native lock is held and backend initialization finished, before
        :meth:`~BaseFileLock.acquire` returns; a raise rolls back the acquisition. :class:`SoftFileLock` rejects it.

        .. versionadded:: 3.30.0

        )r^  r2   s    r4   rp   zBaseFileLock.on_acquired%  s        r7   c                .    | j                   j                  S )zPath to the lock file.)r  r  r2   s    r4   r  zBaseFileLock.lock_file2  s     }}&&&r7   c                .    | j                   j                  S )zZ
        The default timeout value, in seconds.

        .. versionadded:: 2.0.0

        )r  r_   r2   s    r4   r_   zBaseFileLock.timeout7  s     }}$$$r7   c                8    t        |      | j                  _        y)ze
        Change the default timeout value.

        :param value: the new value, in seconds

        N)r^   r  r_   r3   r  s     r4   r_   zBaseFileLock.timeoutA  s     !&er7   c                .    | j                   j                  S )z\
        Whether the locking is blocking or not.

        .. versionadded:: 3.14.0

        r  rd   r2   s    r4   rd   zBaseFileLock.blockingK  s     }}%%%r7   c                &    || j                   _        y)zb
        Change the default blocking value.

        :param value: the new value as bool

        Nrt  rr  s     r4   rd   zBaseFileLock.blockingU  s     "'r7   c                .    | j                   j                  S )z^
        The default polling interval, in seconds.

        .. versionadded:: 3.24.0

        r  rf   r2   s    r4   rf   zBaseFileLock.poll_interval_  s     }}***r7   c                &    || j                   _        y)zh
        Change the default polling interval.

        :param value: the new value, in seconds

        Nrw  rr  s     r4   rf   zBaseFileLock.poll_intervali  s     ',#r7   c                .    | j                   j                  S )aY  
        The soft marker age in seconds that permits expiry, or ``None`` to disable age-based expiry.

        A non-``None`` value permits a waiter to enter while the previous holder remains active, so it does not provide
        strict mutual exclusion. Native locks ignore the value with a warning.

        .. versionadded:: 3.24.0

        )r  rh   r2   s    r4   rh   zBaseFileLock.lifetimes  s     }}%%%r7   c                P    t        |t        |       d      | j                  _        y)a!  
        Change the legacy age-based expiry threshold.

        :param value: the new value in seconds, or ``None`` to disable expiration

        :raises ValueError: if *value* is negative or not finite
        :raises TypeError: if *value* is not ``None`` and not a real number

        rQ   r   N)r   r   r  rh   rr  s     r4   rh   zBaseFileLock.lifetime  s     "35$t*QR!Sr7   c                l    | j                   j                  t        k(  rdS | j                   j                  S )z&The file permissions for the lockfile.i  r  ra   r   r2   s    r4   ra   zBaseFileLock.mode  s+     **.>>uVDMMDVDVVr7   c                <    | j                   j                  t        k7  S )z1Whether the file permissions were explicitly set.r|  r2   s    r4   has_explicit_modezBaseFileLock.has_explicit_mode  s     }}!!%555r7   c                l    | j                   j                  t        k(  rdS | j                   j                  S )z]Mode for ``os.open``: 0o666 when unset so umask and ACLs decide, otherwise the explicit mode.i  r|  r2   s    r4   
_open_modezBaseFileLock._open_mode  s)    **.>>uVDMMDVDVVr7   c                F    t                | j                  j                  duS )z
        A boolean indicating if the lock file is holding the lock currently.

        .. versionchanged:: 2.0.0

            This was previously a method and is now a property.

        N)r   r  lock_file_fdr2   s    r4   	is_lockedzBaseFileLock.is_locked  s     	 !}}))55r7   c                B    t                | j                  j                  S )zGThe number of times this lock has been acquired (but not yet released).)r   r  lock_counterr2   s    r4   r  zBaseFileLock.lock_counter  s     	 !}})))r7   c                &    | j                          | S )zG
        Acquire the lock.

        :returns: the lock object

        )acquirer2   s    r4   	__enter__zBaseFileLock.__enter__  s     	r7   c                &    | j                  |       y)zgRelease the lock, reconciling a release failure with any body failure per :attr:`context_error_policy`.N)_release_in_contextr3   exc_type	exc_value	tracebacks       r4   __exit__zBaseFileLock.__exit__  s     	  +r7   c                    	 | j                          y # t        $ r(}|| j                  dk(  r t        ||       Y d }~y d }~ww xY w)Nr!   )releaser   rZ  r   )r3   r   r   s      r4   r  z BaseFileLock._release_in_context  sC    	?LLN 	?!T%?%?7%J#J>>	?s    	A?Ac                    t        |       j                  d      t        j                         k7  ryt	        j
                  t              5  | j                  d       ddd       y# 1 sw Y   yxY w)z=Force-release so a dropped reference never leaks a held lock.rV  NT)force)varsr   r   r  
contextlibr&   	Exceptionr  r2   s    r4   __del__zBaseFileLock.__del__  sS    :>>.)RYY[8   + 	%LLtL$	% 	% 	%s   
A&&A/)poll_intervallrd   cancel_checkc                  | j                          || j                  j                  }|| j                  j                  }| d}t	        j
                  |t        d       |}||n| j                  j                  }t        j                         }| j                  |||||      5  | j                  xj                  dz  c_        t        | j                        }| j                  |||       	 | j                  |||||       | j%                  |       t'        |       cddd       S # t         $ r | j#                  |        w xY w# 1 sw Y   yxY w)	a  
        Try to acquire the file lock.

        :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
            if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
        :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
            :attr:`~poll_interval`
        :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
        :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
            first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
        :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
            iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.

        :returns: a context object that will unlock the file when the context is exited

        :raises Timeout: if fails to acquire lock within the timeout period

        .. code-block:: python

            # You can use this method in the context manager (recommended)
            with lock.acquire():
                pass

            # Or use an equivalent try-finally construct:
            lock.acquire()
            try:
                pass
            finally:
                lock.release()

        .. versionchanged:: 2.0.0

            This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement
            without side effects.

        Nz+use poll_interval instead of poll_intervall   r   )rd   r  r_   rf   
start_timer   )r_   rd   lock)_raise_if_inheritedr  r_   rd   r?  r@  DeprecationWarningrf   timeperf_counter_transition_admissionr  r   r  _raise_if_would_deadlock_poll_until_acquiredr   _reconcile_failed_acquire_commit_acquireAcquireReturnProxy)	r3   r_   rf   r  rd   r  r  r  	canonicals	            r4   r  zBaseFileLock.acquire  sX   Z 	  "?mm++G}}--H%?CMM#1a@*M)6)BHcHc&&(
 ''%'! ( 
 	1 MM&&!+&"4>>2I)))Wx)X
))%!-#"/) *    +%403	1 	1* ! ..y9+	1 	1s%   'A	E1D-E-E		EEc             #    K   | j                   r| j                  rd  y | j                  j                  d      s|r	| |       rt	        | j
                        |dk\  r/t        j                         |z
  |k\  rt	        | j
                        t        j                  |       | j                  j                  d      s	 d  | j                  j                          y # | j                  j                          w xY ww)NF)rd   r   )
rN  rX  rW  r  r   r  r  r  sleepr  )r3   rd   r  r_   rf   r  s         r4   r  z"BaseFileLock._transition_admission.  s      **d.C.C''///? 8\^dnn--!| 1 1 3j @G Kdnn--JJ}% ''///?	,!!))+D!!))+s   B?DC" D"C>>Dc                   | j                   xr | j                   }|r| j                  nt        j                         5  | j
                  t        j                         k7  s| j                  s
	 ddd       y|sB| j                  j                  dkD  r)| j                  xj                  dz  c_
        	 ddd       yt        |       | j                  }}t        j                  d||       	 | j                          | j#                          t        j                  d||       ddd       y# t         $ r | j                  s| j#                           w xY w# 1 sw Y   yxY w)a1  
        Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
        itself may be deleted automatically, the behavior is platform-specific.

        :param force: If true, the lock counter is ignored and the lock is released in every case.

        Nr   z#Attempting to release lock %s on %szLock %s released on %s)rN  rX  rW  r  nullcontextrV  r   r  r  r  r  r   r  rU   debug_release_with_fork_trackingr   _commit_release)r3   r  	serializelock_idlock_filenames        r4   r  zBaseFileLock.releaseI  s2    //M8M8M4M	&/T""Z5K5K5M 	L  BIIK/t~~	L 	L T]]77!;**a/*	L 	L &(Xt~~]GMM?-X002   "MM2G]K'	L 	L !  ~~((*	L 	Ls/   /E6;E:.E)D)9'E)'EEEc                    | j                   t        j                         k7  r0t        |       j                   d| j
                   d}t        |      y )Nz on z4 was inherited across fork; construct a new instance)rV  r   r  r   r;   r  r   )r3   r  s     r4   r  z BaseFileLock._raise_if_inheritedi  sI    		+$Z(()dnn-==qrCs## ,r7   c                    d | j                   _        d | j                   _        || j                   _        || j                   _        y r0   r  pending_lock_file_fdpending_lock_file_fd_identityr  lock_file_fd_identityr3   ri  identitys      r4   _mark_descriptor_ownedz#BaseFileLock._mark_descriptor_ownedn  s2    -1*6:3%'".6+r7   c                H    || j                   _        || j                   _        y r0   )r  r  r  r  s      r4   _mark_descriptor_pendingz%BaseFileLock._mark_descriptor_pendingt  s    -/*6>3r7   c                    d | j                   _        d | j                   _        d | j                   _        d | j                   _        y r0   r  r2   s    r4   _mark_descriptor_releasedz&BaseFileLock._mark_descriptor_releasedx  s2    -1*6:3%)".2+r7   c                T   t               | _        d| j                  _        d | j                  _        d | j                  _        d | j                  _        d | j                  _        d | j                  _        d | j                  _	        d| j                  _
        d | j                  _        y )Nr1   r   )r   rW  r  owner_claim_paths
claim_rootr  lock_file_fd_tokenr  r  r  r  lock_file_keyr2   s    r4   r5   z'BaseFileLock._reset_after_fork_in_child~  sx     %*,'#' %)"+/(.2+-1*6:3%&"&*#r7   c                   g }| j                   j                  Q| j                   j                  ;|j                  | j                   j                  | j                   j                  f       | j                   j
                  ;|j                  | j                   j
                  | j                   j                  f       t        |      S r0   )r  r  r  r   r  r  r  tuple)r3   descriptorss     r4   rA   z"BaseFileLock._descriptors_for_fork  s    @B==%%1dmm6V6V6^ : :DMM<_<_`a==--9 B BDMMDoDopq[!!r7   c               t   | j                   j                  dk(  xr | j                   xr	 |dk  xr |}|rt        j                  j                  | j                  |            dt        |       hvrG| j                   xj                  dz  c_        d| j                   d| j                   d}t        |      yy)a^  
        Fail fast when a *different* live instance already holds this path in the current deadlock scope.

        Only the first, indefinitely-blocking acquire can self-deadlock this way: waiting in the OS primitive would
        block on a lock this flow already owns. A finite timeout or ``blocking=False`` keeps the normal Timeout path.
        r   r   NzDeadlock: lock 'z!' is already held by a different zE. Use is_singleton=True to enable reentrant locking across instances.)r  r  r  r   r   r   _registry_keyr   r  rM  r   )r3   r  r_   rd   would_blockr  s         r4   r  z%BaseFileLock._raise_if_would_deadlock  s     mm00A5idnn:LiQX[\Q\iai9>>--d.@.@.KLUY[]^b[cTddMM&&!+&"4>>"22STXTnTnSo pV W  s## e;r7   c                2    | j                         x}|S ||fS r0   )_deadlock_scope)r3   r  scopes      r4   r  zBaseFileLock._registry_key  s&    &*&:&:&<<UEy]ES\K]]r7   c                      y)aX  
        Execution unit whose own hold would deadlock a new acquire.

        ``None`` scopes holders to the thread, which the thread-local registry already separates. Async locks
        override it with the running task, since one event loop thread runs many tasks and only a reacquire from
        the *same* task can self-deadlock.
        Nr1   r1   r7   r4   r  zBaseFileLock._deadlock_scope  s     r7   c                  t        |       }| j                  }d}	 | j                          | j                  sG| j	                          t
        j                  d||       | j                          | j                          | j                  rt
        j                  d||       y | j                  ||||      rt        |      |dz  }| j                  ||      }	d}
t
        j                  |
|||	       t        j                  |	       )Nr   z#Attempting to acquire lock %s on %szLock %s acquired on %s)rd   r  r_   r  r   z2Lock %s not acquired on %s, waiting %s seconds ...)r   r  r  r  _try_break_expired_lockrU   r  _acquire_with_fork_tracking_check_give_upr   _poll_delayr  r  )r3   rd   r  r_   rf   r  r  r  attemptdelayr  s              r4   r  z!BaseFileLock._poll_until_acquired  s     T($$&>>,,.CWm\002((*~~6O""!)%	 #  m,,qLG$$]G<EFCMM#wu=JJu+ r7   c           	         | j                   s|S t        | j                   |dt        |t              z  z        }t        |t	        j
                  t        |dz        dz         dz        S )Nr  i@B r   )rO  minr    maxsecrets	randbelowr`   )r3   rf   r  windows       r4   r  zBaseFileLock._poll_delay  sf     %%   T++]Q#gOdBe=e-ef='"3"3C8J4Ka4O"PS\"\]]r7   c                `    | j                   r| j                  |       y | j                          y r0   )r  r  _undo_acquire)r3   r  s     r4   r  z&BaseFileLock._reconcile_failed_acquire  s%     >>  + r7   c                n   | j                   | j                  j                  dk7  ry 	 | j                  t        d| j                  j                               y # t
        $ rS}|j                  }	 | j                          ||_         # t
        $ r}t        ||       Y d }~||_         d }~ww xY wd }~ww xY w)Nr   r`   )	r^  r  r  r   r  r   r   r  r   )r3   callback_errorcallback_contextr   s       r4   _invoke_on_acquiredz BaseFileLock._invoke_on_acquired  s    $(B(Ba(G		d5$--*D*DEF 	-99G002 *:N& ! G'FF)9N&G		sA   /A 	B4!B/.B>B/	B,B'B/'B,,B//B4c                P   t        |       5  	 | j                          	 | j	                          	 d d d        | j                  r| j                          y y # t        $ r}| j                  |        d }~ww xY w# t        $ r}| j                  |        d }~ww xY w# 1 sw Y   mxY wr0   )r0  _acquirer   _rollback_failed_acquire_register_context_descriptor_rollback_failed_registrationr  r  )r3   acquisition_errorregistration_errors      r4   r  z(BaseFileLock._acquire_with_fork_tracking  s    d# 
	113
	 >>$$&  ! --.?@
 ! 223EF
	 
	sE   BAA9	A6A11A66B9	BBBBB%c                Z   | j                   sy d }d }	 | j                          	 | j	                          |t        d|||       y y # t        $ r6}|}	 | j                          n# t        $ r}|}Y d }~nd }~ww xY wY d }~]d }~ww xY w# t        $ r}t        d||||       Y d }~qd }~ww xY w)Nzlock acquisition cleanup failed)r  r  r   '_register_unverified_context_descriptorr  r   )r3   r  r  tracking_errorr   rollback_errors         r4   r  z%BaseFileLock._rollback_failed_acquire  s    ~~37/3	'--/		,,. )!13DFXZh *#  	'!&'<<>  '!&'	'  	!1!" 	sX   A B 	BB A#"B #	A8,A3.B 3A88B  B	B*B%%B*c                    d }	 | j                          	 | j                          |t        d||       y y # t        $ r}|}Y d }~2d }~ww xY w# t        $ r}t        d|||       Y d }~Ed }~ww xY w)Nz&descriptor registration cleanup failed)r  r   r  r   )r3   r  r  r   r  s        r4   r  z*BaseFileLock._rollback_failed_registration#  s    /3	#88:	,,.
 %!"JL^`no &  	#"N	#  	!8:Ln^l 	s+   6 A 	AAA	A/A**A/c                    t        |       5  	 | j                          | j                          	 d d d        y # | j                          w xY w# 1 sw Y   y xY wr0   )r0  _release_unregister_released_descriptorr2   s    r4   r  z(BaseFileLock._release_with_fork_tracking3  sN    d# 	77446		7 	7 446		7 	7s   A8AA

AAc                    | j                   j                  [| j                   j                  Dt        | j                   j                  | j                   j                        | j                   _        y y y r0   )r  r  r  _register_owned_descriptorr  r2   s    r4   r  z)BaseFileLock._register_context_descriptor:  sU    ==%%1dmm6V6V6^/I**330DMM, 7_1r7   c                    | j                   j                  F| j                   j                  /t        | j                   j                        | j                   _        y y y r0   )r  r  r  %_register_unverified_owned_descriptorr2   s    r4   r  z4BaseFileLock._register_unverified_context_descriptorA  sH    ==%%1dmm6V6V6^/TUYUbUbUoUo/pDMM, 7_1r7   c                    | j                   j                  F| j                   j                  x}t        |       d | j                   _        d | j                   _        y y r0   )r  r  r  _unregister_owned_descriptorr  )r3   tokens     r4   r  z,BaseFileLock._unregister_released_descriptorE  sL    ==%%-999F,U3/3DMM,26DMM/	 .r7   c                    t        d| j                  j                  dz
        | j                  _        | j                  j                  dk(  r| j                          yy)zfRoll back the counter after a failed acquire, dropping the registry entry once nothing holds the path.r   r   N)r  r  r  _drop_registry_entryr2   s    r4   r  zBaseFileLock._undo_acquireL  sG    %(DMM,F,F,J%K"==%%*%%' +r7   c                    | j                   j                  dk(  r?| j                  |      }|| j                   _        t	        |       t
        j                  |<   yy)zeRecord this instance as the holder once the first acquire succeeds, so peers can detect the deadlock.r   N)r  r  r  r  r   r   r   )r3   r  keys      r4   r  zBaseFileLock._commit_acquireR  sG    ==%%*$$Y/C*-DMM'"$T(INN3	 +r7   c                    | j                   j                  }d| j                   _        |!t        j                  j	                  |d       yy)zIForget the key owned by this hold without resolving a mutable path again.N)r  r  r   r   r   )r3   r  s     r4   r  z!BaseFileLock._drop_registry_entryZ  s;    mm))&*#?NNsD) r7   c                F    d| j                   _        | j                          y)zdRecord the lock as fully released: reset the recursion counter and drop the deadlock-registry entry.r   N)r  r  r  r2   s    r4   r  zBaseFileLock._commit_releasea  s    %&"!!#r7   c                   | j                   j                  x}yt        j                  t              5  t        j                  | j                        }t        j                         |j                  z
  |k  r
	 ddd       yt        | j                  |j                  |j                         ddd       y# 1 sw Y   yxY w)zVRemove the lock file if its modification time exceeds the configured :attr:`lifetime`.N)r  rh   r  r&   rh  r   lstatr  r  st_mtimer   st_ino)r3   rh   sts      r4   r  z$BaseFileLock._try_break_expired_lockf  s    ...H7  ) 	D
 $..)Byy{R[[(83	D 	D DNNBKKC	D 	D 	Ds   AB5+B55B>c               "   t        |       | j                  }}|du rt        j                  d||       y| |       rt        j                  d||       yd|cxk  rt	        j
                         |z
  k  rn yt        j                  d||       yy)NFz+Failed to immediately acquire lock %s on %sTz(Cancellation requested for lock %s on %sr   z"Timeout on acquiring lock %s on %s)r   r  rU   r  r  r  )r3   rd   r  r_   r  r  r  s          r4   r  zBaseFileLock._check_give_upt  s     "$D4>>uMMGR_`#MMDg}]:$++-
::  MM>Wr7   c                    t         )zjIf the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file.NotImplementedErrorr2   s    r4   r  zBaseFileLock._acquire  
     "!r7   c                    t         )z>Releases the lock and sets self._context.lock_file_fd to None.r  r2   s    r4   r  zBaseFileLock._release  r  r7   )r	  r[   r9   r:   r8   )r  r#  r_   r^   ra   r`   rc   rb   rd   rb   re   rb   rf   r^   rh   rg   rj   ri   rl   rk   rm   rb   rn   rb   rp   ro   r9   r:   )r9   rb   )r9   ri   )r9   rk   )ri  r`   rj  rb   r9   r:   )r9   ro   r   )r9   r^   )r  zfloat | strr9   r:   )r  rb   r9   r:   )r  r^   r9   r:   )r9   rg   )r  rg   r9   r:   )r9   r`   )r9   rS   r  ztype[BaseException] | Noner  BaseException | Noner  zTracebackType | Noner9   r:   )r   r  r9   r:   )NN)r_   rg   rf   rg   r  rg   rd   zbool | Noner  Callable[[], bool] | Noner9   r  )rd   rb   r  r  r_   r^   rf   r^   r  r^   r9   Generator[None])F)r  rb   r9   r:   r0   )ri  r`   r  tuple[int, int] | Noner9   r:   rB   )r  r   r_   r^   rd   rb   r9   r:   )r  r   r9   r   )r9   Hashable | None)rd   rb   r  r  r_   r^   rf   r^   r  r^   r9   r:   )rf   r^   r  r`   r9   r^   )r  r   r9   r:   )r  r   r9   r:   )r  r   r9   r:   )
rd   rb   r  r  r_   r^   r  r^   r9   rb   )Or;   r<   r=   rq   rr   rM  r>  rB  rA  r   r   r   rN  rO  rQ  classmethodrF   r   r   r  r   re   rj   rl   rk  rm   rn   rp   r  r_   setterrd   rf   rh   ra   r~  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r5   rA   r  r  staticmethodr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r   r   s   @r4   r   r   I  s@    76#++ "D3C !&% 6:29 )_ #^ 56,c5 +/!4. $(D' $)D(  #u"" 2 2 $!X$ "#!%3:/8!%#(48X$)X$ X$ 	X$
 X$ X$ X$ X$ X$ 1X$ -X$ X$ !X$ 2X$  
!X$t% " " * * ( ( 
& 
& 
( 
( 
! 
! ' ' % % ^^- - & & __' ' + + , , 
& 
& __
T 
T W W 6 6W 
6 
6 * *
,,, (, (	,
 
,?% !%&*W1
 (, $26W1W1 $W1
 %W1 W1 0W1 
W1r , , 0	,
 , , , 
, ,4L@$
7?3+"$ ^  ! ! 0	!
 ! ! ! 
!F	^!':p 7q7(+*$
D  0	
   
( " " " "r7   )	metaclassc                  8    e Zd ZdZddZddZ	 	 	 	 	 	 	 	 ddZy)	r  zDA context-aware object that will release the lock file when exiting.c                    || _         y r0   r  )r3   r  s     r4   r   zAcquireReturnProxy.__init__  s	    FJ	r7   c                    | j                   S r0   r  r2   s    r4   r  zAcquireReturnProxy.__enter__  s    yyr7   c                    t        | j                  t              r| j                  j                  |       y | j                  j	                          y r0   )r   r  r   r  r  r  s       r4   r  zAcquireReturnProxy.__exit__  s4     dii.II)))4IIr7   N)r  0BaseFileLock | ReadWriteLock | SoftReadWriteLockr9   r:   )r9   r  r
  )r;   r<   r=   rq   r   r  r  r1   r7   r4   r  r    s;    NK	 ,	  (	  (		 
 
	 r7   r  c                      e Zd ZU dZded<   ded<   ded<   ded	<   ded
<   dZded<   dZded<   dZded<   dZded<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   y)r`  z0Holds the context for a ``BaseFileLock`` object.r   r  r^   r_   r`   ra   rb   rd   rf   Nrg   rh   
int | Noner  r  r  r  r  r  r   r  r  r  r1   ztuple[str, ...]r  z
str | Noner  )r;   r<   r=   rq   rr   rh   r  r  r  r  r  r  r  r  r  r1   r7   r4   r`  r`    s    : NN
IN "Hl!  $L*# &*
) 5918 (,*+ =A!#9@ L# &*M?) *,+ "J
!r7   r`  c                      e Zd ZdZy)r_  z8A thread local version of the ``FileLockContext`` class.N)r;   r<   r=   rq   r1   r7   r4   r_  r_    s    Br7   r_  c                  6    e Zd ZU ded<   ded<   ded<   ded<   y)_OwnedDescriptorr`   ri  creator_pidr  deviceinodeNr:  r1   r7   r4   r  r    s    Gr7   r  c                      e Zd ZU dZded<   y)_ForkTransitionContextr   r`   depthN)r;   r<   r=   r#  rr   r1   r7   r4   r"  r"    s    E3Nr7   r"  c                      e Zd ZddZddZy)
_ForkStatec                "   t        t                     | _        t               | _        t               | _        t               | _        i | _        d| _        d| _	        i | _
        i | _        i | _        i | _        t        j                         | _        y Nr   F)r   r   gateregistry_lockr2  r"  transition_contexttransitionsactive_transitionsadmission_closedfork_owner_depthspinned_objectspinned_classesprovisional_descriptor_tokensr   r  pidr2   s    r4   r   z_ForkState.__init__  st    eg&	"W%*W""8":NP"# %13LNQSOQ*99;r7   c                    t        t                     | _        t               | _        t               | _        t               | _        i | _        d| _        d| _	        i | _
        i | _        i | _        i | _        y r'  )r   r   r(  r)  r2  r"  r*  r+  r,  r-  r.  r/  r0  r1  r2   s    r4   reset_synchronizationz _ForkState.reset_synchronization  sg    eg&	"W%*W""8":"# %!#  -/*r7   Nr8   )r;   r<   r=   r   r4  r1   r7   r4   r%  r%    s    0r7   r%  z0Final[WeakValueDictionary[int, _ForkResettable]]_FORK_OBJECTSz5Final[WeakValueDictionary[int, _ForkResettableClass]]_FORK_CLASSESz"Final[dict[int, _OwnedDescriptor]]_OWNED_DESCRIPTORSzFinal[count[int]]_DESCRIPTOR_TOKENS_TRANSITION_TOKENSr   r1  zos.forkz
os.forkpty_FORK_AUDIT_EVENTSc                 x    t         y t        j                  t               t        t        t
        t               y )NrI   )rW   rv   addaudithook_audit_fork_safety_pin_fork_objects_resume_parent_after_fork_reset_child_after_forkr1   r7   r4   _register_fork_hooksrA    s+     '( 1.r7   c              #    K   t         sd  y t                t        j                         }t	        |       }	 d  t        j                         |k(  rt        |       y y # t        j                         |k(  rt        |       w w xY wwr0   )rX   r   r   r  _enter_fork_transition_leave_fork_transition)descriptor_ownerr  r  s      r4   r0  r0    si      ))+K"#34E*99;+%"5) &299;+%"5) &s   5BA  $B %BBc                    t         sy t               5  t        j                  5  | t        t        |       <   t                d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wr0   )rX   r0  r1  r)  r5  r   _refresh_owner_pins)r  s    r4   ra  ra  &  sT     		 [66 &.bl#     "   AA AA	AA&c                    t         sy t               5  t        j                  5  | t        t        |       <   t                d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wr0   )rX   r0  r1  r)  r6  r   rG  rT  s    r4   rR  rR  .  sT     		 [66 !$bg     rH  c                    t         sy t               5  |-t        j                  |       }|j                  |j
                  f}t        | |      cd d d        S # 1 sw Y   y xY wr0   )rX   r0  r   fstatst_devr  _record_owned_descriptorri  r  stat_results      r4   r  r  6  sV     		 6((2,K"));+=+==H'H5	6 6 6s   ;AA c                h    t         sy t               5  t        | d       cd d d        S # 1 sw Y   y xY wr0   )rX   r0  rM  )ri  s    r4   r  r  @  s-     		 2'D12 2 2s   (1c                    t         j                  5  t        t              }t	        | t        j                         |d n|d   |d n|d         t        |<   d d d        |S # 1 sw Y   S xY w)Nr   r   ri  r  r  r   )r1  r)  nextr8  r  r   r  r7  )ri  r  r  s      r4   rM  rM  G  sl    		"	" 
'($4		#+4!"*$	%
5!
 L
 Ls   AA!!A+c                    t               5  t        j                  5  t        j	                  | d        d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wr0   )r0  r1  r)  r7  r   )r  s    r4   r  r  S  sJ    		 ,[66 ,ud+, , , , , ,s!   AAAA		AAc                    t                t               } t        j                  5  t        j                  j                  | d      dz   t        j                  | <   dt        _        t        j                  t        t        j                  j                  | d            kD  rYt        j                  j                          t        j                  t        t        j                  j                  | d            kD  rYt        t        j                  j                  | i       j                               }d d d        t                D ci c]  }|t        |      | }}t        t        t         d |j                         D                    }t        j"                  5  t        j$                  j'                  | g       j)                  |       t        j*                  j'                  | g       j)                  t        t,        j                                      t        j.                  j'                  | g       j)                  t        t0        j                                      d d d        y # 1 sw Y   ;xY wc c}w # 1 sw Y   y xY w)Nr   r   Tr1   c              3  J   K   | ]  }|j                         D ]  }|   y wr0   )rA   )r   owner
descriptors      r4   r   z$_pin_fork_objects.<locals>.<genexpr>f  s%     eEuGbGbGdeZeZes   !#)r   r   r1  r(  r.  r   r-  r,  r   r+  waitr  r5  _verify_unverified_descriptorsr   r   _snapshot_descriptor_for_forkr)  r1  
setdefaultr   r/  r5  r0  r6  )	thread_idtransition_ownersrW  ownersr1  s        r4   r>  r>  X  s   I			 W3>3P3P3T3TU^`a3bef3f%%i0'+$,,s;3J3J3N3NyZ\3]/^^!!# ,,s;3J3J3N3NyZ\3]/^^!+"9"9"="=i"L"S"S"UVW #$,=S5ARbiSFS$))eV]]_e	
%! 
	"	" c11<<YKRRSpq""--i<CCE-J^J^J`Dab""--i<CCE-J^J^J`Dabc cW W Tc cs+   CI(87I(I5I5CI:(I2:Jc                 :   t               } t        j                  5  t        j                  |    j	                         D ]  }t
        j	                  |d         t        j                  |    j	                          t        j                  |    j	                          t        j                  |    s3t        j                  | = t        j                  | = t        j                  | = d d d        t        j                  5  t        j                  |    dk(  rt        j                  | = nt        j                  | xx   dz  cc<   t        t        j                        t        _        t        j                  j                          d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wNr   )r   r1  r)  r1  r   r7  r/  r0  r(  r.  rb   r-  
notify_all)r]  r  s     r4   r?  r?  o  sA   I		"	" 6 >>yIMMO 	0E""5$/	0""9-113""9-11388C99)D**95**956 
		 &((3q8--i8)))494'+K,I,I'J$##%& &6 6& &s   CF8BFFFc                     t                y r0   )r@  r1   r7   r4   r   r     s    r7   c                 .   t        j                         x} t        j                  k(  ry t	               }t        j
                  j                  |dg      d   }t        j                  j                  |dg      d   }g }t        t        j                               D ]9  \  }}|j                  | k7  s|j                  t        j                  |             ; t        j                          | t        _        t        j!                          t#        |||       y )Nr1   r   )r   r  r1  r2  r   r/  r   r0  r  r7  r  r  r   r   r4  r$  clear_detach_child_state)r2  r]  r/  r0  r  r  rX  s          r4   r@  r@    s    yy{{.I //33ItDRHN //33ItDRHN*,K"#5#;#;#=> >z!!S(155e<=> %%'KO  "^^Dr7   c                N   t               }t        j                  5  t        j                  rw|t        j                  vre|t        j
                  vrSt        j                  j                          t        j                  r%|t        j                  vr|t        j
                  vrSt        t              }| t        j
                  j                  |i       |<   t        xj                  dz  c_
        d d d        t        j                  xj                  dz  c_        S # 1 sw Y   .xY wra  )r   r1  r(  r-  r.  r+  rY  rS  r9  r\  r,  r*  r#  )rE  r]  r  s      r4   rC  rC    s    I			 	,((!>!>>!8!88!!#	 ((!>!>>!8!88 '(CS**9b9%@&&!+&	, ""((A-(L	, 	,s   BD#ADD$c                   t         j                  xj                  dz  c_        t         j                  5  t	               }t         j
                  |   | = t         j
                  |   st         j
                  |= t         xj                  dz  c_        t         j                  j                          d d d        y # 1 sw Y   y xY wra  )r1  r*  r#  r(  r   r+  r,  rb  )r  r]  s     r4   rD  rD    s    ""((A-(			 &K	##I.u5&&y1''	2&&!+&##%& & &s   A:B77C c                    t         j                  5  t        t        j	                               D ]  \  } }|j
                  t        j                         k7  s|j                  4	 t        j                  |j                        }t        |j                  |j
                  |j                  |j                        t        | <    	 d d d        y # t        $ r Y w xY w# 1 sw Y   y xY w)NrR  )r1  r)  r  r7  r  r  r   r  r  rK  ri  rh  r  rL  r  )r  rX  rO  s      r4   rZ  rZ    s    		"	" !&'9'?'?'A!B 	E:%%4
8I8I8U hhz}}5 )9==&22"))!((	)u%	    s1   AC$CA C	CCCCC%c                    |.	 t        j                  |       }|j                  |j                  f}t        | |      S # t        $ r Y w xY wr0   )r   rK  rL  r  rh  rM  rN  s      r4   r[  r[    sS    	>((2,K #));+=+==H#B11	  		s   = 	A	A	c                "   | D ]  }|j                   	 t        j                  |j                        }|j
                  |j                  f|j                   |j                  fk7  rbt        j                  t              5  t        j                  |j                         d d d         |D ]  }|j                           |D ]  }|j                           t        j                  j                          y # t        $ r Y w xY w# 1 sw Y   xY wr0   )r  r   rK  ri  rh  rL  r  r   r  r&   rg  r5   rF   r   r   re  )r  r/  r0  rX  rO  r  r  s          r4   rf  rf    s    
 " 
$
$	((:==1K  2 23
8I8I:K[K[7\\  ) 	$HHZ]]#	$ 	$
$ # .++-. &##%&NN  			$ 	$s   C5> D5	D DD	c                    t         j                  5  t        t         j                        } d d d        t	                vry t        t
        j                               }t        t        j                               }| D ]Y  }t         j                  j                  |      x}s%|gt        |      z  |d d  |gt        |      z  t         j                  |   d d  [ y # 1 sw Y   xY wr0   )r1  r(  r  r.  r   r5  r5  r6  r/  r   r   r0  )fork_owner_thread_idsobjectsclassesr]  object_snapshotss        r4   rG  rG    s    			 E %k&C&C DE{//M((*+GM((*+G* Y	*99==iHHH#*)c2B.C"CQ8?y3GWCX7XK&&y1!4YE Es   CC"c                    | t         v r;t        j                  j                  st        j                  r|  d}t        |      y | dk(  r(t        j                  j                  rd}t        |      y y )Nz: is unsafe while filelock is changing descriptor ownershipz_posixsubprocess.fork_execzCfork_exec is unsafe while filelock is changing descriptor ownership)r:  r1  r*  r#  r.  r   )event_argsr  s      r4   r=  r=    st     ""))//;3P3PGUVCs## 4Q 
.	.;3Q3Q3W3WS3 4X	.r7   )r   r  r   rk   ri   r`  r   r]   r   r   r   r0  r   r   r   r   r   rR  ra  r  r  )r9   ztype[BaseException])r   r   r   r   r   r   r   r   r{   ztuple[str, _MarkerValue] | Noner9   r   )r   r   r9   r:   )r   r   r   r   r9   rb   )r   r   r   r  r9   rb   )r   r   r   r   r9   r:   )r   r   r   r   r9   rb   )r   r   r   r   r{   ztuple[str, _MarkerValue]r9   z tuple[BaseException, ...] | Noner0   )r   r   r   r  r9   r   )r   r   r   r   r9   r:   )r   r   r   r   r9   r   )r   r   r   r   r   r  r9   r   )r   r#  r9   r   )r  type[BaseFileLock]r9   r%  )rh   rg   r  rt  r   r`   r9   rg   )rG  r   r9   ri   )rG  r   r9   rk   )r   rb   r   rb   r   r   r9   rb   )rp   ro   r   rb   r   r   r9   ro   r8   )rE  _ForkDescriptorOwner | Noner9   r  )r  r.   r9   r:   )r  rD   r9   r:   )ri  r`   r  r  r9   r  )ri  r`   r9   r  )ri  r`   r  r  r9   r`   )r  r`   r9   r:   )rE  ru  r9   r`   )r  zlist[_OwnedDescriptor]r/  ztuple[_ForkResettable, ...]r0  z tuple[_ForkResettableClass, ...]r9   r:   )rr  r   rs  ztuple[object, ...]r9   r:   )
__future__r   r  r)  loggingr<  r   r  rv   r  r?  abcr   r   collections.abcr   r   r   dataclassesr	   	itertoolsr
   r   	threadingr   r   r   r   typingr   r   r   r   r   r   r   weakrefr   r   _errorr   r   _utilr   r   rr   r    ri   r6  r#   rk   r'   r(   typesr)   r*   _read_writer+   _soft_rwr,   r.   r?   rD   rH   rw   rS   typing_extensions	getLoggerrU   r   rW   rX   rY   rZ   r[   r^   r`   rb   r   _LockInitValuer]   rz   r   r}   r   r   r   r   r   r   r   r   r   r   platformr   abspathrealpathr   r   r   r   r   r   r$  r  r%  r   r   r   r   r   ContextDecoratorr   r  r`  r_  r  r"  r%  r5  r6  r7  r8  r9  r1  r:  rA  r0  ra  rR  r  r  rM  r  r>  r?  r   r@  rC  rD  rZ  r[  rf  rG  r=  __all__r1   r7   r4   <module>r     s   "     	  
   ' . % ! $ 8 8 T T T : 8 "  " * ! %' z & -. 1:GW;M1N . N 9: /89Y/Z , Z)#*+:( :_x _
7x 7(  7"*!2!2!2:!>	 >378PRYZ\^prvRw3x 0 x%6d%B { Bm$~&)*t#c)D08SE4K3HH.)5 ."
$ /3   &	
 , N,0" &ss#&s0Hs%s ?( ?0P$Z		 	 *	 		 @C||w?VBGGOO\^\c\c\l\l) lA,5 , *>)?	& ? T(@
7 @
F ]n\o Y o, $1 1 1 F
.,-=AMP!(G":.., G"X   * (" (" ("VC_e C $  U 0 0: CVBW? WGZG\D \9; 6 ;(- % /(- % /\U !,5y,6O,P ) P * *62	,
c.&(E  &"2'/ 5 
	.
Y	 	 )	 		   r7   