§
    %P„jûÞ  ã                  óN  — d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZmZmZ  ej        e¦  «        ZdZdZdZ G d„ deej        ¦  «        Z G d	„ d
e	j        ¦  «        Z G d„ dej        j        ¦  «        Z G d„ dej        d         ¦  «        ZdS )a-
  Distributed locking through Redis pubsub instead of expiring keys.

The usual way to build a Redis lock is a key with a time to live: the
holder writes ``SET <name> <token> NX PX <ttl>`` and keeps refreshing it.
That design has an awkward failure mode. When a holder crashes, its
network drops, or its machine is powered off, the key outlives it and
every other process waits out the remaining TTL even though the holder is
provably gone. Shortening the TTL narrows that window but risks a merely
slow holder losing a lock it still believes it owns.

`RedisLock` keeps the lock in a *subscription* rather than in a key. A
holder subscribes to the lock channel and a background thread keeps
reading from it, so ownership is a property of a live connection. If the
process dies the socket closes, Redis drops the subscriber, and the lock
is released at once: there is no expiry to wait out and no heartbeat to
refresh. The price is that nothing is stored anywhere, so a lock attempt
has to ask the channel who is currently there.

Asking is a ping/pong on the channel itself::

    acquire()
      |
      +- subscribe to the channel, naming the connection `client_name`
      +- count subscribers; being the only one means the lock is free
      +- otherwise publish a ping carrying a private response channel,
      |  which every subscriber answers with a record of its holder id
      |  and its current mode (see `RedisLockHolder`)
      +- decide (see `RedisLock._resolve_lock_holders`):
           compatible holders     -> join them, the lock is held
           elected, no readers    -> take the lock exclusively
           anything else          -> unsubscribe and retry

Shared readers hold the lock together, an exclusive writer holds it
alone. There is no coordinator and no lock to take before taking the
lock, so competing writers agree on a single winner by sorting the
pending holder ids they all saw; see `RedisLock._writer_is_elected`.
Subscribers that Redis still counts but that stopped answering are
crashed processes, and their connections are killed so that the channel
becomes consistent again.

Set ``health_check_interval`` on the connection (it is part of
`RedisLock.DEFAULT_REDIS_KWARGS`) so that both sides notice a dead peer
promptly.

Example:
    >>> import fakeredis
    >>> import portalocker
    >>> connection = fakeredis.FakeStrictRedis(
    ...     server=fakeredis.FakeServer(), decode_responses=True
    ... )
    >>> lock = portalocker.RedisLock('some_channel', connection=connection)
    >>> with lock:
    ...     print('do something here')
    do something here
é    )ÚannotationsNé   )Ú	constantsÚ
exceptionsÚutilsgš™™™™™¹?c                  ó   — e Zd ZdZdZdZdZdS )ÚRedisLockModea  What a participant claims to be doing with the lock.

    The member values are the strings that travel in the ``mode`` field of
    a holder record, which is why this is a `str` subclass: a member
    compares equal to its own wire value.

    `PENDING` is the member that makes the protocol work. An exclusive
    waiter announces itself on the channel before it owns anything, which
    is what lets competing writers elect a single winner among themselves
    and what stops an endless stream of readers from starving a writer.
    Ú	exclusiveÚpendingÚsharedN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	EXCLUSIVEÚPENDINGÚSHARED© ó    úV/root/disk_3tb/conda_envs/Huy-visual/lib/python3.11/site-packages/portalocker/redis.pyr	   r	   Y   s-   € € € € € ð
ð 
ð €Ið €Gð €F€F€Fr   r	   c                  ó6   — e Zd ZU dZded<   ded<   dZded<   d	S )
ÚRedisLockHoldera§  One participant's answer to a liveness ping.

    A probe collects one of these per subscriber on the lock channel and
    the whole acquisition decision is made from the resulting list.

    Example:
        >>> from portalocker import redis
        >>> holder = redis.RedisLockHolder('a1b2', redis.RedisLockMode.SHARED)
        >>> holder.holder_id, holder.mode.value, holder.legacy
        ('a1b2', 'shared', False)
    ÚstrÚ	holder_idr	   ÚmodeFÚboolÚlegacyN)r   r   r   r   Ú__annotations__r   r   r   r   r   r   p   sF   € € € € € € ð
ð 
ð €N€N�NàÐÐÑð €FÐÐÐÑÐÐr   r   c                  ó$   ‡ — e Zd ZdZdˆ fd„Zˆ xZS )ÚPubSubWorkerThreada^  redis-py's pubsub reader thread, with failures escalated to main.

    The subscription this thread services *is* the lock. While it runs,
    the holder answers liveness pings and Redis keeps counting it as a
    subscriber. If the thread were to die quietly - a dropped connection,
    a protocol error - the owning process would carry on believing it
    still holds a lock that every other process now considers released,
    which is exactly the split-brain this lock exists to avoid.

    Interrupting the main thread turns that silent divergence into a loud
    failure the process cannot miss.
    ÚreturnÚNonec                óŽ   •— 	 t          ¦   «                              ¦   «          dS # t          $ r t          j        ¦   «          ‚ w xY w)aœ  Read from the subscription, interrupting main on failure.

        Raises:
            Exception: Whatever the underlying reader raised, re-raised
                after `_thread.interrupt_main` has queued a
                `KeyboardInterrupt` in the main thread. Re-raising only
                ends this worker thread; the queued interrupt is what the
                rest of the process actually sees.
        N)ÚsuperÚrunÚ	ExceptionÚ_threadÚinterrupt_main)ÚselfÚ	__class__s    €r   r%   zPubSubWorkerThread.run˜   sJ   ø€ ð	Ý‰GŒG�KŠK‰MŒMˆMˆMˆMøÝð 	ð 	ð 	ÝÔ"Ñ$Ô$Ð$Øð	øøøs	   ƒ % ¥A©r!   r"   )r   r   r   r   r%   Ú__classcell__©r*   s   @r   r    r    Š   sG   ø€ € € € € ðð ðð ð ð ð ð ð ð ð ð r   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ed<   ded<   ded<   ded<   ded<    edd¬¦  «        Zded<   ddddee	de
j        j        fdIˆ fd&„ZdJd(„ZdKd*„ZdLd,„ZdMd/„ZedNd0„¦   «         ZedNd1„¦   «         ZdOd3„ZdPd4„ZdQd9„ZdRd<„ZdSd?„ZdTdB„ZdTdC„ZdUdD„Z	 	 	 dVdWdE„ZdXdF„ZdYdG„ZdYdH„Z ˆ xZ!S )ZÚ	RedisLockaP  An extremely reliable Redis lock based on pubsub.

    The lock is held by a subscription kept open by a keep-alive thread.

    As opposed to most Redis locking systems based on key/value pairs,
    this locking method is based on the pubsub system. The big advantage is
    that if the connection gets killed due to network issues, crashing
    processes or otherwise, it will still immediately unlock instead of
    waiting for a lock timeout.

    To make sure both sides of the lock know about the connection state it is
    recommended to set the `health_check_interval` when creating the redis
    connection.

    Args:
        channel: the redis channel to use as locking key.
        connection: an optional redis connection if you already have one
            or if you need to specify the redis connection. A connection
            given here is never closed by the lock; one created by the
            lock itself is closed on release.
        timeout: timeout when trying to acquire a lock
        check_interval: check interval while waiting
        fail_when_locked: after the initial lock failed, return an error
            or lock the file. This does not wait for the timeout.
        thread_sleep_time: sleep time between fetching messages from redis to
            prevent a busy/wait loop. In the case of lock conflicts this
            increases the time it takes to resolve the conflict. This should
            be smaller than the `check_interval` to be useful.
        unavailable_timeout: If the conflicting lock is properly connected
            this should never exceed twice your redis latency. Note that this
            will increase the wait time possibly beyond your `timeout` and is
            always executed if a conflict arises.
        redis_kwargs: The redis connection arguments if no connection is
            given. The `DEFAULT_REDIS_KWARGS` are used as default, if you want
            to override these you need to explicitly specify a value (e.g.
            `health_check_interval=0`)
        flags: `LockFlags.EXCLUSIVE` (the default) or `LockFlags.SHARED`.
            Shared holders may coexist, while an exclusive holder waits for
            all shared holders to release. Other flag combinations are
            rejected; use `fail_when_locked` for non-blocking acquisition.

    Example:
        Two readers can hold the same channel at the same time, while a
        writer would have to wait for both of them:

        >>> import fakeredis
        >>> import portalocker
        >>> connection = fakeredis.FakeStrictRedis(
        ...     server=fakeredis.FakeServer(), decode_responses=True
        ... )
        >>> reader = portalocker.RedisLock(
        ...     'shared_channel',
        ...     connection=connection,
        ...     flags=portalocker.LockFlags.SHARED,
        ... )
        >>> other_reader = portalocker.RedisLock(
        ...     'shared_channel',
        ...     connection=connection,
        ...     flags=portalocker.LockFlags.SHARED,
        ... )
        >>> with reader, other_reader:
        ...     print('both readers are in')
        both readers are in
    údict[str, typing.Any]Úredis_kwargszPubSubWorkerThread | NoneÚthreadr   ÚchannelÚfloatÚtimeoutúredis.client.Redis | NoneÚ
connectionNzredis.client.PubSub | NoneÚpubsubr   Úclose_connectionúconstants.LockFlagsÚflagsr   r	   r   Úwriter_electedé
   T)Úhealth_check_intervalÚdecode_responsesz&typing.ClassVar[dict[str, typing.Any]]ÚDEFAULT_REDIS_KWARGSFúfloat | NoneÚcheck_intervalÚfail_when_lockedúbool | NoneÚthread_sleep_timeÚunavailable_timeoutúdict[str, typing.Any] | Noner!   r"   c
                ód  •— | | _         d| _        || _        || _        || _        || _        |pt          ¦   «         | _        |	t          j	        j
        t          j	        j        fvrt          d¦  «        ‚|	| _        t          j        ¦   «         j        | _        d| _        |	t          j	        j        k    rt&          j        nt&          j        | _        | j                             ¦   «         D ] \  }
}| j                             |
|¦  «         Œ!t3          ¦   «                              |||¬¦  «         dS )a2  Configure the lock without touching Redis.

        Nothing is connected, subscribed or published here. The
        constructor only records the configuration, allocates the
        `holder_id` that identifies this instance on the wire, and picks
        the starting `mode`: `RedisLockMode.SHARED` for a reader, or
        `RedisLockMode.PENDING` for a writer, which only becomes
        `RedisLockMode.EXCLUSIVE` once `acquire` succeeds. The first
        contact with Redis happens in `acquire`.

        Every instance gets its own random `holder_id`, so two locks in
        the same process are two independent holders and neither can
        satisfy the other's lock.

        See the class docstring for the argument reference.

        Raises:
            ValueError: `flags` was neither exactly
                `constants.LockFlags.EXCLUSIVE` nor exactly
                `constants.LockFlags.SHARED`. Combinations such as
                ``EXCLUSIVE | NON_BLOCKING`` have no meaning here; use
                `fail_when_locked` for non-blocking behaviour.
        NzSRedisLock flags must contain exactly one of LockFlags.EXCLUSIVE or LockFlags.SHAREDF)r5   rB   rC   )r9   r2   r3   r7   rE   rF   Údictr1   r   Ú	LockFlagsr   r   Ú
ValueErrorr;   ÚuuidÚuuid4Úhexr   r<   r	   r   r   r@   ÚitemsÚ
setdefaultr$   Ú__init__)r)   r3   r7   r5   rB   rC   rE   rF   r1   r;   ÚkeyÚvaluer*   s               €r   rQ   zRedisLock.__init__ü   sC  ø€ ðH %/ ˆÔàˆŒØˆŒØ$ˆŒØ!2ˆÔØ#6ˆÔ Ø(Ð2­D©F¬FˆÔØÝÔÔ)ÝÔÔ&ð
ð 
ð 
õ ð:ñô ð ð ˆŒ
Ýœ™œÔ)ˆŒØ#ˆÔð �	Ô+Ô2Ò2Ð2õ Ô Ð åÔ&ð 	Œ	ð Ô3×9Ò9Ñ;Ô;ð 	5ð 	5‰JˆC�ØÔ×(Ò(¨¨eÑ4Ô4Ð4Ð4å‰Œ×ÒØØ)Ø-ð 	ñ 	
ô 	
ð 	
ð 	
ð 	
r   úredis.client.Redisc                ó^   — | j         s t          j        j        di | j        ¤Ž| _         | j         S )aö  Return the Redis connection, creating one on first use.

        A connection handed to the constructor is returned unchanged and
        is never closed by this class; the caller owns it. A connection
        created here is owned by the lock, is built from `redis_kwargs`
        (with `DEFAULT_REDIS_KWARGS` filled in), and is closed by
        `release`, after which the next call creates a fresh one.

        Returns:
            The connection every command from this lock is issued on.
        r   )r7   ÚredisÚclientÚRedisr1   ©r)   s    r   Úget_connectionzRedisLock.get_connectionB  s4   € ð Œð 	FÝ#œlÔ0ÐEÐE°4Ô3DÐEÐEˆDŒOàŒÐr   úredis.client.PubSubc                óP   — t          j        d|                     ¦   «         ¦  «        S )z;Typed wrapper, `Redis.pubsub()` is unannotated in redis-py.r[   )ÚtypingÚcastr8   ©r)   r7   s     r   Ú_get_pubsubzRedisLock._get_pubsubS  s*   € õ
 Œ{Ø!Ø×ÒÑÔñ
ô 
ð 	
r   Úintc                óN   — |                      | j        ¦  «        d         d         S )z)Get the subscriber count for our channel.r   r   )Úpubsub_numsubr3   r_   s     r   Ú_get_subscriber_countzRedisLock._get_subscriber_count]  s"   € à×'Ò'¨¬Ñ5Ô5°aÔ8¸Ô;Ð;r   Úmessageúdict[str, str]c           	     óZ  — |                      d¦  «        dk    rdS |                      d¦  «        }|sdS 	 t          j        |¦  «        }n8# t          j        t          f$ r t
                               d|¦  «         Y dS w xY wt          |t          ¦  «        sdS t          j
        d|¦  «        }|                      d¦  «        }t          |t          ¦  «        r|sdS | j        €J ‚| j                             |t          j        | j        | j        j        t$          dœ¦  «        ¦  «         dS )	a�  Answer a liveness ping with this holder's record.

        Registered as the subscription callback in `_start_subscription`,
        so it runs on the `PubSubWorkerThread` for every message
        published to `channel`. Anything that is not a JSON object with a
        non-empty ``response_channel`` string is ignored, which keeps
        unrelated traffic on the channel harmless.

        The reply is published on the private response channel the prober
        asked for and carries `holder_id`, the *current* `mode` and
        `REDIS_LOCK_PROTOCOL_VERSION`. Answering with the live mode
        rather than a stored one is what makes the protocol truthful: a
        writer that is still `RedisLockMode.PENDING` says so, and a probe
        therefore learns the state as it was at the moment it asked.

        A probing lock is subscribed to its own channel, so it answers
        its own ping and appears in its own holder list.

        Args:
            message: A redis-py pubsub message. Only messages of type
                ``message`` are answered; subscribe confirmations and
                other control frames are dropped.
        Útypere   NÚdatazInvalid Redis lock message: %rr0   Úresponse_channel)r   r   Úprotocol)ÚgetÚjsonÚloadsÚJSONDecodeErrorÚ	TypeErrorÚloggerÚdebugÚ
isinstancerI   r]   r^   r   r7   ÚpublishÚdumpsr   r   rS   ÚREDIS_LOCK_PROTOCOL_VERSION)r)   re   Úraw_datari   Ú	data_dictrj   s         r   Úchannel_handlerzRedisLock.channel_handlera  sU  € ð0 �;Š;�vÑÔ )Ò+Ð+ØˆFà&Ÿ{š{¨6Ñ2Ô2ˆØð 	ØˆFð	Ý#œz¨(Ñ3Ô3ˆDˆDøÝÔ$¥iÐ0ð 	ð 	ð 	Ý�LŠLÐ9¸7ÑCÔCÐCØˆFˆFð	øøøõ ˜$¥Ñ%Ô%ð 	ØˆFÝ+1¬;Ø#Øñ,
ô ,
ˆ	ð (1§}¢}Ð5GÑ'HÔ'HÐÝÐ*­CÑ0Ô0ð 	Ð8Hð 	ØˆFàŒÐ*Ð*Ð*ØŒ×ÒØÝŒJà!%¤Ø œIœOÝ ;ðð ñô ñ		
ô 		
ð 		
ð 		
ð 		
s   ¶A Á1B Á?B c                ó$   — | j         › d| j        › �S )aK  Name given to this holder's subscriber connection.

        `_start_subscription` sends ``CLIENT SETNAME`` over the pubsub
        connection itself, so the name lands on the connection that
        actually holds the subscription and shows up against it in
        ``CLIENT LIST``. `_kill_unavailable_locks` reads it back the
        other way around: a listed connection whose name carries a
        `holder_id` that did not answer the last ping belongs to a
        crashed holder, and killing it releases the lock.

        Returns:
            `legacy_client_name` with this instance's `holder_id`
            appended.

        Example:
            >>> from portalocker import redis
            >>> lock = redis.RedisLock('some_channel')
            >>> lock.client_name == f'some_channel-lock-{lock.holder_id}'
            True
        ú-)Úlegacy_client_namer   rY   s    r   Úclient_namezRedisLock.client_name›  s   € ð, Ô)Ð<Ð<¨D¬NÐ<Ð<Ð<r   c                ó   — | j         › d�S )a  Connection name used by portalocker 3.2.0 and older.

        Up to and including portalocker 3.2.0 every holder on a channel
        named its connection ``<channel>-lock``, with no per-holder
        suffix, and answered a ping with a bare timestamp string instead
        of a record. Shared locks need holders to be individually
        identifiable, so 4.0.0 appended `holder_id` to the name (see
        `client_name`) and replaced the timestamp with a JSON record.

        The old name is still recognised so that a 4.0.0 holder sharing a
        channel with an older one stays correct: an old reply is recorded
        as a single legacy `RedisLockMode.EXCLUSIVE` holder, which blocks
        readers and writers alike, and an old connection that stops
        answering is still reaped by name.

        Returns:
            The unsuffixed ``<channel>-lock`` name.

        Example:
            >>> from portalocker import redis
            >>> redis.RedisLock('some_channel').legacy_client_name
            'some_channel-lock'
        z-lock)r3   rY   s    r   r|   zRedisLock.legacy_client_name³  s   € ð2 ”,Ð%Ð%Ð%Ð%r   útyping.Iterator[int]c              #  ó@  K  — |€d}|€| j         }t          j        ¦   «         |z   }d}|st          j        ¦   «         |k     r]d}|dk    r|n| j         }|dt          j        ¦   «         z   z  }t          j        |¦  «         dV — |°Dt          j        ¦   «         |k     °[dS dS )a$  Yield once per attempt until the deadline passes.

        Overrides `utils.LockBase._timeout_generator` because a Redis
        retry loop has different needs from a filesystem one:

        - Every interval is scaled by a random factor in ``[0.5, 1.5)``.
          Contenders that started together would otherwise retry in
          lockstep and keep colliding round after round; the jitter
          spreads them out so one of them gets a clean probe.
        - The sleep happens *before* the yield, so a caller waits out an
          interval before its first attempt as well as between attempts.
          The loops driven by this generator poll a subscription, and
          polling one that was created microseconds ago only wastes a
          round trip.
        - The deadline is taken from `time.monotonic`, so adjusting the
          system clock mid-wait cannot stretch or cut short a timeout.

        Like the base class it always yields at least once, even with a
        zero or negative timeout, so ``fail_when_locked`` still makes one
        real attempt rather than failing without asking.

        Args:
            timeout: Seconds to keep yielding for. `None` means zero,
                which still yields exactly once.
            check_interval: Base seconds to sleep before each attempt.
                `None` or a non-positive value falls back to
                `thread_sleep_time`.

        Yields:
            A constant ``0``. Unlike the base class this is not an
            attempt counter; callers iterate for the timing alone.
        Nç        TFr   g      à?)rE   ÚtimeÚ	monotonicÚrandomÚsleep)r)   r5   rB   ÚdeadlineÚfirstÚeffective_intervalÚ
sleep_times          r   Ú_timeout_generatorzRedisLock._timeout_generatorÎ  sÎ   è è € ðF ˆ?ØˆGØÐ!Ø!Ô3ˆNÝ”>Ñ#Ô# gÑ-ˆØˆØð 		•t”~Ñ'Ô'¨(Ò2Ð2ØˆEð " AÒ%Ð%ð �àÔ+ð ð
 ,¨sµV´]±_´_Ñ/DÑEˆJÝŒJ�zÑ"Ô"Ð"ØˆGˆGˆGð ð 		•t”~Ñ'Ô'¨(Ò2Ð2Ð2Ð2Ð2Ð2r   c                óª  — |                       |¦  «        }|| _        	 |                     dd| j        ¦  «         |                     ¦   «           |j        di | j        | j        i¤Ž t          || j	        d¬¦  «        | _
        | j
                             ¦   «          t          j        d¦  «         dS # t          $ r |                      ¦   «          ‚ w xY w)aý  Subscribe to the lock channel and start the keep-alive thread.

        This is where the lock comes into existence. Once the
        subscription is live this process is counted by ``PUBSUB
        NUMSUB``, answers pings through `channel_handler`, and stays a
        holder for exactly as long as the connection survives.

        The order of operations matters:

        1. ``CLIENT SETNAME`` is sent over the pubsub connection rather
           than the command connection, so the name identifies the
           connection that actually holds the subscription - the one
           `_kill_unavailable_locks` looks for in ``CLIENT LIST``. Its
           reply is consumed with ``parse_response`` so it cannot later
           be mistaken for a pubsub message.
        2. The subscription is registered with `channel_handler` as its
           callback, so pings are answered from now on.
        3. A `PubSubWorkerThread` starts reading. It is a daemon thread:
           an unreleased lock must never keep the interpreter alive, and
           since losing the connection *is* releasing the lock, dying at
           process exit is the correct behaviour rather than a leak.

        Any failure rolls the whole thing back through `release` before
        re-raising, leaving `pubsub` as `None`. Without that rollback a
        failed `acquire` would leave half a subscription behind and the
        ``assert not self.pubsub`` at the top of `acquire` would refuse
        every later retry on the same object.

        Args:
            connection: The connection to subscribe on.

        Raises:
            Exception: Anything the Redis client raises while naming,
                subscribing or starting the thread, re-raised unchanged
                after the rollback.
        ÚCLIENTÚSETNAMET)r‰   Údaemonç{®Gáz„?Nr   )r`   r8   Úexecute_commandr}   Úparse_responseÚ	subscriber3   ry   r    rE   r2   Ústartr‚   r…   r&   Úrelease)r)   r7   r8   s      r   Ú_start_subscriptionzRedisLock._start_subscription  sú   € ðP '+×&6Ò&6°zÑ&BÔ&BˆØˆŒð	Ø×"Ò"ØØØÔ ñô ð ð
 ×!Ò!Ñ#Ô#Ð#ØˆFÔÐDÐD ¤¨dÔ.BÐCÐDÐDÐDõ -ØØÔ1Øðñ ô ˆDŒKð
 ŒK×ÒÑÔÐÝŒJ�tÑÔÐÐÐøÝð 	ð 	ð 	Ø�LŠL‰NŒNˆNØð	øøøs   žBB2 Â2 Crw   ú
typing.AnyÚlegacy_indexr   c                óÊ  — 	 t          j        |¦  «        }|                     d¦  «        }|                     d¦  «        }|                     d¦  «        }|t          k    rHt	          |t
          ¦  «        r3t	          |t
          ¦  «        rt          |t          |¦  «        ¬¦  «        S n# t          t          t          f$ r Y nw xY wt          d|› �t          j        d¬¦  «        S )a†  Turn one raw ping reply into a `RedisLockHolder`.

        A reply is accepted as a protocol record only if it decodes to a
        mapping whose ``protocol`` equals `REDIS_LOCK_PROTOCOL_VERSION`
        and whose ``holder_id`` and ``mode`` are both strings, with
        ``mode`` naming a known `RedisLockMode`. Everything else - a bare
        timestamp from portalocker 3.2.0, a truncated payload, a mode
        some future version invents - falls back to a synthetic legacy
        holder.

        That fallback is deliberately pessimistic. It reports
        `RedisLockMode.EXCLUSIVE`, so anything unrecognised blocks
        readers and writers alike. Assuming `RedisLockMode.SHARED` for a
        participant whose intentions could not be read would hand out
        overlapping locks, which is the one outcome a lock may never
        produce.

        Legacy replies carry no identity, so they cannot be de-duplicated
        by holder id the way protocol replies are. `legacy_index` gives
        each one a distinct ``legacy-<n>`` id, so two silent old holders
        count as two holders instead of collapsing into one and leaving
        the caller short of the subscriber count it expected.

        Args:
            raw_data: The message payload exactly as received, normally a
                JSON string but not required to be anything in
                particular.
            legacy_index: How many legacy replies this probe has already
                seen. Used only to build a unique fallback holder id.

        Returns:
            The parsed holder, or a legacy exclusive holder when the
            reply could not be interpreted.
        r   r   rk   )r   r   zlegacy-T)r   r   r   )rm   rn   rl   rv   rs   r   r   r	   ÚAttributeErrorrp   rK   r   )r)   rw   r—   ri   r   r   rk   s          r   Ú_parse_lock_responsezRedisLock._parse_lock_responseB  sø   € ðN	Ý#œz¨(Ñ3Ô3ˆDØ$(§H¢H¨[Ñ$9Ô$9ˆIØ#Ÿxšx¨Ñ/Ô/ˆDØ#'§8¢8¨JÑ#7Ô#7ˆHàÕ7Ò7Ð7Ý˜y­#Ñ.Ô.ð 8å˜t¥SÑ)Ô)ð 8õ 'Ø'Ý& tÑ,Ô,ðñ ô ð øøõ ¥	­:Ð6ð 	ð 	ð 	ØˆDð	øøøõ Ø. Ð.Ð.ÝÔ(Øð
ñ 
ô 
ð 	
s   ‚B%B) Â)CÃCÚresponding_holdersú typing.Iterable[RedisLockHolder]c                óÞ  — t          |¦  «        }d„ |D ¦   «         }t          d„ |D ¦   «         ¦  «        }| j        › d�}|                     ¦   «         }|D ]—}|                     dd¦  «        }	|	| j        k    o| p+|	                     |¦  «        o|	                     |¦  «        |v}
|
rCt                               d|¦  «         | 	                    |                     d¦  «        ¦  «         Œ˜dS )	aÎ  Kill the connections of holders that did not answer the ping.

        Called only when a probe collected fewer replies than there are
        subscribers on the channel. A subscriber Redis still counts but
        that no longer answers is a crashed or wedged process; because
        ownership lives in the connection, killing that connection is
        precisely what releases its lock, and the next probe then sees a
        consistent channel again.

        Every entry in ``CLIENT LIST`` is matched against the two naming
        schemes this package has used:

        - exactly `legacy_client_name`: a portalocker 3.2.0 or older
          holder. Killed unless some legacy reply arrived in this probe,
          since old holders are indistinguishable from one another.
        - `legacy_client_name` plus a `holder_id` suffix: a current
          holder. Killed unless that exact holder id replied.

        This lock names its own connection the same way, so the caller
        must include its own reply in `responding_holders` or it will
        kill itself. It does: a probing lock is subscribed to its own
        channel and answers its own ping.

        Args:
            connection: The connection to run ``CLIENT LIST`` and
                ``CLIENT KILL`` on.
            responding_holders: The holders that did answer this probe.
                Anything named like a holder of this channel but absent
                from this list is considered crashed.
        c                ó*   — h | ]}|j         °	|j        ’ŒS r   )r   r   ©Ú.0Úholders     r   ú	<setcomp>z4RedisLock._kill_unavailable_locks.<locals>.<setcomp>¤  s2   € ð +
ð +
ð +
Ø!'¸&¼-ð+
ØÔð+
ð +
ð +
r   c              3  ó$   K  — | ]}|j         V — Œd S ©N)r   rŸ   s     r   ú	<genexpr>z4RedisLock._kill_unavailable_locks.<locals>.<genexpr>§  s$   è è € Ð$IÐ$I°v V¤]Ð$IÐ$IÐ$IÐ$IÐ$IÐ$Ir   r{   ÚnameÚ ú$Killing unavailable redis client: %rÚidN)
ÚlistÚanyr|   Úclient_listrl   Ú
startswithÚremoveprefixrq   ÚwarningÚclient_kill_filter)r)   r7   r›   ÚholdersÚresponding_holder_idsÚlegacy_respondedÚclient_name_prefixÚclientsÚclient_r}   Úunavailables              r   Ú_kill_unavailable_locksz!RedisLock._kill_unavailable_locks€  s?  € õF *.Ð.@Ñ)AÔ)Aˆð+
ð +
Ø+2ð+
ñ +
ô +
Ðõ "%Ð$IÐ$IÀÐ$IÑ$IÔ$IÑ!IÔ!IÐØ%)Ô%<Ð"?Ð"?Ð"?ÐØ(2×(>Ò(>Ñ(@Ô(@ˆØð 	Að 	AˆGØ&Ÿ{š{¨6°2Ñ6Ô6ˆKà˜tÔ6Ò6ÐOÐ?OÐ;Oð!ð ×&Ò&Ð'9Ñ:Ô:ð -Ø×,Ò,Ð-?Ñ@Ô@Ø,ð-ð	 ð ð AÝ—’Ø:Øñô ð ð ×-Ò-¨g¯kªk¸$Ñ.?Ô.?Ñ@Ô@Ð@øð	Að 	Ar   Úexpected_subscribersúlist[RedisLockHolder] | Nonec                ón  — | j         › dt          j        ¦   «         j        › �}t	          | j        |dz  ¦  «        }|                      |¦  «        }i }d}	 |                     |¦  «         |                      ||¦  «        D ]H}	t          j
        d|                     |¬¦  «        ¦  «        }
|
r|
                     d¦  «        dk    r nŒI|                     | j         t          j        d|d	œ¦  «        ¦  «         |                      ||¦  «        D ]¥}	t          j
        d|                     |¬¦  «        ¦  «        }|rx|                     d¦  «        d
k    r_|                      |                     d¦  «        |¦  «        }|||j        <   |t%          |j        ¦  «        z  }t)          |¦  «        |k    r nŒ¦|                      |¦  «        }t,                               d| j        |t)          |¦  «        |¦  «         ||k    r	 |                     ¦   «          dS t)          |¦  «        |k     r?|                      ||                     ¦   «         ¦  «         	 |                     ¦   «          dS t7          |                     ¦   «         ¦  «        |                     ¦   «          S # |                     ¦   «          w xY w)a  Probe the channel and report who is holding the lock.

        Publishes a ping on the lock channel carrying a private,
        single-use response channel (``<channel>-<uuid4>``) and gathers
        the answers. That channel is subscribed *and its subscription
        confirmed* before the ping goes out, so a fast holder cannot
        reply into a subscription that is not listening yet; the
        confirmation frame is drained here rather than counted as a
        reply. That wait is bounded by ``timeout``: if no confirmation
        arrives in time the ping is published anyway, and replies that
        beat the subscription are missed, which shows up as an
        inconclusive probe. The probe uses its own short-lived pubsub,
        which is always closed again, so the subscription that holds the
        lock is never disturbed.

        Answers are keyed by holder id, so a holder that answers twice is
        counted once, and collection stops as soon as
        `expected_subscribers` distinct holders have replied.

        Returning `None` is not the same as returning an empty list, and
        the difference is the reason `_resolve_lock_holders` guards every
        branch on ``holders is not None``:

        - `None` means *could not determine*. The probe is unusable and
          the only safe response is to try again. Reading it as "nobody
          holds the lock" would hand out a lock that somebody else may
          well be holding.
        - A list is a positive statement about who is there, and can be
          acted on. It always contains this lock itself, because a
          probing lock is subscribed to its own channel and answers its
          own ping. An empty list would mean nobody at all is there, but
          `acquire` never asks in that situation: it short-circuits when
          it is the only subscriber.

        A probe is inconclusive in two ways:

        1. The subscriber count changed while the probe was running
           (``current != expected``). Someone joined or left, so the
           replies describe a channel that no longer exists in that
           shape, and a decision made from them could be wrong for
           either party.
        2. Fewer holders replied than there were subscribers. Somebody
           counted by Redis is not answering, which normally means it
           crashed, though a holder too slow to answer inside ``timeout``
           is treated the same way;
           `_kill_unavailable_locks` reaps those connections and the
           probe still reports inconclusive so that the caller retries
           against the cleaned-up channel.

        Args:
            connection: The connection to publish the ping on and to run
                the subscriber count against.
            expected_subscribers: How many subscribers the caller counted
                just before probing. This is both the target number of
                replies and the value the count is re-checked against.
            timeout: Seconds to spend waiting for the subscribe
                confirmation and, separately, for the replies. Polling
                uses `thread_sleep_time` or a tenth of this timeout,
                whichever is smaller.

        Returns:
            The holders that answered, or `None` when the probe was
            inconclusive.
        r{   r=   r   rG   ©r5   rh   r’   Úping)re   rj   re   ri   z6Redis lock %s probe expected=%d received=%d current=%dN)r3   rL   rM   rN   ÚminrE   r`   r’   rŠ   r]   r^   Úget_messagerl   rt   rm   ru   rš   r   ra   r   Úlenrd   rq   rr   Úcloser¸   Úvaluesrª   )r)   r7   r¹   r5   rj   rB   r8   r±   r—   Ú_Úconfirmationre   r¡   Úcurrent_subscriberss                 r   Ú_collect_lock_holderszRedisLock._collect_lock_holdersº  sÎ  € ðL $(¤<Ð DÐ Dµ$´*±,´,Ô2BÐ DÐ DÐÝ # DÔ$:¸GÀb¹LÑ IÔ IˆØ&*×&6Ò&6°zÑ&BÔ&BˆØ.0ˆØˆð2	Ø×ÒÐ-Ñ.Ô.Ð.Ø×,Ò,¨W°nÑEÔEð ð �Ý=C¼[Ø2Ø×&Ò&¨~Ð&Ñ>Ô>ñ>ô >�ð  ð  L×$4Ò$4°VÑ$<Ô$<ÀÒ$KÐ$KØ�Eøà×ÒØ”Ý”
à#)Ø,<ðð ñô ñô ð ð ×,Ò,¨W°nÑEÔEð ð �Ý8>¼Ø2Ø×&Ò&¨~Ð&Ñ>Ô>ñ9ô 9�ð ð ˜wŸ{š{¨6Ñ2Ô2°iÒ?Ð?Ø.2×.GÒ.GØŸš FÑ+Ô+Ø$ñ/ô /�Fð 17�G˜FÔ,Ñ-Ø ¥C¨¬Ñ$6Ô$6Ñ6�LÝ˜7‘|”|Ð';Ò;Ð;Ø˜øà'+×'AÒ'AÀ*Ñ'MÔ'MÐÝ�LŠLØHØ”Ø$Ý�G‘”Ø#ñô ð ð #Ð&:Ò:Ð:Øð �LŠL‰NŒNˆNˆNˆNõ �7‰|Œ|Ð2Ò2Ð2Ø×,Ò,¨Z¸¿ºÑ9IÔ9IÑJÔJÐJØð �LŠL‰NŒNˆNˆNˆNõ ˜ŸšÑ(Ô(Ñ)Ô)à�LŠL‰NŒNˆNˆNøˆF�LŠL‰NŒNˆNˆNøøøs   ÁF+J È;J É) J ÊJ4r±   úlist[RedisLockHolder]c                óh   — | j         t          j        j        k    ot	          d„ |D ¦   «         ¦  «        S )ak  Report whether this lock may join the holders already present.

        The whole compatibility matrix fits in one expression because
        only one combination is allowed::

            our flags   the holders present       result
            ---------   -------------------       ------
            SHARED      all SHARED                compatible
            SHARED      any PENDING or EXCLUSIVE  not compatible
            EXCLUSIVE   anything at all           not compatible

        An exclusive lock never joins anybody; it goes through the
        election in `_writer_is_elected` instead. A reader joins only a
        set of pure readers, and a single `RedisLockMode.PENDING` holder
        is enough to keep it out - that is the rule that stops an endless
        stream of readers from starving a waiting writer. Legacy holders
        are recorded as `RedisLockMode.EXCLUSIVE`, so an old participant
        blocks readers too.

        This lock's own reply is part of `holders`, and a shared lock
        advertises `RedisLockMode.SHARED` from construction onwards, so
        seeing itself in the list never makes it incompatible with
        itself.

        Args:
            holders: The holders returned by a conclusive probe.

        Returns:
            True when this lock can be added to the existing holders
            without violating exclusivity.
        c              3  ó<   K  — | ]}|j         t          j        u V — Œd S r¤   ©r   r	   r   rŸ   s     r   r¥   z4RedisLock._holders_are_compatible.<locals>.<genexpr>\  sE   è è € ð @
ð @
Ø4:ˆFŒK�=Ô/Ð/ð@
ð @
ð @
ð @
ð @
ð @
r   )r;   r   rJ   r   Úall)r)   r±   s     r   Ú_holders_are_compatiblez!RedisLock._holders_are_compatible9  sL   € ðF Œz�YÔ0Ô7Ò7ð 
½Cð @
ð @
Ø>Eð@
ñ @
ô @
ñ =
ô =
ð 	
r   c                óª   — t          d„ |D ¦   «         ¦  «        rdS t          d„ |D ¦   «         ¦  «        }t          |o|d         | j        k    ¦  «        S )aQ  Report whether this lock is the writer elected to go next.

        Returns False at once if any holder is already
        `RedisLockMode.EXCLUSIVE`: the lock is owned, so there is nothing
        to elect. Otherwise the ids of every `RedisLockMode.PENDING`
        holder are sorted and the lowest one wins.

        Sorting is the entire trick, and it is worth spelling out why it
        works. There is no coordinator here, and no lock to take before
        taking the lock. What every contender does have is the result of
        its own probe, and each probe asked the same channel at
        approximately the same time, so they all see the same set of
        pending ids. Sorting that set is a pure function of its contents,
        so every contender independently computes the *same* winner, and
        only the one whose own `holder_id` sorts first concludes that it
        won. No message needs to be exchanged to agree.

        Contenders whose probes disagree - someone joined halfway
        through - do not corrupt the outcome, because a probe taken
        during a membership change is discarded upstream:
        `_collect_lock_holders` returns `None` when the subscriber count
        moved. The losers simply retry, and a loser that keeps losing is
        bounded by the caller's timeout, not by the election.

        Holder ids are uuid4 hex strings, so the resulting order is
        arbitrary but stable. It is a tie-break, not a priority: this is
        not a fair queue and a writer is not guaranteed to be served
        before writers that arrive later.

        `RedisLockMode.SHARED` holders do not block the election, so a
        writer can be elected while readers are still draining. Being
        elected is not the same as holding the lock; only
        `_resolve_lock_holders` converts election into ownership, and
        only once no shared holder is left.

        Args:
            holders: The holders returned by a conclusive probe,
                including this lock's own record.

        Returns:
            True when this lock is the pending writer with the lowest
            holder id and nobody holds the lock exclusively.

        Example:
            >>> from portalocker import redis
            >>> lock = redis.RedisLock('some_channel')
            >>> lock.holder_id = 'bbb'
            >>> pending = redis.RedisLockMode.PENDING
            >>> lock._writer_is_elected(
            ...     [
            ...         redis.RedisLockHolder('aaa', pending),
            ...         redis.RedisLockHolder('bbb', pending),
            ...     ]
            ... )
            False
            >>> lock._writer_is_elected(
            ...     [
            ...         redis.RedisLockHolder('bbb', pending),
            ...         redis.RedisLockHolder('ccc', pending),
            ...     ]
            ... )
            True
        c              3  ó<   K  — | ]}|j         t          j        u V — Œd S r¤   )r   r	   r   rŸ   s     r   r¥   z/RedisLock._writer_is_elected.<locals>.<genexpr>£  s,   è è € ÐLÐL¸&ˆvŒ{�mÔ5Ð5ÐLÐLÐLÐLÐLÐLr   Fc              3  óJ   K  — | ]}|j         t          j        u ¯|j        V — Œd S r¤   )r   r	   r   r   rŸ   s     r   r¥   z/RedisLock._writer_is_elected.<locals>.<genexpr>¥  sA   è è € ð /
ð /
àØŒ{�mÔ3Ð3Ð3ð Ôà3Ð3Ð3Ð3ð/
ð /
r   r   )r«   Úsortedr   r   )r)   r±   Úpending_holder_idss      r   Ú_writer_is_electedzRedisLock._writer_is_elected`  s~   € õF ÐLÐLÀGÐLÑLÔLÑLÔLð 	Ø�5Ý(.ð /
ð /
à!ð/
ñ /
ô /
ñ )
ô )
Ðõ
 ØÐJÐ#5°aÔ#8¸D¼NÒ#Jñ
ô 
ð 	
r   c                ó
  — |�|                       |¦  «        rdS |duo.| j        t          j        j        k    o|                      |¦  «        }|r`d| _        |r'|                      ¦   «          t          j	        ¦   «         ‚|�,t          d„ |D ¦   «         ¦  «        st          j        | _        dS dS |€	| j        rdS |                      ¦   «          t                               d| j        ¦  «         |rt          j	        ¦   «         ‚dS )aj  Decide what to do with the result of one probe.

        This is the only place where an observation becomes an action.
        Every branch is guarded on ``holders is not None``, because an
        inconclusive probe must never be read as "the lock is free".

        The outcomes, in the order they are tested:

        - **Compatible holders** (see `_holders_are_compatible`): the
          lock is now held. The subscription opened for the probe is
          exactly the subscription that holds it, so nothing more is
          needed.
        - **Elected writer, no readers left** (see `_writer_is_elected`):
          `mode` is promoted from `RedisLockMode.PENDING` to
          `RedisLockMode.EXCLUSIVE`, which is what every later probe by
          anybody else will see, and the lock is held.
        - **Elected writer, readers still holding**: the election is
          remembered in `writer_elected` and the subscription is kept, so
          this lock's `RedisLockMode.PENDING` record keeps new readers
          out while the existing ones drain. The caller retries.
        - **Inconclusive probe while already elected**: the subscription
          is kept and the caller retries. An elected writer must not drop
          its pending record over a single noisy probe; doing so would
          let new readers in and could forfeit an election it had already
          won, since `release` clears `writer_elected`.
        - **Anything else**: somebody incompatible is there, or the probe
          was inconclusive and this lock is not elected. The
          subscription is released before retrying. That release is the
          point rather than a detail: a waiter that stayed subscribed
          would keep inflating the subscriber count that everybody
          else's probe has to match exactly.

        With `fail_when_locked` the caller does not want to wait, so the
        first attempt that does not end in ownership raises instead of
        returning. An elected writer always raises here, even when no
        readers remain and the lock could have been taken outright,
        because that check runs before the promotion to
        `RedisLockMode.EXCLUSIVE`; reaching this method at all means the
        channel is contended. The one exception is an already-elected
        writer facing
        an inconclusive probe, which keeps retrying because it is not
        contention that stopped it.

        Args:
            holders: A conclusive probe result, or `None` when the probe
                could not determine the state of the channel.
            fail_when_locked: Give up immediately instead of retrying.

        Returns:
            True when the lock is now held and `acquire` may return;
            False when the caller should retry.

        Raises:
            AlreadyLocked: `fail_when_locked` was set and this attempt
                did not end in ownership.
        NTc              3  ó<   K  — | ]}|j         t          j        u V — Œd S r¤   rÊ   rŸ   s     r   r¥   z2RedisLock._resolve_lock_holders.<locals>.<genexpr>ø  s=   è è € ð /ð /Ø8>�”�}Ô3Ð3ð/ð /ð /ð /ð /ð /r   FzRedis lock %s released to retry)rÌ   r;   r   rJ   r   rÒ   r<   r”   r   ÚAlreadyLockedr«   r	   r   rq   rr   r   )r)   r±   rC   Úwriter_is_electeds       r   Ú_resolve_lock_holderszRedisLock._resolve_lock_holders®  s+  € ðz Ð 4×#?Ò#?ÀÑ#HÔ#HÐØ�4ð ˜4Ðð 1Ø”
�iÔ1Ô;Ò;ð1à×'Ò'¨Ñ0Ô0ð 	ð
 ð 
	Ø"&ˆDÔØð 1Ø—’‘”�Ý Ô.Ñ0Ô0Ð0ØÐ"­3ð /ð /ØBIð/ñ /ô /ñ ,ô ,Ð"õ *Ô3�”	Ø�tØ�5àˆ?˜tÔ2ˆ?Ø�5à�Š‰ŒˆÝ�ŠÐ6¸¼ÑGÔGÐGØð 	-ÝÔ*Ñ,Ô,Ð,Øˆur   c                ó  — t          j        dt          j        || j        d¦  «        ¦  «        }t          j        dt          j        || j        d¦  «        ¦  «        }t          j        dt          j        || j        d¦  «        ¦  «        }| j        r
J d¦   «         ‚| j        t          j
        j        k    rt          j        | _        d| _        |                      ¦   «         }|                      ||¦  «        D ]ë}| j        €|                      |¦  «         |                      |¦  «        }	t(                               d| j        | j        j        |	¦  «         |	dk    r/| j        t          j
        j        k    rt          j        | _        | c S |                      ||	| j        ¦  «        }
t(                               d	| j        |
¦  «         |                      |
|¦  «        r| c S Œì|                      ¦   «          t9          j        ¦   «         ‚)
a{  Acquire the lock, retrying until it is free or time runs out.

        Every attempt subscribes to the channel if this lock is not
        subscribed already, then either takes the lock outright or hands
        a probe result to `_resolve_lock_holders`:

        1. Count the subscribers. Being the only one means nobody else is
           on the channel, so the lock is free and is taken immediately;
           an exclusive lock promotes itself from `RedisLockMode.PENDING`
           to `RedisLockMode.EXCLUSIVE` here. This is the uncontended
           fast path and costs one round trip.
        2. Otherwise probe the channel with `_collect_lock_holders` and
           let `_resolve_lock_holders` decide.

        A failed attempt normally unsubscribes again, so the next
        iteration subscribes from scratch; an elected writer is the
        exception and holds on to its subscription between attempts.

        `fail_when_locked` turns the retry loop into a single attempt
        against a contended channel: rather than polling until the
        timeout expires against a holder that has demonstrably answered a
        ping, the first attempt that does not end in ownership raises
        `AlreadyLocked`. An elected writer always raises here too, even
        when no readers remain and the lock could have been taken
        outright.

        If subscribing itself fails, `_start_subscription` rolls back
        before re-raising, so the original error propagates with the lock
        left inactive and the same object can be used again.

        Args:
            timeout: Seconds to keep retrying. Defaults to the instance's
                `timeout`, itself defaulting to `utils.DEFAULT_TIMEOUT`.
                Zero still makes exactly one attempt.
            check_interval: Base seconds to wait between attempts,
                jittered by `_timeout_generator`. Defaults to the
                instance's `check_interval`.
            fail_when_locked: Raise `AlreadyLocked` on the first
                unsuccessful attempt instead of retrying. Defaults to the
                instance's `fail_when_locked`.

        Returns:
            This lock, so ``with RedisLock(...) as lock`` binds the lock
            itself rather than a file handle.

        Raises:
            ~portalocker.exceptions.AlreadyLocked: The timeout expired
                without acquiring the lock, or `fail_when_locked` was set
                and the first attempt did not succeed.
            AssertionError: This instance is already holding a lock. A
                `RedisLock` is not reentrant and holds at most one lock
                at a time; use a second instance, which gets its own
                `holder_id`.

        Example:
            >>> import fakeredis
            >>> import portalocker
            >>> connection = fakeredis.FakeStrictRedis(
            ...     server=fakeredis.FakeServer(), decode_responses=True
            ... )
            >>> lock = portalocker.RedisLock(
            ...     'some_channel', connection=connection
            ... )
            >>> lock.acquire(timeout=1) is lock
            True
            >>> lock.release()
        r4   r�   r   FzThis lock is already activeNz-Redis lock %s mode=%s observed %d subscribersr   z!Redis lock %s observed holders=%r)r]   r^   r   Úcoalescer5   rB   rC   r8   r;   r   rJ   r   r	   r   r   r<   rZ   rŠ   r•   rd   rq   rr   r   rS   rÆ   rF   r×   r”   r   rÕ   )r)   r5   rB   rC   Úeffective_timeoutÚeffective_check_intervalÚeffective_fail_when_lockedr7   rÃ   Úsubscribersr±   s              r   ÚacquirezRedisLock.acquire  s  € õR $*¤;ØÝŒN˜7 D¤L°#Ñ6Ô6ñ$
ô $
Ðõ +1¬+ØÝŒN˜>¨4Ô+>ÀÑDÔDñ+
ô +
Ð õ ,2¬;ØÝŒNÐ+¨TÔ-BÀEÑJÔJñ,
ô ,
Ð"ð
 ”;Ð=Ð=Ð =Ñ=Ô=ˆØŒ:�Ô,Ô6Ò6Ð6Ý%Ô-ˆDŒIØ"'ˆDÔØ)-×)<Ò)<Ñ)>Ô)>ˆ
à×(Ò(ØØ$ñ
ô 
ð  	ð  	ˆAð Œ{Ð"Ø×(Ò(¨Ñ4Ô4Ð4Ø#×9Ò9¸*ÑEÔEˆKÝ�LŠLØ?Ø”Ø”	”Øñ	ô ð ð ˜aÒÐØ”:¥Ô!4Ô!>Ò>Ð>Ý -Ô 7�D”IØ���à48×4NÒ4NØØØÔ(ñ5ô 5ˆGõ
 �LŠLØ3Ø”Øñô ð ð
 ×)Ò)ØØ*ñô ð ð ���ð	ð 	�Š‰ŒˆÝÔ&Ñ(Ô(Ð(r   c           	     ó6  — | j         › dt          j        ¦   «         › �}t          | j        |dz  ¦  «        }|                      |¦  «        }	 |                     |¦  «         |                      ||¦  «        D ]H}t          j        d| 	                    |¬¦  «        ¦  «        }|r| 
                    d¦  «        dk    r nŒI|                     | j         t          j        t          |d¬¦  «        ¦  «        ¦  «         |                      ||¦  «        D ]]}t          j        d| 	                    |¬¦  «        ¦  «        }|r0| 
                    d¦  «        d	k    r |                     ¦   «          d
S Œ^|                     d¦  «        }	|	D ]c}
|
 
                    d¦  «        | j        k    rCt$                               d|
¦  «         |                     |
 
                    d¦  «        ¦  «         Œd	 |                     ¦   «          dS # |                     ¦   «          w xY w)aÙ  Ask whether anyone is alive on the channel, and reap if not.

        The public liveness check from before 4.0.0. `acquire` no longer
        uses it: it probes with `_collect_lock_holders` and reaps with
        `_kill_unavailable_locks`, which understand individual holders
        and lock modes. This method predates holder ids and answers only
        the coarser question "is anybody answering on this channel?".

        The ping is published only after the subscription's own
        confirmation frame has been consumed, or the wait for it times
        out. Redis queues a ``subscribe`` confirmation the moment a
        subscription is made; before 4.0.0 the reply poll accepted any
        message, so that confirmation was read as a reply, a crashed
        holder was reported as alive and stale locks were never reaped.
        The poll below now also requires ``type == 'message'``, and
        draining the confirmation first guarantees that the subscription
        is active before the ping goes out, so a real reply cannot be
        published into a subscription that is not listening yet.

        Note:
            The reap step matches ``CLIENT LIST`` entries against
            `client_name`, which since 4.0.0 carries this instance's own
            `holder_id`. On a live server that name identifies only this
            lock's own connection, so another process's crashed holder is
            not matched here; reaping across holders is what
            `_kill_unavailable_locks` does during `acquire`.

        Args:
            connection: The connection to probe and to reap on.
            timeout: Seconds to wait for the subscribe confirmation and,
                separately, for a reply, so a fully silent channel can
                take up to twice this long.

        Returns:
            True as soon as any reply arrives. `None` when nothing
            answered in time, after killing the matching pubsub
            connections. False is never returned.
        r{   r=   rG   r¼   rh   r’   r½   )rj   re   re   Tr8   r¦   r¨   r©   N)r3   r„   r¾   rE   r`   r’   rŠ   r]   r^   r¿   rl   rt   rm   ru   rI   rÁ   r¬   r}   rq   r¯   r°   )r)   r7   r5   rj   rB   r8   rÃ   rÄ   re   rµ   r¶   s              r   Úcheck_or_kill_lockzRedisLock.check_or_kill_lock‰  s>  € ðX #œlÐ>Ð>­V¬]©_¬_Ð>Ð>ÐÝ˜TÔ3°W¸r±\ÑBÔBˆà×!Ò! *Ñ-Ô-ˆð-	Ø×ÒÐ-Ñ.Ô.Ð.ð ×,Ò,¨W°nÑEÔEð ð �Ý%œ{Ø2Ø×&Ò&¨~Ð&Ñ>Ô>ñ ô  �ð  ð  L×$4Ò$4°VÑ$<Ô$<ÀÒ$KÐ$KØ�Eøà×ÒØ”Ý”
ÝØ)9Ø &ðñ ô ñô ñô ð ð ×,Ò,¨W°nÑEÔEð  ð  �Ý œ+Ø2Ø×&Ò&¨~Ð&Ñ>Ô>ñô �ð ð  ˜wŸ{š{¨6Ñ2Ô2°iÒ?Ð?Øð �LŠL‰NŒNˆNˆNˆNøð -7×,BÒ,BÀ8Ñ,LÔ,LˆGØ"ð Eð E�Ø—;’;˜vÑ&Ô&¨$Ô*:Ò:Ð:Ý—N’NØ>Øñô ð ð ×1Ò1°'·+²+¸dÑ2CÔ2CÑDÔDÐDøØà�LŠL‰NŒNˆNˆNˆNøˆF�LŠL‰NŒNˆNˆNøøøs   ÁDH Å/A<H ÈHc                ó¬  — d| _         | j        rM| j                             ¦   «          | j                             ¦   «          d| _        t	          j        d¦  «         | j        r?| j                             | j        ¦  «         | j         	                    ¦   «          d| _        | j
        r)| j        �$| j         	                    ¦   «          d| _        dS dS dS )a^  Give up the lock and undo everything `acquire` set up.

        Stops and joins the keep-alive thread, unsubscribes and closes
        the pubsub connection, and forgets any election this lock had
        won. A connection the lock created itself is closed and cleared,
        so the next `get_connection` builds a fresh one; a connection
        supplied by the caller is left alone.

        Dropping the subscription is not merely cleanup, it *is* the
        release: other processes learn the lock is free by no longer
        seeing this subscriber, with no key to delete and no expiry to
        wait for.

        The same method doubles as the back-off between attempts.
        `_resolve_lock_holders` calls it after an unsuccessful probe so
        that a waiting lock stops being counted as a subscriber, and
        `_start_subscription` calls it to roll back a subscribe that
        failed halfway.

        Calling this when nothing was acquired is harmless - it still
        closes a self-created connection if one exists - which is what
        makes both that rollback and `__del__` safe.
        FNr�   )r<   r2   ÚstopÚjoinr‚   r…   r8   Úunsubscriber3   rÁ   r9   r7   rY   s    r   r”   zRedisLock.releaseè  sÞ   € ð0 $ˆÔØŒ;ð 	ØŒK×ÒÑÔÐØŒK×ÒÑÔÐØˆDŒKÝŒJ�tÑÔÐàŒ;ð 	àŒK×#Ò#Ø”ñô ð ð ŒK×ÒÑÔÐØˆDŒKð Ô ð 	# T¤_Ð%@ØŒO×!Ò!Ñ#Ô#Ð#Ø"ˆDŒOˆOˆOð	#ð 	#Ð%@Ð%@r   c                ó.   — |                       ¦   «          dS )a~  Release the lock when the object is garbage collected.

        A safety net for a lock that was never released explicitly, not a
        substitute for `release` or a ``with`` block. CPython's reference
        counting usually runs this promptly, but PyPy collects whenever
        it sees fit, and nothing runs at all if the interpreter exits
        while a reference is still alive.

        That last case is harmless here, which is the advantage of
        holding a lock in a connection rather than in a key: the process
        exits, the daemon reader thread goes with it, the socket closes
        and Redis releases the lock. Unlike
        `utils.LockBase.__del__` this does not suppress errors, so a
        failure during collection surfaces as the interpreter's
        "Exception ignored in" message and cannot be caught by the code
        that dropped the reference.
        N)r”   rY   s    r   Ú__del__zRedisLock.__del__  s   € ð$ 	�Š‰Œˆˆˆr   )r3   r   r7   r6   r5   rA   rB   rA   rC   rD   rE   r4   rF   r4   r1   rG   r;   r:   r!   r"   )r!   rT   )r7   rT   r!   r[   )r7   rT   r!   ra   )re   rf   r!   r"   )r!   r   )r5   rA   rB   rA   r!   r   )r7   rT   r!   r"   )rw   r–   r—   ra   r!   r   )r7   rT   r›   rœ   r!   r"   )r7   rT   r¹   ra   r5   r4   r!   rº   )r±   rÇ   r!   r   )r±   rº   rC   r   r!   r   )NNN)r5   rA   rB   rA   rC   rD   r!   r/   )r7   rT   r5   r4   r!   rD   r+   )"r   r   r   r   r   r8   rI   r@   ÚDEFAULT_THREAD_SLEEP_TIMEÚDEFAULT_UNAVAILABLE_TIMEOUTr   rJ   r   rQ   rZ   r`   rd   ry   Úpropertyr}   r|   rŠ   r•   rš   r¸   rÆ   rÌ   rÒ   r×   rÞ   rà   r”   ræ   r,   r-   s   @r   r/   r/   ©   sâ  ø€ € € € € € ð?ð ?ðB (Ð'Ð'Ñ'Ø%Ð%Ð%Ñ%Ø€L€L�LØ€N€N�NØ)Ð)Ð)Ñ)Ø)-€FÐ-Ð-Ð-Ñ-ØÐÐÑØÐÐÑØ€N€N�NØÐÐÑØÐÐÑàCGÀ4Ø ØðDñ Dô DÐð ð ð ñ ð 15Ø $Ø'+Ø(-Ø#<Ø%@Ø59Ø%.Ô%8Ô%BðD
ð D
ð D
ð D
ð D
ð D
ð D
ðLð ð ð ð"
ð 
ð 
ð 
ð<ð <ð <ð <ð8
ð 8
ð 8
ð 8
ðt ð=ð =ð =ñ „Xð=ð. ð&ð &ð &ñ „Xð&ð42ð 2ð 2ð 2ðh>ð >ð >ð >ð@<
ð <
ð <
ð <
ð|8Að 8Að 8Að 8Aðt}ð }ð }ð }ð~%
ð %
ð %
ð %
ðNL
ð L
ð L
ð L
ð\Xð Xð Xð Xðx !%Ø'+Ø(,ð	)ð )ð )ð )ð )ðB]ð ]ð ]ð ]ð~+#ð +#ð +#ð +#ðZð ð ð ð ð ð ð r   r/   ) r   Ú
__future__r   r'   Úenumrm   Úloggingr„   r‚   r]   rL   Úredis.clientrV   r§   r   r   r   Ú	getLoggerr   rq   rè   rç   rv   r   ÚEnumr	   Ú
NamedTupler   rW   r    ÚLockBaser/   r   r   r   ú<module>rò      s�  ðð
6ð 6ðp #Ð "Ð "Ð "Ð "Ð "à €€€Ø €€€Ø €€€Ø €€€Ø €€€Ø €€€Ø €€€Ø €€€à Ð Ð Ð à *Ð *Ð *Ð *Ð *Ð *Ð *Ð *Ð *Ð *à	ˆÔ	˜8Ñ	$Ô	$€ð  Ð ð  Ð ð  Ð ðð ð ð ð �C˜œñ ô ð ð.ð ð ð ð �fÔ'ñ ô ð ð4ð ð ð ð ˜œÔ8ñ ô ð ð>~ð ~ð ~ð ~ð ~�”˜{Ô+ñ ~ô ~ð ~ð ~ð ~r   