We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
v4.3.3 continues to contain backwards incompatible change to ``redis.lock.Lock``
Hey this is a continuation of #2209.

The API change made in https://github.com/redis/redis-py/pull/2210/files does not restore backwards compatibility.

We are calling acquire like this:

```py
lock = redis.lock(
    "_lock{0}".format(key),
    timeout=self.lock_timeout,
    sleep=self.lock_sleep,
    thread_local=self.thread_local_lock,
)

lock.acquire(False)

```

this is broken by fa0be7671de6be85f859cbb57a31531b2482c9e1 which changes the API of lock.acquire() to use kw-only arguments.

since in #2209 it looks like py-redis has the willingness to revert these changes, hoping you can do that here also.  otherwise we have a dogpile.cache patch ready to go out to work around this.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `redis/lock.py`
Content:
```
1 import threading
2 import time as mod_time
3 import uuid
4 from types import SimpleNamespace, TracebackType
5 from typing import Optional, Type
6 
7 from redis.exceptions import LockError, LockNotOwnedError
8 from redis.typing import Number
9 
10 
11 class Lock:
12     """
13     A shared, distributed Lock. Using Redis for locking allows the Lock
14     to be shared across processes and/or machines.
15 
16     It's left to the user to resolve deadlock issues and make sure
17     multiple clients play nicely together.
18     """
19 
20     lua_release = None
21     lua_extend = None
22     lua_reacquire = None
23 
24     # KEYS[1] - lock name
25     # ARGV[1] - token
26     # return 1 if the lock was released, otherwise 0
27     LUA_RELEASE_SCRIPT = """
28         local token = redis.call('get', KEYS[1])
29         if not token or token ~= ARGV[1] then
30             return 0
31         end
32         redis.call('del', KEYS[1])
33         return 1
34     """
35 
36     # KEYS[1] - lock name
37     # ARGV[1] - token
38     # ARGV[2] - additional milliseconds
39     # ARGV[3] - "0" if the additional time should be added to the lock's
40     #           existing ttl or "1" if the existing ttl should be replaced
41     # return 1 if the locks time was extended, otherwise 0
42     LUA_EXTEND_SCRIPT = """
43         local token = redis.call('get', KEYS[1])
44         if not token or token ~= ARGV[1] then
45             return 0
46         end
47         local expiration = redis.call('pttl', KEYS[1])
48         if not expiration then
49             expiration = 0
50         end
51         if expiration < 0 then
52             return 0
53         end
54 
55         local newttl = ARGV[2]
56         if ARGV[3] == "0" then
57             newttl = ARGV[2] + expiration
58         end
59         redis.call('pexpire', KEYS[1], newttl)
60         return 1
61     """
62 
63     # KEYS[1] - lock name
64     # ARGV[1] - token
65     # ARGV[2] - milliseconds
66     # return 1 if the locks time was reacquired, otherwise 0
67     LUA_REACQUIRE_SCRIPT = """
68         local token = redis.call('get', KEYS[1])
69         if not token or token ~= ARGV[1] then
70             return 0
71         end
72         redis.call('pexpire', KEYS[1], ARGV[2])
73         return 1
74     """
75 
76     def __init__(
77         self,
78         redis,
79         name: str,
80         timeout: Optional[Number] = None,
81         sleep: Number = 0.1,
82         blocking: bool = True,
83         blocking_timeout: Optional[Number] = None,
84         thread_local: bool = True,
85     ):
86         """
87         Create a new Lock instance named ``name`` using the Redis client
88         supplied by ``redis``.
89 
90         ``timeout`` indicates a maximum life for the lock in seconds.
91         By default, it will remain locked until release() is called.
92         ``timeout`` can be specified as a float or integer, both representing
93         the number of seconds to wait.
94 
95         ``sleep`` indicates the amount of time to sleep in seconds per loop
96         iteration when the lock is in blocking mode and another client is
97         currently holding the lock.
98 
99         ``blocking`` indicates whether calling ``acquire`` should block until
100         the lock has been acquired or to fail immediately, causing ``acquire``
101         to return False and the lock not being acquired. Defaults to True.
102         Note this value can be overridden by passing a ``blocking``
103         argument to ``acquire``.
104 
105         ``blocking_timeout`` indicates the maximum amount of time in seconds to
106         spend trying to acquire the lock. A value of ``None`` indicates
107         continue trying forever. ``blocking_timeout`` can be specified as a
108         float or integer, both representing the number of seconds to wait.
109 
110         ``thread_local`` indicates whether the lock token is placed in
111         thread-local storage. By default, the token is placed in thread local
112         storage so that a thread only sees its token, not a token set by
113         another thread. Consider the following timeline:
114 
115             time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
116                      thread-1 sets the token to "abc"
117             time: 1, thread-2 blocks trying to acquire `my-lock` using the
118                      Lock instance.
119             time: 5, thread-1 has not yet completed. redis expires the lock
120                      key.
121             time: 5, thread-2 acquired `my-lock` now that it's available.
122                      thread-2 sets the token to "xyz"
123             time: 6, thread-1 finishes its work and calls release(). if the
124                      token is *not* stored in thread local storage, then
125                      thread-1 would see the token value as "xyz" and would be
126                      able to successfully release the thread-2's lock.
127 
128         In some use cases it's necessary to disable thread local storage. For
129         example, if you have code where one thread acquires a lock and passes
130         that lock instance to a worker thread to release later. If thread
131         local storage isn't disabled in this case, the worker thread won't see
132         the token set by the thread that acquired the lock. Our assumption
133         is that these cases aren't common and as such default to using
134         thread local storage.
135         """
136         self.redis = redis
137         self.name = name
138         self.timeout = timeout
139         self.sleep = sleep
140         self.blocking = blocking
141         self.blocking_timeout = blocking_timeout
142         self.thread_local = bool(thread_local)
143         self.local = threading.local() if self.thread_local else SimpleNamespace()
144         self.local.token = None
145         self.register_scripts()
146 
147     def register_scripts(self) -> None:
148         cls = self.__class__
149         client = self.redis
150         if cls.lua_release is None:
151             cls.lua_release = client.register_script(cls.LUA_RELEASE_SCRIPT)
152         if cls.lua_extend is None:
153             cls.lua_extend = client.register_script(cls.LUA_EXTEND_SCRIPT)
154         if cls.lua_reacquire is None:
155             cls.lua_reacquire = client.register_script(cls.LUA_REACQUIRE_SCRIPT)
156 
157     def __enter__(self) -> "Lock":
158         if self.acquire():
159             return self
160         raise LockError("Unable to acquire lock within the time specified")
161 
162     def __exit__(
163         self,
164         exc_type: Optional[Type[BaseException]],
165         exc_value: Optional[BaseException],
166         traceback: Optional[TracebackType],
167     ) -> None:
168         self.release()
169 
170     def acquire(
171         self,
172         *,
173         sleep: Optional[Number] = None,
174         blocking: Optional[bool] = None,
175         blocking_timeout: Optional[Number] = None,
176         token: Optional[str] = None,
177     ):
178         """
179         Use Redis to hold a shared, distributed lock named ``name``.
180         Returns True once the lock is acquired.
181 
182         If ``blocking`` is False, always return immediately. If the lock
183         was acquired, return True, otherwise return False.
184 
185         ``blocking_timeout`` specifies the maximum number of seconds to
186         wait trying to acquire the lock.
187 
188         ``token`` specifies the token value to be used. If provided, token
189         must be a bytes object or a string that can be encoded to a bytes
190         object with the default encoding. If a token isn't specified, a UUID
191         will be generated.
192         """
193         if sleep is None:
194             sleep = self.sleep
195         if token is None:
196             token = uuid.uuid1().hex.encode()
197         else:
198             encoder = self.redis.get_encoder()
199             token = encoder.encode(token)
200         if blocking is None:
201             blocking = self.blocking
202         if blocking_timeout is None:
203             blocking_timeout = self.blocking_timeout
204         stop_trying_at = None
205         if blocking_timeout is not None:
206             stop_trying_at = mod_time.monotonic() + blocking_timeout
207         while True:
208             if self.do_acquire(token):
209                 self.local.token = token
210                 return True
211             if not blocking:
212                 return False
213             next_try_at = mod_time.monotonic() + sleep
214             if stop_trying_at is not None and next_try_at > stop_trying_at:
215                 return False
216             mod_time.sleep(sleep)
217 
218     def do_acquire(self, token: str) -> bool:
219         if self.timeout:
220             # convert to milliseconds
221             timeout = int(self.timeout * 1000)
222         else:
223             timeout = None
224         if self.redis.set(self.name, token, nx=True, px=timeout):
225             return True
226         return False
227 
228     def locked(self) -> bool:
229         """
230         Returns True if this key is locked by any process, otherwise False.
231         """
232         return self.redis.get(self.name) is not None
233 
234     def owned(self) -> bool:
235         """
236         Returns True if this key is locked by this lock, otherwise False.
237         """
238         stored_token = self.redis.get(self.name)
239         # need to always compare bytes to bytes
240         # TODO: this can be simplified when the context manager is finished
241         if stored_token and not isinstance(stored_token, bytes):
242             encoder = self.redis.get_encoder()
243             stored_token = encoder.encode(stored_token)
244         return self.local.token is not None and stored_token == self.local.token
245 
246     def release(self) -> None:
247         """
248         Releases the already acquired lock
249         """
250         expected_token = self.local.token
251         if expected_token is None:
252             raise LockError("Cannot release an unlocked lock")
253         self.local.token = None
254         self.do_release(expected_token)
255 
256     def do_release(self, expected_token: str) -> None:
257         if not bool(
258             self.lua_release(keys=[self.name], args=[expected_token], client=self.redis)
259         ):
260             raise LockNotOwnedError("Cannot release a lock" " that's no longer owned")
261 
262     def extend(self, additional_time: int, replace_ttl: bool = False) -> bool:
263         """
264         Adds more time to an already acquired lock.
265 
266         ``additional_time`` can be specified as an integer or a float, both
267         representing the number of seconds to add.
268 
269         ``replace_ttl`` if False (the default), add `additional_time` to
270         the lock's existing ttl. If True, replace the lock's ttl with
271         `additional_time`.
272         """
273         if self.local.token is None:
274             raise LockError("Cannot extend an unlocked lock")
275         if self.timeout is None:
276             raise LockError("Cannot extend a lock with no timeout")
277         return self.do_extend(additional_time, replace_ttl)
278 
279     def do_extend(self, additional_time: int, replace_ttl: bool) -> bool:
280         additional_time = int(additional_time * 1000)
281         if not bool(
282             self.lua_extend(
283                 keys=[self.name],
284                 args=[self.local.token, additional_time, "1" if replace_ttl else "0"],
285                 client=self.redis,
286             )
287         ):
288             raise LockNotOwnedError("Cannot extend a lock that's no longer owned")
289         return True
290 
291     def reacquire(self) -> bool:
292         """
293         Resets a TTL of an already acquired lock back to a timeout value.
294         """
295         if self.local.token is None:
296             raise LockError("Cannot reacquire an unlocked lock")
297         if self.timeout is None:
298             raise LockError("Cannot reacquire a lock with no timeout")
299         return self.do_reacquire()
300 
301     def do_reacquire(self) -> bool:
302         timeout = int(self.timeout * 1000)
303         if not bool(
304             self.lua_reacquire(
305                 keys=[self.name], args=[self.local.token, timeout], client=self.redis
306             )
307         ):
308             raise LockNotOwnedError("Cannot reacquire a lock that's no longer owned")
309         return True
310
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/redis/lock.py b/redis/lock.py
--- a/redis/lock.py
+++ b/redis/lock.py
@@ -169,7 +169,6 @@
 
     def acquire(
         self,
-        *,
         sleep: Optional[Number] = None,
         blocking: Optional[bool] = None,
         blocking_timeout: Optional[Number] = None,

{"golden_diff": "diff --git a/redis/lock.py b/redis/lock.py\n--- a/redis/lock.py\n+++ b/redis/lock.py\n@@ -169,7 +169,6 @@\n \n     def acquire(\n         self,\n-        *,\n         sleep: Optional[Number] = None,\n         blocking: Optional[bool] = None,\n         blocking_timeout: Optional[Number] = None,\n", "issue": "v4.3.3 continues to contain backwards incompatible change to ``redis.lock.Lock``\nHey this is a continuation of #2209.\r\n\r\nThe API change made in https://github.com/redis/redis-py/pull/2210/files does not restore backwards compatibility.\r\n\r\nWe are calling acquire like this:\r\n\r\n```py\r\nlock = redis.lock(\r\n    \"_lock{0}\".format(key),\r\n    timeout=self.lock_timeout,\r\n    sleep=self.lock_sleep,\r\n    thread_local=self.thread_local_lock,\r\n)\r\n\r\nlock.acquire(False)\r\n\r\n```\r\n\r\nthis is broken by fa0be7671de6be85f859cbb57a31531b2482c9e1 which changes the API of lock.acquire() to use kw-only arguments.\r\n\r\nsince in #2209 it looks like py-redis has the willingness to revert these changes, hoping you can do that here also.  otherwise we have a dogpile.cache patch ready to go out to work around this.\n", "before_files": [{"content": "import threading\nimport time as mod_time\nimport uuid\nfrom types import SimpleNamespace, TracebackType\nfrom typing import Optional, Type\n\nfrom redis.exceptions import LockError, LockNotOwnedError\nfrom redis.typing import Number\n\n\nclass Lock:\n    \"\"\"\n    A shared, distributed Lock. Using Redis for locking allows the Lock\n    to be shared across processes and/or machines.\n\n    It's left to the user to resolve deadlock issues and make sure\n    multiple clients play nicely together.\n    \"\"\"\n\n    lua_release = None\n    lua_extend = None\n    lua_reacquire = None\n\n    # KEYS[1] - lock name\n    # ARGV[1] - token\n    # return 1 if the lock was released, otherwise 0\n    LUA_RELEASE_SCRIPT = \"\"\"\n        local token = redis.call('get', KEYS[1])\n        if not token or token ~= ARGV[1] then\n            return 0\n        end\n        redis.call('del', KEYS[1])\n        return 1\n    \"\"\"\n\n    # KEYS[1] - lock name\n    # ARGV[1] - token\n    # ARGV[2] - additional milliseconds\n    # ARGV[3] - \"0\" if the additional time should be added to the lock's\n    #           existing ttl or \"1\" if the existing ttl should be replaced\n    # return 1 if the locks time was extended, otherwise 0\n    LUA_EXTEND_SCRIPT = \"\"\"\n        local token = redis.call('get', KEYS[1])\n        if not token or token ~= ARGV[1] then\n            return 0\n        end\n        local expiration = redis.call('pttl', KEYS[1])\n        if not expiration then\n            expiration = 0\n        end\n        if expiration < 0 then\n            return 0\n        end\n\n        local newttl = ARGV[2]\n        if ARGV[3] == \"0\" then\n            newttl = ARGV[2] + expiration\n        end\n        redis.call('pexpire', KEYS[1], newttl)\n        return 1\n    \"\"\"\n\n    # KEYS[1] - lock name\n    # ARGV[1] - token\n    # ARGV[2] - milliseconds\n    # return 1 if the locks time was reacquired, otherwise 0\n    LUA_REACQUIRE_SCRIPT = \"\"\"\n        local token = redis.call('get', KEYS[1])\n        if not token or token ~= ARGV[1] then\n            return 0\n        end\n        redis.call('pexpire', KEYS[1], ARGV[2])\n        return 1\n    \"\"\"\n\n    def __init__(\n        self,\n        redis,\n        name: str,\n        timeout: Optional[Number] = None,\n        sleep: Number = 0.1,\n        blocking: bool = True,\n        blocking_timeout: Optional[Number] = None,\n        thread_local: bool = True,\n    ):\n        \"\"\"\n        Create a new Lock instance named ``name`` using the Redis client\n        supplied by ``redis``.\n\n        ``timeout`` indicates a maximum life for the lock in seconds.\n        By default, it will remain locked until release() is called.\n        ``timeout`` can be specified as a float or integer, both representing\n        the number of seconds to wait.\n\n        ``sleep`` indicates the amount of time to sleep in seconds per loop\n        iteration when the lock is in blocking mode and another client is\n        currently holding the lock.\n\n        ``blocking`` indicates whether calling ``acquire`` should block until\n        the lock has been acquired or to fail immediately, causing ``acquire``\n        to return False and the lock not being acquired. Defaults to True.\n        Note this value can be overridden by passing a ``blocking``\n        argument to ``acquire``.\n\n        ``blocking_timeout`` indicates the maximum amount of time in seconds to\n        spend trying to acquire the lock. A value of ``None`` indicates\n        continue trying forever. ``blocking_timeout`` can be specified as a\n        float or integer, both representing the number of seconds to wait.\n\n        ``thread_local`` indicates whether the lock token is placed in\n        thread-local storage. By default, the token is placed in thread local\n        storage so that a thread only sees its token, not a token set by\n        another thread. Consider the following timeline:\n\n            time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.\n                     thread-1 sets the token to \"abc\"\n            time: 1, thread-2 blocks trying to acquire `my-lock` using the\n                     Lock instance.\n            time: 5, thread-1 has not yet completed. redis expires the lock\n                     key.\n            time: 5, thread-2 acquired `my-lock` now that it's available.\n                     thread-2 sets the token to \"xyz\"\n            time: 6, thread-1 finishes its work and calls release(). if the\n                     token is *not* stored in thread local storage, then\n                     thread-1 would see the token value as \"xyz\" and would be\n                     able to successfully release the thread-2's lock.\n\n        In some use cases it's necessary to disable thread local storage. For\n        example, if you have code where one thread acquires a lock and passes\n        that lock instance to a worker thread to release later. If thread\n        local storage isn't disabled in this case, the worker thread won't see\n        the token set by the thread that acquired the lock. Our assumption\n        is that these cases aren't common and as such default to using\n        thread local storage.\n        \"\"\"\n        self.redis = redis\n        self.name = name\n        self.timeout = timeout\n        self.sleep = sleep\n        self.blocking = blocking\n        self.blocking_timeout = blocking_timeout\n        self.thread_local = bool(thread_local)\n        self.local = threading.local() if self.thread_local else SimpleNamespace()\n        self.local.token = None\n        self.register_scripts()\n\n    def register_scripts(self) -> None:\n        cls = self.__class__\n        client = self.redis\n        if cls.lua_release is None:\n            cls.lua_release = client.register_script(cls.LUA_RELEASE_SCRIPT)\n        if cls.lua_extend is None:\n            cls.lua_extend = client.register_script(cls.LUA_EXTEND_SCRIPT)\n        if cls.lua_reacquire is None:\n            cls.lua_reacquire = client.register_script(cls.LUA_REACQUIRE_SCRIPT)\n\n    def __enter__(self) -> \"Lock\":\n        if self.acquire():\n            return self\n        raise LockError(\"Unable to acquire lock within the time specified\")\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_value: Optional[BaseException],\n        traceback: Optional[TracebackType],\n    ) -> None:\n        self.release()\n\n    def acquire(\n        self,\n        *,\n        sleep: Optional[Number] = None,\n        blocking: Optional[bool] = None,\n        blocking_timeout: Optional[Number] = None,\n        token: Optional[str] = None,\n    ):\n        \"\"\"\n        Use Redis to hold a shared, distributed lock named ``name``.\n        Returns True once the lock is acquired.\n\n        If ``blocking`` is False, always return immediately. If the lock\n        was acquired, return True, otherwise return False.\n\n        ``blocking_timeout`` specifies the maximum number of seconds to\n        wait trying to acquire the lock.\n\n        ``token`` specifies the token value to be used. If provided, token\n        must be a bytes object or a string that can be encoded to a bytes\n        object with the default encoding. If a token isn't specified, a UUID\n        will be generated.\n        \"\"\"\n        if sleep is None:\n            sleep = self.sleep\n        if token is None:\n            token = uuid.uuid1().hex.encode()\n        else:\n            encoder = self.redis.get_encoder()\n            token = encoder.encode(token)\n        if blocking is None:\n            blocking = self.blocking\n        if blocking_timeout is None:\n            blocking_timeout = self.blocking_timeout\n        stop_trying_at = None\n        if blocking_timeout is not None:\n            stop_trying_at = mod_time.monotonic() + blocking_timeout\n        while True:\n            if self.do_acquire(token):\n                self.local.token = token\n                return True\n            if not blocking:\n                return False\n            next_try_at = mod_time.monotonic() + sleep\n            if stop_trying_at is not None and next_try_at > stop_trying_at:\n                return False\n            mod_time.sleep(sleep)\n\n    def do_acquire(self, token: str) -> bool:\n        if self.timeout:\n            # convert to milliseconds\n            timeout = int(self.timeout * 1000)\n        else:\n            timeout = None\n        if self.redis.set(self.name, token, nx=True, px=timeout):\n            return True\n        return False\n\n    def locked(self) -> bool:\n        \"\"\"\n        Returns True if this key is locked by any process, otherwise False.\n        \"\"\"\n        return self.redis.get(self.name) is not None\n\n    def owned(self) -> bool:\n        \"\"\"\n        Returns True if this key is locked by this lock, otherwise False.\n        \"\"\"\n        stored_token = self.redis.get(self.name)\n        # need to always compare bytes to bytes\n        # TODO: this can be simplified when the context manager is finished\n        if stored_token and not isinstance(stored_token, bytes):\n            encoder = self.redis.get_encoder()\n            stored_token = encoder.encode(stored_token)\n        return self.local.token is not None and stored_token == self.local.token\n\n    def release(self) -> None:\n        \"\"\"\n        Releases the already acquired lock\n        \"\"\"\n        expected_token = self.local.token\n        if expected_token is None:\n            raise LockError(\"Cannot release an unlocked lock\")\n        self.local.token = None\n        self.do_release(expected_token)\n\n    def do_release(self, expected_token: str) -> None:\n        if not bool(\n            self.lua_release(keys=[self.name], args=[expected_token], client=self.redis)\n        ):\n            raise LockNotOwnedError(\"Cannot release a lock\" \" that's no longer owned\")\n\n    def extend(self, additional_time: int, replace_ttl: bool = False) -> bool:\n        \"\"\"\n        Adds more time to an already acquired lock.\n\n        ``additional_time`` can be specified as an integer or a float, both\n        representing the number of seconds to add.\n\n        ``replace_ttl`` if False (the default), add `additional_time` to\n        the lock's existing ttl. If True, replace the lock's ttl with\n        `additional_time`.\n        \"\"\"\n        if self.local.token is None:\n            raise LockError(\"Cannot extend an unlocked lock\")\n        if self.timeout is None:\n            raise LockError(\"Cannot extend a lock with no timeout\")\n        return self.do_extend(additional_time, replace_ttl)\n\n    def do_extend(self, additional_time: int, replace_ttl: bool) -> bool:\n        additional_time = int(additional_time * 1000)\n        if not bool(\n            self.lua_extend(\n                keys=[self.name],\n                args=[self.local.token, additional_time, \"1\" if replace_ttl else \"0\"],\n                client=self.redis,\n            )\n        ):\n            raise LockNotOwnedError(\"Cannot extend a lock that's no longer owned\")\n        return True\n\n    def reacquire(self) -> bool:\n        \"\"\"\n        Resets a TTL of an already acquired lock back to a timeout value.\n        \"\"\"\n        if self.local.token is None:\n            raise LockError(\"Cannot reacquire an unlocked lock\")\n        if self.timeout is None:\n            raise LockError(\"Cannot reacquire a lock with no timeout\")\n        return self.do_reacquire()\n\n    def do_reacquire(self) -> bool:\n        timeout = int(self.timeout * 1000)\n        if not bool(\n            self.lua_reacquire(\n                keys=[self.name], args=[self.local.token, timeout], client=self.redis\n            )\n        ):\n            raise LockNotOwnedError(\"Cannot reacquire a lock that's no longer owned\")\n        return True\n", "path": "redis/lock.py"}], "after_files": [{"content": "import threading\nimport time as mod_time\nimport uuid\nfrom types import SimpleNamespace, TracebackType\nfrom typing import Optional, Type\n\nfrom redis.exceptions import LockError, LockNotOwnedError\nfrom redis.typing import Number\n\n\nclass Lock:\n    \"\"\"\n    A shared, distributed Lock. Using Redis for locking allows the Lock\n    to be shared across processes and/or machines.\n\n    It's left to the user to resolve deadlock issues and make sure\n    multiple clients play nicely together.\n    \"\"\"\n\n    lua_release = None\n    lua_extend = None\n    lua_reacquire = None\n\n    # KEYS[1] - lock name\n    # ARGV[1] - token\n    # return 1 if the lock was released, otherwise 0\n    LUA_RELEASE_SCRIPT = \"\"\"\n        local token = redis.call('get', KEYS[1])\n        if not token or token ~= ARGV[1] then\n            return 0\n        end\n        redis.call('del', KEYS[1])\n        return 1\n    \"\"\"\n\n    # KEYS[1] - lock name\n    # ARGV[1] - token\n    # ARGV[2] - additional milliseconds\n    # ARGV[3] - \"0\" if the additional time should be added to the lock's\n    #           existing ttl or \"1\" if the existing ttl should be replaced\n    # return 1 if the locks time was extended, otherwise 0\n    LUA_EXTEND_SCRIPT = \"\"\"\n        local token = redis.call('get', KEYS[1])\n        if not token or token ~= ARGV[1] then\n            return 0\n        end\n        local expiration = redis.call('pttl', KEYS[1])\n        if not expiration then\n            expiration = 0\n        end\n        if expiration < 0 then\n            return 0\n        end\n\n        local newttl = ARGV[2]\n        if ARGV[3] == \"0\" then\n            newttl = ARGV[2] + expiration\n        end\n        redis.call('pexpire', KEYS[1], newttl)\n        return 1\n    \"\"\"\n\n    # KEYS[1] - lock name\n    # ARGV[1] - token\n    # ARGV[2] - milliseconds\n    # return 1 if the locks time was reacquired, otherwise 0\n    LUA_REACQUIRE_SCRIPT = \"\"\"\n        local token = redis.call('get', KEYS[1])\n        if not token or token ~= ARGV[1] then\n            return 0\n        end\n        redis.call('pexpire', KEYS[1], ARGV[2])\n        return 1\n    \"\"\"\n\n    def __init__(\n        self,\n        redis,\n        name: str,\n        timeout: Optional[Number] = None,\n        sleep: Number = 0.1,\n        blocking: bool = True,\n        blocking_timeout: Optional[Number] = None,\n        thread_local: bool = True,\n    ):\n        \"\"\"\n        Create a new Lock instance named ``name`` using the Redis client\n        supplied by ``redis``.\n\n        ``timeout`` indicates a maximum life for the lock in seconds.\n        By default, it will remain locked until release() is called.\n        ``timeout`` can be specified as a float or integer, both representing\n        the number of seconds to wait.\n\n        ``sleep`` indicates the amount of time to sleep in seconds per loop\n        iteration when the lock is in blocking mode and another client is\n        currently holding the lock.\n\n        ``blocking`` indicates whether calling ``acquire`` should block until\n        the lock has been acquired or to fail immediately, causing ``acquire``\n        to return False and the lock not being acquired. Defaults to True.\n        Note this value can be overridden by passing a ``blocking``\n        argument to ``acquire``.\n\n        ``blocking_timeout`` indicates the maximum amount of time in seconds to\n        spend trying to acquire the lock. A value of ``None`` indicates\n        continue trying forever. ``blocking_timeout`` can be specified as a\n        float or integer, both representing the number of seconds to wait.\n\n        ``thread_local`` indicates whether the lock token is placed in\n        thread-local storage. By default, the token is placed in thread local\n        storage so that a thread only sees its token, not a token set by\n        another thread. Consider the following timeline:\n\n            time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.\n                     thread-1 sets the token to \"abc\"\n            time: 1, thread-2 blocks trying to acquire `my-lock` using the\n                     Lock instance.\n            time: 5, thread-1 has not yet completed. redis expires the lock\n                     key.\n            time: 5, thread-2 acquired `my-lock` now that it's available.\n                     thread-2 sets the token to \"xyz\"\n            time: 6, thread-1 finishes its work and calls release(). if the\n                     token is *not* stored in thread local storage, then\n                     thread-1 would see the token value as \"xyz\" and would be\n                     able to successfully release the thread-2's lock.\n\n        In some use cases it's necessary to disable thread local storage. For\n        example, if you have code where one thread acquires a lock and passes\n        that lock instance to a worker thread to release later. If thread\n        local storage isn't disabled in this case, the worker thread won't see\n        the token set by the thread that acquired the lock. Our assumption\n        is that these cases aren't common and as such default to using\n        thread local storage.\n        \"\"\"\n        self.redis = redis\n        self.name = name\n        self.timeout = timeout\n        self.sleep = sleep\n        self.blocking = blocking\n        self.blocking_timeout = blocking_timeout\n        self.thread_local = bool(thread_local)\n        self.local = threading.local() if self.thread_local else SimpleNamespace()\n        self.local.token = None\n        self.register_scripts()\n\n    def register_scripts(self) -> None:\n        cls = self.__class__\n        client = self.redis\n        if cls.lua_release is None:\n            cls.lua_release = client.register_script(cls.LUA_RELEASE_SCRIPT)\n        if cls.lua_extend is None:\n            cls.lua_extend = client.register_script(cls.LUA_EXTEND_SCRIPT)\n        if cls.lua_reacquire is None:\n            cls.lua_reacquire = client.register_script(cls.LUA_REACQUIRE_SCRIPT)\n\n    def __enter__(self) -> \"Lock\":\n        if self.acquire():\n            return self\n        raise LockError(\"Unable to acquire lock within the time specified\")\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_value: Optional[BaseException],\n        traceback: Optional[TracebackType],\n    ) -> None:\n        self.release()\n\n    def acquire(\n        self,\n        sleep: Optional[Number] = None,\n        blocking: Optional[bool] = None,\n        blocking_timeout: Optional[Number] = None,\n        token: Optional[str] = None,\n    ):\n        \"\"\"\n        Use Redis to hold a shared, distributed lock named ``name``.\n        Returns True once the lock is acquired.\n\n        If ``blocking`` is False, always return immediately. If the lock\n        was acquired, return True, otherwise return False.\n\n        ``blocking_timeout`` specifies the maximum number of seconds to\n        wait trying to acquire the lock.\n\n        ``token`` specifies the token value to be used. If provided, token\n        must be a bytes object or a string that can be encoded to a bytes\n        object with the default encoding. If a token isn't specified, a UUID\n        will be generated.\n        \"\"\"\n        if sleep is None:\n            sleep = self.sleep\n        if token is None:\n            token = uuid.uuid1().hex.encode()\n        else:\n            encoder = self.redis.get_encoder()\n            token = encoder.encode(token)\n        if blocking is None:\n            blocking = self.blocking\n        if blocking_timeout is None:\n            blocking_timeout = self.blocking_timeout\n        stop_trying_at = None\n        if blocking_timeout is not None:\n            stop_trying_at = mod_time.monotonic() + blocking_timeout\n        while True:\n            if self.do_acquire(token):\n                self.local.token = token\n                return True\n            if not blocking:\n                return False\n            next_try_at = mod_time.monotonic() + sleep\n            if stop_trying_at is not None and next_try_at > stop_trying_at:\n                return False\n            mod_time.sleep(sleep)\n\n    def do_acquire(self, token: str) -> bool:\n        if self.timeout:\n            # convert to milliseconds\n            timeout = int(self.timeout * 1000)\n        else:\n            timeout = None\n        if self.redis.set(self.name, token, nx=True, px=timeout):\n            return True\n        return False\n\n    def locked(self) -> bool:\n        \"\"\"\n        Returns True if this key is locked by any process, otherwise False.\n        \"\"\"\n        return self.redis.get(self.name) is not None\n\n    def owned(self) -> bool:\n        \"\"\"\n        Returns True if this key is locked by this lock, otherwise False.\n        \"\"\"\n        stored_token = self.redis.get(self.name)\n        # need to always compare bytes to bytes\n        # TODO: this can be simplified when the context manager is finished\n        if stored_token and not isinstance(stored_token, bytes):\n            encoder = self.redis.get_encoder()\n            stored_token = encoder.encode(stored_token)\n        return self.local.token is not None and stored_token == self.local.token\n\n    def release(self) -> None:\n        \"\"\"\n        Releases the already acquired lock\n        \"\"\"\n        expected_token = self.local.token\n        if expected_token is None:\n            raise LockError(\"Cannot release an unlocked lock\")\n        self.local.token = None\n        self.do_release(expected_token)\n\n    def do_release(self, expected_token: str) -> None:\n        if not bool(\n            self.lua_release(keys=[self.name], args=[expected_token], client=self.redis)\n        ):\n            raise LockNotOwnedError(\"Cannot release a lock\" \" that's no longer owned\")\n\n    def extend(self, additional_time: int, replace_ttl: bool = False) -> bool:\n        \"\"\"\n        Adds more time to an already acquired lock.\n\n        ``additional_time`` can be specified as an integer or a float, both\n        representing the number of seconds to add.\n\n        ``replace_ttl`` if False (the default), add `additional_time` to\n        the lock's existing ttl. If True, replace the lock's ttl with\n        `additional_time`.\n        \"\"\"\n        if self.local.token is None:\n            raise LockError(\"Cannot extend an unlocked lock\")\n        if self.timeout is None:\n            raise LockError(\"Cannot extend a lock with no timeout\")\n        return self.do_extend(additional_time, replace_ttl)\n\n    def do_extend(self, additional_time: int, replace_ttl: bool) -> bool:\n        additional_time = int(additional_time * 1000)\n        if not bool(\n            self.lua_extend(\n                keys=[self.name],\n                args=[self.local.token, additional_time, \"1\" if replace_ttl else \"0\"],\n                client=self.redis,\n            )\n        ):\n            raise LockNotOwnedError(\"Cannot extend a lock that's no longer owned\")\n        return True\n\n    def reacquire(self) -> bool:\n        \"\"\"\n        Resets a TTL of an already acquired lock back to a timeout value.\n        \"\"\"\n        if self.local.token is None:\n            raise LockError(\"Cannot reacquire an unlocked lock\")\n        if self.timeout is None:\n            raise LockError(\"Cannot reacquire a lock with no timeout\")\n        return self.do_reacquire()\n\n    def do_reacquire(self) -> bool:\n        timeout = int(self.timeout * 1000)\n        if not bool(\n            self.lua_reacquire(\n                keys=[self.name], args=[self.local.token, timeout], client=self.redis\n            )\n        ):\n            raise LockNotOwnedError(\"Cannot reacquire a lock that's no longer owned\")\n        return True\n", "path": "redis/lock.py"}]}