1414and/or the lease has been lost.
1515
1616"""
17- from __future__ import annotations
18-
1917import re
2018import time
21- from typing import TYPE_CHECKING , cast , ContextManager
2219import uuid
2320
2421from kazoo .exceptions import (
3431 RetryFailedError ,
3532)
3633
37- if TYPE_CHECKING :
38- from kazoo .client import KazooClient
39- from kazoo .protocol .states import WatchedEvent
40- from typing import (
41- Any ,
42- List ,
43- Optional ,
44- Sequence ,
45- Type ,
46- Union ,
47- )
48- from typing_extensions import Literal
49-
5034
5135class _Watch (object ):
52- def __init__ (self , duration : Optional [ float ] = None ):
36+ def __init__ (self , duration = None ):
5337 self .duration = duration
54- self .started_at : Optional [ float ] = None
38+ self .started_at = None
5539
56- def start (self ) -> None :
40+ def start (self ):
5741 self .started_at = time .monotonic ()
5842
59- def leftover (self ) -> Optional [ float ] :
43+ def leftover (self ):
6044 if self .duration is None :
6145 return None
6246 else :
63- elapsed = time .monotonic () - cast ( float , self .started_at )
47+ elapsed = time .monotonic () - self .started_at
6448 return max (0 , self .duration - elapsed )
6549
6650
67- class Lock (ContextManager [ None ] ):
51+ class Lock (object ):
6852 """Kazoo Lock
6953
7054 Example usage with a :class:`~kazoo.client.KazooClient` instance:
@@ -93,13 +77,7 @@ class Lock(ContextManager[None]):
9377 # sequence number. Involved in read/write locks.
9478 _EXCLUDE_NAMES = ["__lock__" ]
9579
96- def __init__ (
97- self ,
98- client : KazooClient ,
99- path : str ,
100- identifier : Optional [str ] = None ,
101- extra_lock_patterns : Sequence [str ] = (),
102- ):
80+ def __init__ (self , client , path , identifier = None , extra_lock_patterns = ()):
10381 """Create a Kazoo lock.
10482
10583 :param client: A :class:`~kazoo.client.KazooClient` instance.
@@ -131,7 +109,7 @@ def __init__(
131109 # some data is written to the node. this can be queried via
132110 # contenders() to see who is contending for the lock
133111 self .data = str (identifier or "" ).encode ("utf-8" )
134- self .node : Optional [ str ] = None
112+ self .node = None
135113
136114 self .wake_event = client .handler .event_object ()
137115
@@ -147,25 +125,20 @@ def __init__(
147125 self .assured_path = False
148126 self .cancelled = False
149127 self ._retry = KazooRetry (
150- max_tries = - 1 , sleep_func = client .handler .sleep_func
128+ max_tries = None , sleep_func = client .handler .sleep_func
151129 )
152130 self ._acquire_method_lock = client .handler .lock_object ()
153131
154- def _ensure_path (self ) -> None :
132+ def _ensure_path (self ):
155133 self .client .ensure_path (self .path )
156134 self .assured_path = True
157135
158- def cancel (self ) -> None :
136+ def cancel (self ):
159137 """Cancel a pending lock acquire."""
160138 self .cancelled = True
161139 self .wake_event .set ()
162140
163- def acquire (
164- self ,
165- blocking : bool = True ,
166- timeout : Optional [float ] = None ,
167- ephemeral : bool = True ,
168- ) -> bool :
141+ def acquire (self , blocking = True , timeout = None , ephemeral = True ):
169142 """
170143 Acquire the lock. By defaults blocks and waits forever.
171144
@@ -231,13 +204,11 @@ def acquire(
231204 finally :
232205 self ._acquire_method_lock .release ()
233206
234- def _watch_session (self , state : KazooState ) -> bool :
207+ def _watch_session (self , state ) :
235208 self .wake_event .set ()
236209 return True
237210
238- def _inner_acquire (
239- self , blocking : bool , timeout : Optional [float ], ephemeral : bool = True
240- ) -> bool :
211+ def _inner_acquire (self , blocking , timeout , ephemeral = True ):
241212
242213 # wait until it's our chance to get it..
243214 if self .is_acquired :
@@ -295,10 +266,10 @@ def _inner_acquire(
295266 finally :
296267 self .client .remove_listener (self ._watch_session )
297268
298- def _watch_predecessor (self , event : WatchedEvent ) -> None :
269+ def _watch_predecessor (self , event ) :
299270 self .wake_event .set ()
300271
301- def _get_predecessor (self , node : str ) -> Optional [ str ] :
272+ def _get_predecessor (self , node ) :
302273 """returns `node`'s predecessor or None
303274
304275 Note: This handle the case where the current lock is not a contender
@@ -307,7 +278,7 @@ def _get_predecessor(self, node: str) -> Optional[str]:
307278 """
308279 node_sequence = node [len (self .prefix ) :]
309280 children = self .client .get_children (self .path )
310- found_self : Union [ Literal [ False ], re . Match [ bytes ]] = False
281+ found_self = False
311282 # Filter out the contenders using the computed regex
312283 contender_matches = []
313284 for child in children :
@@ -322,7 +293,7 @@ def _get_predecessor(self, node: str) -> Optional[str]:
322293 if child == node :
323294 # Remember the node's match object so we can short circuit
324295 # below.
325- found_self = cast ( re . Match [ bytes ], match )
296+ found_self = match
326297
327298 if found_self is False : # pragma: nocover
328299 # somehow we aren't in the childrens -- probably we are
@@ -338,42 +309,42 @@ def _get_predecessor(self, node: str) -> Optional[str]:
338309 sorted_matches = sorted (contender_matches , key = lambda m : m .groups ())
339310 return sorted_matches [- 1 ].string
340311
341- def _find_node (self ) -> Optional [ str ] :
312+ def _find_node (self ):
342313 children = self .client .get_children (self .path )
343314 for child in children :
344315 if child .startswith (self .prefix ):
345316 return child
346317 return None
347318
348- def _delete_node (self , node : str ) -> None :
319+ def _delete_node (self , node ) :
349320 self .client .delete (self .path + "/" + node )
350321
351- def _best_effort_cleanup (self ) -> None :
322+ def _best_effort_cleanup (self ):
352323 try :
353324 node = self .node or self ._find_node ()
354325 if node :
355326 self ._delete_node (node )
356327 except KazooException : # pragma: nocover
357328 pass
358329
359- def release (self ) -> bool :
330+ def release (self ):
360331 """Release the lock immediately."""
361332 return self .client .retry (self ._inner_release )
362333
363- def _inner_release (self ) -> bool :
334+ def _inner_release (self ):
364335 if not self .is_acquired :
365336 return False
366337
367338 try :
368- self ._delete_node (cast ( str , self .node ) )
339+ self ._delete_node (self .node )
369340 except NoNodeError : # pragma: nocover
370341 pass
371342
372343 self .is_acquired = False
373344 self .node = None
374345 return True
375346
376- def contenders (self ) -> List [ str ] :
347+ def contenders (self ):
377348 """Return an ordered list of the current contenders for the
378349 lock.
379350
@@ -409,7 +380,7 @@ def contenders(self) -> List[str]:
409380 for match in sorted (contender_matches , key = lambda m : m .groups ())
410381 ]
411382 # Retrieve all the contender nodes data (preserving order).
412- contenders : List [ str ] = []
383+ contenders = []
413384 for node in contender_nodes :
414385 try :
415386 data , stat = self .client .get (self .path + "/" + node )
@@ -420,15 +391,10 @@ def contenders(self) -> List[str]:
420391
421392 return contenders
422393
423- def __enter__ (self ) -> None :
394+ def __enter__ (self ):
424395 self .acquire ()
425396
426- def __exit__ (
427- self ,
428- exc_type : Optional [Type [BaseException ]],
429- exc_value : Optional [BaseException ],
430- traceback : Any ,
431- ) -> None :
397+ def __exit__ (self , exc_type , exc_value , traceback ):
432398 self .release ()
433399
434400
@@ -492,7 +458,7 @@ class ReadLock(Lock):
492458 _EXCLUDE_NAMES = ["__lock__" ]
493459
494460
495- class Semaphore (ContextManager [ None ] ):
461+ class Semaphore (object ):
496462 """A Zookeeper-based Semaphore
497463
498464 This synchronization primitive operates in the same manner as the
@@ -527,13 +493,7 @@ class Semaphore(ContextManager[None]):
527493
528494 """
529495
530- def __init__ (
531- self ,
532- client : KazooClient ,
533- path : str ,
534- identifier : Optional [str ] = None ,
535- max_leases : int = 1 ,
536- ):
496+ def __init__ (self , client , path , identifier = None , max_leases = 1 ):
537497 """Create a Kazoo Lock
538498
539499 :param client: A :class:`~kazoo.client.KazooClient` instance.
@@ -569,7 +529,7 @@ def __init__(
569529 self .cancelled = False
570530 self ._session_expired = False
571531
572- def _ensure_path (self ) -> None :
532+ def _ensure_path (self ):
573533 result = self .client .ensure_path (self .path )
574534 self .assured_path = True
575535 if result is True :
@@ -590,14 +550,12 @@ def _ensure_path(self) -> None:
590550 else :
591551 self .client .set (self .path , str (self .max_leases ).encode ("utf-8" ))
592552
593- def cancel (self ) -> None :
553+ def cancel (self ):
594554 """Cancel a pending semaphore acquire."""
595555 self .cancelled = True
596556 self .wake_event .set ()
597557
598- def acquire (
599- self , blocking : bool = True , timeout : Optional [float ] = None
600- ) -> bool :
558+ def acquire (self , blocking = True , timeout = None ):
601559 """Acquire the semaphore. By defaults blocks and waits forever.
602560
603561 :param blocking: Block until semaphore is obtained or
@@ -635,9 +593,7 @@ def acquire(
635593
636594 return self .is_acquired
637595
638- def _inner_acquire (
639- self , blocking : bool , timeout : Optional [float ] = None
640- ) -> bool :
596+ def _inner_acquire (self , blocking , timeout = None ):
641597 """Inner loop that runs from the top anytime a command hits a
642598 retryable Zookeeper exception."""
643599 self ._session_expired = False
@@ -678,10 +634,10 @@ def _inner_acquire(
678634 finally :
679635 lock .release ()
680636
681- def _watch_lease_change (self , event : WatchedEvent ) -> None :
637+ def _watch_lease_change (self , event ) :
682638 self .wake_event .set ()
683639
684- def _get_lease (self ) -> bool :
640+ def _get_lease (self , data = None ) :
685641 # Make sure the session is still valid
686642 if self ._session_expired :
687643 raise ForceRetryError ("Retry on session loss at top" )
@@ -710,26 +666,25 @@ def _get_lease(self) -> bool:
710666 # Return current state
711667 return self .is_acquired
712668
713- def _watch_session (self , state : KazooState ) -> Optional [ Literal [ True ]] :
669+ def _watch_session (self , state ) :
714670 if state == KazooState .LOST :
715671 self ._session_expired = True
716672 self .wake_event .set ()
717673
718674 # Return true to de-register
719675 return True
720- return None
721676
722- def _best_effort_cleanup (self ) -> None :
677+ def _best_effort_cleanup (self ):
723678 try :
724679 self .client .delete (self .create_path )
725680 except KazooException : # pragma: nocover
726681 pass
727682
728- def release (self ) -> bool :
683+ def release (self ):
729684 """Release the lease immediately."""
730685 return self .client .retry (self ._inner_release )
731686
732- def _inner_release (self ) -> bool :
687+ def _inner_release (self ):
733688 if not self .is_acquired :
734689 return False
735690 try :
@@ -739,7 +694,7 @@ def _inner_release(self) -> bool:
739694 self .is_acquired = False
740695 return True
741696
742- def lease_holders (self ) -> List [ str ] :
697+ def lease_holders (self ):
743698 """Return an unordered list of the current lease holders.
744699
745700 .. note::
@@ -753,7 +708,7 @@ def lease_holders(self) -> List[str]:
753708
754709 children = self .client .get_children (self .path )
755710
756- lease_holders : List [ str ] = []
711+ lease_holders = []
757712 for child in children :
758713 try :
759714 data , stat = self .client .get (self .path + "/" + child )
@@ -762,13 +717,8 @@ def lease_holders(self) -> List[str]:
762717 pass
763718 return lease_holders
764719
765- def __enter__ (self ) -> None :
720+ def __enter__ (self ):
766721 self .acquire ()
767722
768- def __exit__ (
769- self ,
770- exc_type : Optional [Type [BaseException ]],
771- exc_value : Optional [BaseException ],
772- traceback : Any ,
773- ) -> None :
723+ def __exit__ (self , exc_type , exc_value , traceback ):
774724 self .release ()
0 commit comments