zstdlib 0.10.8__tar.gz → 0.10.10__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {zstdlib-0.10.8 → zstdlib-0.10.10}/PKG-INFO +1 -1
- {zstdlib-0.10.8 → zstdlib-0.10.10}/pyproject.toml +2 -1
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_exc_capture.py +6 -0
- zstdlib-0.10.10/tests/test_ip_lock.py +350 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_keyed_instance.py +9 -7
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_singleton.py +1 -1
- zstdlib-0.10.10/tests/test_util.py +32 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/__init__.py +13 -3
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/enum.py +1 -7
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/exc_capture.py +19 -1
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/io.py +1 -1
- zstdlib-0.10.10/zstdlib/ip_lock.py +287 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/keyed_instance.py +28 -23
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/not_set.py +1 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/singleton.py +9 -16
- zstdlib-0.10.10/zstdlib/util.py +8 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib.egg-info/PKG-INFO +1 -1
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib.egg-info/SOURCES.txt +4 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/LICENSE +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/README.md +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/setup.cfg +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/__init__.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/log/__init__.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/log/base.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/log/test_cute.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/log/test_trace.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_ansi.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_enum.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_frozen.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_hybridmethod.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_io.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_lazy.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_not_set.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/tests/test_prompt.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/ansi.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/frozen.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/hybridmethod.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/lazy.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/log/__init__.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/log/cute.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/log/trace.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/macos.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/prompt.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/py.typed +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib/signal_cm.py +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib.egg-info/dependency_links.txt +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib.egg-info/requires.txt +0 -0
- {zstdlib-0.10.8 → zstdlib-0.10.10}/zstdlib.egg-info/top_level.txt +0 -0
|
@@ -47,6 +47,12 @@ class TestLazy(unittest.TestCase):
|
|
|
47
47
|
with non.capture(RuntimeError):
|
|
48
48
|
raise RuntimeError()
|
|
49
49
|
self.assertEqual(len(non.errors), 1)
|
|
50
|
+
# run_fn
|
|
51
|
+
ke = ExcCapture(KeyError)
|
|
52
|
+
self.assertEqual(ke.run_fn({0: 5}.__getitem__, 0), 5)
|
|
53
|
+
self.assertEqual(len(ke.errors), 0)
|
|
54
|
+
self.assertIs(ke.run_fn({}.__getitem__, 0), ke.NoResult)
|
|
55
|
+
self.assertEqual(len(ke.errors), 1)
|
|
50
56
|
|
|
51
57
|
def test_delay(self) -> None:
|
|
52
58
|
# No raise
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
|
|
2
|
+
from tempfile import TemporaryDirectory, NamedTemporaryFile as NTF
|
|
3
|
+
from collections.abc import Callable, Iterator
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
import multiprocessing as mp
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
import unittest
|
|
9
|
+
import time
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
from zstdlib import (
|
|
13
|
+
GlobalIPLock as GIPL,
|
|
14
|
+
AbstractIPLock,
|
|
15
|
+
IPLock,
|
|
16
|
+
RIPLock,
|
|
17
|
+
LockHung,
|
|
18
|
+
LockPathInUse,
|
|
19
|
+
NotAcquired,
|
|
20
|
+
normpath,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
DELAY = 0.25 # Lower is faster but less accurate
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@contextmanager
|
|
27
|
+
def mk_gipl() -> Iterator[GIPL]:
|
|
28
|
+
with NTF(delete_on_close=False) as f:
|
|
29
|
+
f.close()
|
|
30
|
+
yield GIPL.new(Path(f.name))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@contextmanager
|
|
34
|
+
def mk_lock[T: (IPLock, RIPLock)](lock_t: type[T]) -> Iterator[T]:
|
|
35
|
+
assert lock_t in (IPLock, RIPLock)
|
|
36
|
+
with NTF(delete_on_close=False) as f:
|
|
37
|
+
f.close()
|
|
38
|
+
yield lock_t(Path(f.name))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@contextmanager
|
|
42
|
+
def enter(lock: AbstractIPLock, timeout: int | float = 10) -> Iterator[None]:
|
|
43
|
+
assert 0 <= timeout <= 10
|
|
44
|
+
old = lock.acquired
|
|
45
|
+
if not lock.acquire(timeout_per=timeout):
|
|
46
|
+
raise RuntimeError("Failed to acquire")
|
|
47
|
+
try:
|
|
48
|
+
yield
|
|
49
|
+
finally:
|
|
50
|
+
lock.release()
|
|
51
|
+
if old != lock.acquired:
|
|
52
|
+
raise RuntimeError("Different state")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class IPLog: # Not thread-safe
|
|
56
|
+
|
|
57
|
+
def __init__(self) -> None:
|
|
58
|
+
self._q: mp.Queue[tuple[float, int, str]] = mp.Queue()
|
|
59
|
+
self._q.put((0, 0, ""))
|
|
60
|
+
self._main: int = os.getpid()
|
|
61
|
+
self._done: bool = False
|
|
62
|
+
|
|
63
|
+
def __call__(self, s: str, pid: int | None = None) -> None:
|
|
64
|
+
main = os.getpid() == self._main
|
|
65
|
+
assert main == (pid is None)
|
|
66
|
+
if main:
|
|
67
|
+
pid = 1
|
|
68
|
+
assert not self._done and isinstance(pid, int) and (main or pid > 1)
|
|
69
|
+
self._q.put((time.monotonic(), pid, s))
|
|
70
|
+
|
|
71
|
+
def read(self) -> list[str]:
|
|
72
|
+
assert not self._done
|
|
73
|
+
self._done = True
|
|
74
|
+
self._q.put((-1, 0, ""))
|
|
75
|
+
contents: list[tuple[float, int, str]] = []
|
|
76
|
+
while not contents or contents[-1][0] != -1:
|
|
77
|
+
contents.append(self._q.get())
|
|
78
|
+
contents = contents[1:-1]
|
|
79
|
+
if not contents:
|
|
80
|
+
return []
|
|
81
|
+
pids = list({i[1] for i in contents})
|
|
82
|
+
rv = sorted(f"{i}|PID-{pids.index(j)+1}: {k}" for i, j, k in contents)
|
|
83
|
+
return [i.split("|", 1)[1] for i in rv]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# For remote testing
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class RemoteProc:
|
|
90
|
+
|
|
91
|
+
type Logger = Callable[[str], None]
|
|
92
|
+
|
|
93
|
+
def __init__(self, fn: Callable[[Logger, Path], None], log: IPLog, path: Path, *, pid: int) -> None:
|
|
94
|
+
if pid < 2:
|
|
95
|
+
raise ValueError("Bad pid")
|
|
96
|
+
self._p = mp.get_context("spawn").Process(target=self._wrapper)
|
|
97
|
+
self._func = fn
|
|
98
|
+
self._pid = pid
|
|
99
|
+
self._done = False
|
|
100
|
+
self._path = path
|
|
101
|
+
self._log = log
|
|
102
|
+
|
|
103
|
+
def start(self) -> None:
|
|
104
|
+
self._p.start()
|
|
105
|
+
|
|
106
|
+
def die(self, timeout: int) -> None:
|
|
107
|
+
assert isinstance(timeout, int) and 0 <= timeout <= 10
|
|
108
|
+
self._p.join(timeout)
|
|
109
|
+
if self._p.is_alive():
|
|
110
|
+
self._log("Alive")
|
|
111
|
+
self._p.kill()
|
|
112
|
+
|
|
113
|
+
def _wrapper(self) -> None:
|
|
114
|
+
|
|
115
|
+
def log(s: str) -> None:
|
|
116
|
+
self._log(s, pid=self._pid)
|
|
117
|
+
|
|
118
|
+
log("START")
|
|
119
|
+
try:
|
|
120
|
+
self._func(log, self._path)
|
|
121
|
+
log("FIN")
|
|
122
|
+
except Exception as e: # noqa: BLE001
|
|
123
|
+
log(f"{e.__class__.__name__}: {e.args}")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def gipl_p1(log: RemoteProc.Logger, path: Path) -> None:
|
|
127
|
+
with GIPL.new(path) as lock:
|
|
128
|
+
log("Locked")
|
|
129
|
+
time.sleep(DELAY)
|
|
130
|
+
with lock:
|
|
131
|
+
log("Double locked; sleeping")
|
|
132
|
+
time.sleep(DELAY)
|
|
133
|
+
log("Awake")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# Unit tests
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class TestGlobalProcessLock(unittest.TestCase):
|
|
140
|
+
|
|
141
|
+
def test_bad_usage(self) -> None:
|
|
142
|
+
# Path
|
|
143
|
+
bad = Path("a/b/../c")
|
|
144
|
+
norm = normpath(bad)
|
|
145
|
+
fixed = norm.absolute()
|
|
146
|
+
assert bad != norm != fixed and fixed == Path.cwd() / norm
|
|
147
|
+
with self.assertRaises(ValueError):
|
|
148
|
+
GIPL(bad)
|
|
149
|
+
self.assertEqual(GIPL.new(bad).path, fixed)
|
|
150
|
+
self.assertEqual(GIPL.new(str(bad)).path, fixed)
|
|
151
|
+
with self.assertRaises(TypeError):
|
|
152
|
+
GIPL(str(fixed)) # type: ignore[arg-type]
|
|
153
|
+
# File
|
|
154
|
+
with TemporaryDirectory() as _td:
|
|
155
|
+
td = GIPL.normalize(_td, check=False)
|
|
156
|
+
with self.assertRaises(FileExistsError):
|
|
157
|
+
_ = GIPL(td)
|
|
158
|
+
no_exist = td / "no_exist"
|
|
159
|
+
self.assertIs(GIPL(no_exist), GIPL.new(no_exist))
|
|
160
|
+
norm = td / "normal"
|
|
161
|
+
norm.touch()
|
|
162
|
+
self.assertIs(GIPL(norm), GIPL.new(norm))
|
|
163
|
+
symlink = td / "symlink"
|
|
164
|
+
symlink.symlink_to(norm)
|
|
165
|
+
assert symlink.resolve() == norm
|
|
166
|
+
with self.assertRaises(FileExistsError): # test for Path, easier here b/c temp dir
|
|
167
|
+
_ = GIPL(symlink)
|
|
168
|
+
with self.assertRaises(FileExistsError):
|
|
169
|
+
GIPL.new(symlink)
|
|
170
|
+
hardlink = td / "hardlink"
|
|
171
|
+
hardlink.hardlink_to(norm)
|
|
172
|
+
with self.assertRaises(FileExistsError):
|
|
173
|
+
GIPL(hardlink)
|
|
174
|
+
with self.assertRaises(FileExistsError):
|
|
175
|
+
GIPL(hardlink)
|
|
176
|
+
# Timeout
|
|
177
|
+
with mk_gipl() as lock:
|
|
178
|
+
self.assertFalse(lock.acquired)
|
|
179
|
+
with self.assertRaises(TypeError):
|
|
180
|
+
lock.acquire(timeout_per="q") # type: ignore[arg-type]
|
|
181
|
+
with self.assertRaises(ValueError):
|
|
182
|
+
lock.acquire(timeout_per=-1)
|
|
183
|
+
with self.assertRaises(ValueError):
|
|
184
|
+
lock.acquire(blocking=False, timeout_per=1)
|
|
185
|
+
self.assertFalse(lock.acquired)
|
|
186
|
+
self.assertTrue(lock.acquire(timeout_per=1))
|
|
187
|
+
lock.release()
|
|
188
|
+
self.assertFalse(lock.acquired)
|
|
189
|
+
self.assertTrue(lock.acquire(timeout_per=1.0))
|
|
190
|
+
lock.release()
|
|
191
|
+
self.assertFalse(lock.acquired)
|
|
192
|
+
|
|
193
|
+
def test_sole_owner(self) -> None:
|
|
194
|
+
with mk_gipl() as lock:
|
|
195
|
+
self.assertFalse(lock.acquired)
|
|
196
|
+
# Can acquire existing file
|
|
197
|
+
self.assertTrue(lock.acquire(timeout_per=0))
|
|
198
|
+
self.assertTrue(lock.acquired)
|
|
199
|
+
# Re-acquisition, count == 2
|
|
200
|
+
self.assertTrue(lock.acquire(timeout_per=0))
|
|
201
|
+
self.assertTrue(lock.acquired)
|
|
202
|
+
# Release 1/2
|
|
203
|
+
lock.release()
|
|
204
|
+
self.assertTrue(lock.acquired)
|
|
205
|
+
# Release 2/2
|
|
206
|
+
lock.release()
|
|
207
|
+
self.assertFalse(lock.acquired)
|
|
208
|
+
# Release 3/2
|
|
209
|
+
with self.assertRaises(NotAcquired):
|
|
210
|
+
lock.release()
|
|
211
|
+
self.assertFalse(lock.acquired)
|
|
212
|
+
# CM exit, lock file removed by NTF
|
|
213
|
+
# Fresh acquire on non-existing file
|
|
214
|
+
lock.acquire(timeout_per=0)
|
|
215
|
+
lock.release()
|
|
216
|
+
|
|
217
|
+
def test_global(self) -> None:
|
|
218
|
+
with mk_gipl() as lock:
|
|
219
|
+
other = GIPL(lock.path)
|
|
220
|
+
self.assertFalse(lock.acquired or other.acquired)
|
|
221
|
+
self.assertTrue(lock.acquire(timeout_per=1))
|
|
222
|
+
self.assertTrue(lock.acquired and other.acquired)
|
|
223
|
+
self.assertTrue(lock.acquire(timeout_per=1))
|
|
224
|
+
other.release()
|
|
225
|
+
self.assertTrue(lock.acquired and other.acquired)
|
|
226
|
+
other.release()
|
|
227
|
+
self.assertFalse(lock.acquired or other.acquired)
|
|
228
|
+
|
|
229
|
+
def test_ipc(self) -> None:
|
|
230
|
+
log = IPLog()
|
|
231
|
+
with mk_gipl() as lock:
|
|
232
|
+
p = RemoteProc(gipl_p1, log, lock.path, pid=2)
|
|
233
|
+
with enter(lock):
|
|
234
|
+
log("Starting child")
|
|
235
|
+
p.start()
|
|
236
|
+
time.sleep(DELAY)
|
|
237
|
+
log("Releasing")
|
|
238
|
+
lock.release()
|
|
239
|
+
time.sleep(DELAY)
|
|
240
|
+
log("Reclaiming")
|
|
241
|
+
lock.acquire(timeout_per=1)
|
|
242
|
+
log("Got")
|
|
243
|
+
expected: list[str] = [
|
|
244
|
+
"PID-1: Starting child",
|
|
245
|
+
"PID-2: START",
|
|
246
|
+
"PID-1: Releasing",
|
|
247
|
+
"PID-2: Locked",
|
|
248
|
+
"PID-1: Reclaiming",
|
|
249
|
+
"PID-2: Double locked; sleeping",
|
|
250
|
+
"PID-2: Awake",
|
|
251
|
+
"PID-2: FIN",
|
|
252
|
+
"PID-1: Got",
|
|
253
|
+
]
|
|
254
|
+
self.assertEqual(log.read(), expected)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class TestIPLocks(unittest.TestCase):
|
|
258
|
+
|
|
259
|
+
def test_locks(self) -> None:
|
|
260
|
+
# Test using a basic IPLock b/c more likely to err if we do something dumb
|
|
261
|
+
# We already trust GlobalProcessLock, threading.Lock, and threading.RLock
|
|
262
|
+
# so instead of spinning up threads and processes, just verify their states
|
|
263
|
+
with mk_lock(IPLock) as lock:
|
|
264
|
+
lock2 = IPLock(lock.path)
|
|
265
|
+
self.assertIsNot(lock, lock2)
|
|
266
|
+
self.assertEqual(lock.path, lock2.path)
|
|
267
|
+
# pylint: disable=protected-access
|
|
268
|
+
self.assertIs(lock._gipl, lock2._gipl)
|
|
269
|
+
self.assertFalse(lock._gipl.acquired)
|
|
270
|
+
with enter(lock):
|
|
271
|
+
|
|
272
|
+
def chk() -> None:
|
|
273
|
+
self.assertTrue(lock._gipl.acquired)
|
|
274
|
+
self.assertTrue(lock.acquired)
|
|
275
|
+
self.assertTrue(lock._sync_lock.locked())
|
|
276
|
+
self.assertFalse(lock2.acquired)
|
|
277
|
+
self.assertTrue(lock2._sync_lock.locked())
|
|
278
|
+
|
|
279
|
+
chk()
|
|
280
|
+
self.assertFalse(lock2.acquire(timeout_per=2))
|
|
281
|
+
chk()
|
|
282
|
+
self.assertFalse(lock._gipl.acquired or lock2._gipl.acquired)
|
|
283
|
+
self.assertFalse(lock._sync_lock.locked())
|
|
284
|
+
self.assertFalse(lock2._sync_lock.locked())
|
|
285
|
+
# pylint: enable=protected-access
|
|
286
|
+
# Test releasing when we don't have
|
|
287
|
+
self.assertFalse(lock.acquired)
|
|
288
|
+
with self.assertRaises(NotAcquired):
|
|
289
|
+
lock.release()
|
|
290
|
+
# pylint: disable=protected-access
|
|
291
|
+
lock._rc += 1
|
|
292
|
+
with self.assertRaises(RuntimeError):
|
|
293
|
+
lock.release()
|
|
294
|
+
lock._rc += 1
|
|
295
|
+
lock._sync_lock.acquire()
|
|
296
|
+
self.assertFalse(lock._gipl.acquired)
|
|
297
|
+
# pylint: enable=protected-access
|
|
298
|
+
with self.assertRaises(OSError):
|
|
299
|
+
lock.release()
|
|
300
|
+
|
|
301
|
+
# Fake GIPL cannot acquire test
|
|
302
|
+
class FakeGIPL:
|
|
303
|
+
def acquire(self, *_: Any, **__: Any) -> bool:
|
|
304
|
+
return False
|
|
305
|
+
|
|
306
|
+
with mk_lock(IPLock) as lock:
|
|
307
|
+
# pylint: disable=protected-access
|
|
308
|
+
old = lock._gipl
|
|
309
|
+
lock._gipl = FakeGIPL() # type: ignore[assignment ,misc]
|
|
310
|
+
self.assertFalse(lock.acquire(timeout_per=3))
|
|
311
|
+
lock._gipl = old # type: ignore[misc]
|
|
312
|
+
# pylint: enable=protected-access
|
|
313
|
+
|
|
314
|
+
def test_lock_types(self) -> None:
|
|
315
|
+
# pylint: disable=protected-access
|
|
316
|
+
self.assertFalse(IPLock._cls_reentrant)
|
|
317
|
+
self.assertTrue(RIPLock._cls_reentrant)
|
|
318
|
+
with mk_lock(IPLock) as lock:
|
|
319
|
+
self.assertFalse(lock._instance_reentrant)
|
|
320
|
+
del lock
|
|
321
|
+
with mk_lock(RIPLock) as rlock:
|
|
322
|
+
self.assertTrue(rlock._instance_reentrant)
|
|
323
|
+
del rlock
|
|
324
|
+
|
|
325
|
+
# pylint: enable=protected-access
|
|
326
|
+
with mk_lock(IPLock) as lock, enter(lock):
|
|
327
|
+
self.assertTrue(lock.acquired)
|
|
328
|
+
self.assertFalse(lock.acquire(timeout_per=2))
|
|
329
|
+
self.assertTrue(lock.acquired)
|
|
330
|
+
self.assertFalse(lock.acquired)
|
|
331
|
+
del lock
|
|
332
|
+
with mk_lock(RIPLock) as rlock, enter(rlock), enter(rlock):
|
|
333
|
+
self.assertTrue(rlock.acquired)
|
|
334
|
+
self.assertFalse(rlock.acquired)
|
|
335
|
+
del rlock
|
|
336
|
+
|
|
337
|
+
with mk_lock(IPLock) as lock, self.assertRaises(LockPathInUse):
|
|
338
|
+
_ = RIPLock(lock.path)
|
|
339
|
+
del lock
|
|
340
|
+
with mk_lock(RIPLock) as rlock, self.assertRaises(LockPathInUse):
|
|
341
|
+
_ = IPLock(rlock.path)
|
|
342
|
+
del rlock
|
|
343
|
+
|
|
344
|
+
def test_lock_hung(self) -> None:
|
|
345
|
+
with mk_lock(IPLock) as lock, enter(lock), self.assertRaises(LockHung):
|
|
346
|
+
_ = lock.acquire()
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
if __name__ == "__main__":
|
|
350
|
+
unittest.main()
|
|
@@ -13,7 +13,7 @@ import sys
|
|
|
13
13
|
import os
|
|
14
14
|
|
|
15
15
|
from zstdlib.keyed_instance import KeyedInstanceProcessError
|
|
16
|
-
from zstdlib import
|
|
16
|
+
from zstdlib import CircularConstruction, KeyedInstance
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
class Nop:
|
|
@@ -53,6 +53,7 @@ def subprocess_fn(q: mp.Queue[str]) -> None:
|
|
|
53
53
|
p.join(1)
|
|
54
54
|
if p.is_alive():
|
|
55
55
|
p.kill()
|
|
56
|
+
q.put("Process had to be killed")
|
|
56
57
|
raise RuntimeError("Process had to be killed")
|
|
57
58
|
|
|
58
59
|
# Multiprocessing is allowed right now, these should work
|
|
@@ -128,14 +129,14 @@ class TestKeyedInstance(unittest.TestCase):
|
|
|
128
129
|
def __init__(self, b: bool) -> None:
|
|
129
130
|
self.same = type(self)(b) # Father is self, circle
|
|
130
131
|
|
|
131
|
-
with self.assertRaises(
|
|
132
|
+
with self.assertRaises(CircularConstruction):
|
|
132
133
|
_ = Crazy(True)
|
|
133
134
|
|
|
134
135
|
class Crazy2(KeyedInstance):
|
|
135
136
|
def __init__(self, b: bool) -> None:
|
|
136
137
|
self.inverse = type(self)(not b) # Grandfather is self
|
|
137
138
|
|
|
138
|
-
with self.assertRaises(
|
|
139
|
+
with self.assertRaises(CircularConstruction):
|
|
139
140
|
_ = Crazy2(True)
|
|
140
141
|
|
|
141
142
|
def test_multiproc(self) -> None:
|
|
@@ -149,6 +150,7 @@ class TestKeyedInstance(unittest.TestCase):
|
|
|
149
150
|
|
|
150
151
|
# Run tests
|
|
151
152
|
q: mp.Queue[str] = mp.Queue()
|
|
153
|
+
q.put("Start")
|
|
152
154
|
p = mp.get_context("spawn").Process(target=subprocess_fn, args=(q,))
|
|
153
155
|
p.start()
|
|
154
156
|
p.join(10) # This should be rather instant, this is generous
|
|
@@ -166,13 +168,13 @@ class TestKeyedInstance(unittest.TestCase):
|
|
|
166
168
|
results: list[str] = []
|
|
167
169
|
while not results or results[-1] != fin:
|
|
168
170
|
results.append(q.get(timeout=3)) # Should be done nearly instantly
|
|
169
|
-
expected: list[str] = ["os.fork", "mp.fork", "mp.spawn"] * 2
|
|
171
|
+
expected: list[str] = ["Start"] + ["os.fork", "mp.fork", "mp.spawn"] * 2
|
|
170
172
|
expected += ["KIPE", "KIPE", "mp.spawn", "Dead", "0", fin]
|
|
171
173
|
self.assertEqual(results, expected)
|
|
172
174
|
|
|
173
175
|
def test_interthread(self) -> None:
|
|
174
176
|
|
|
175
|
-
scale: int =
|
|
177
|
+
scale: int = 8 # Higher runs faster, lower is more accurate
|
|
176
178
|
actions: list[Action] = []
|
|
177
179
|
type RV_T = C1 | C2 | Exception
|
|
178
180
|
|
|
@@ -247,8 +249,8 @@ class TestKeyedInstance(unittest.TestCase):
|
|
|
247
249
|
"5 | Thread-1 | C1(0), next=[0, 0] - err: C2(0)", # release C2(0)
|
|
248
250
|
]
|
|
249
251
|
self.assertEqual(Action.strs(actions), expected)
|
|
250
|
-
self.assertIsInstance(fail1,
|
|
251
|
-
self.assertIsInstance(fail2,
|
|
252
|
+
self.assertIsInstance(fail1, CircularConstruction)
|
|
253
|
+
self.assertIsInstance(fail2, CircularConstruction)
|
|
252
254
|
self.assertIsNot(fail1, fail2)
|
|
253
255
|
|
|
254
256
|
# Test simultaneous construction
|
|
@@ -48,7 +48,7 @@ class TestSingleton(unittest.TestCase):
|
|
|
48
48
|
self.assertIs(ST.instance(), obj)
|
|
49
49
|
|
|
50
50
|
with self.assertRaises(TypeError):
|
|
51
|
-
ST.instance(4)
|
|
51
|
+
ST.instance(4)
|
|
52
52
|
|
|
53
53
|
def test_multi_thread(self) -> None:
|
|
54
54
|
"""Ensure that Singleton is thread safe and that constructing an object doesn't delay other threads
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import unittest
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
from zstdlib import normpath
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestUtil(unittest.TestCase):
|
|
10
|
+
|
|
11
|
+
def test_normpath(self) -> None:
|
|
12
|
+
tests_raw = {
|
|
13
|
+
"": ".",
|
|
14
|
+
"/": "/",
|
|
15
|
+
"/a/": "/a",
|
|
16
|
+
"/a/..": "/",
|
|
17
|
+
"/a/../": "/",
|
|
18
|
+
"/a/b/..": "/a",
|
|
19
|
+
"/a/b/../": "/a",
|
|
20
|
+
"/a//b": "/a/b",
|
|
21
|
+
"/a//b/": "/a/b",
|
|
22
|
+
"c": "c",
|
|
23
|
+
"c//d///": "c/d",
|
|
24
|
+
}
|
|
25
|
+
res = [(k, os.path.normpath(i), normpath(Path(i))) for i, k in tests_raw.items()]
|
|
26
|
+
for want, os_np, np in res:
|
|
27
|
+
self.assertEqual(want, os_np)
|
|
28
|
+
self.assertEqual(Path(want), np)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
unittest.main()
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
__version__ = "0.10.
|
|
1
|
+
__version__ = "0.10.10"
|
|
2
2
|
|
|
3
|
-
from .
|
|
3
|
+
from .ip_lock import AbstractIPLock, GlobalIPLock, IPLock, LockHung, LockPathInUse, NotAcquired, RIPLock
|
|
4
|
+
from .keyed_instance import CircularConstruction, KeyedInstance
|
|
4
5
|
from .prompt import prompt_until, prompt_for, yn_prompt
|
|
5
6
|
from .exc_capture import ExcCapture, ExcDelay
|
|
6
7
|
from .hybridmethod import hybridmethod
|
|
@@ -9,17 +10,25 @@ from .frozen import Freezable, frozen
|
|
|
9
10
|
from .singleton import Singleton
|
|
10
11
|
from .signal_cm import signal_cm
|
|
11
12
|
from .enum import Enum, auto
|
|
13
|
+
from .util import normpath
|
|
12
14
|
from . import macos, lazy, log, io
|
|
13
15
|
|
|
14
16
|
__all__ = (
|
|
15
|
-
"
|
|
17
|
+
"AbstractIPLock",
|
|
18
|
+
"CircularConstruction",
|
|
16
19
|
"Enum",
|
|
17
20
|
"ExcCapture",
|
|
18
21
|
"ExcDelay",
|
|
19
22
|
"Freezable",
|
|
23
|
+
"GlobalIPLock",
|
|
24
|
+
"IPLock",
|
|
20
25
|
"KeyedInstance",
|
|
26
|
+
"LockHung",
|
|
27
|
+
"LockPathInUse",
|
|
28
|
+
"NotAcquired",
|
|
21
29
|
"NotSet",
|
|
22
30
|
"NotSetType",
|
|
31
|
+
"RIPLock",
|
|
23
32
|
"Singleton",
|
|
24
33
|
"auto",
|
|
25
34
|
"frozen",
|
|
@@ -28,6 +37,7 @@ __all__ = (
|
|
|
28
37
|
"lazy",
|
|
29
38
|
"log",
|
|
30
39
|
"macos",
|
|
40
|
+
"normpath",
|
|
31
41
|
"prompt_for",
|
|
32
42
|
"prompt_until",
|
|
33
43
|
"signal_cm",
|
|
@@ -2,13 +2,7 @@ from collections.abc import Iterator, Set
|
|
|
2
2
|
from typing import ClassVar, Never, Any
|
|
3
3
|
import annotationlib
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
class _Auto:
|
|
7
|
-
"""A sentinel value for automatic enum values"""
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
# Pass this as a value to have it automatically assigned
|
|
11
|
-
auto = _Auto()
|
|
5
|
+
auto = object() # Use sentinel in python3.15
|
|
12
6
|
|
|
13
7
|
|
|
14
8
|
class EnumType(type):
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
from contextlib import AbstractContextManager, contextmanager
|
|
2
|
-
from collections.abc import Iterator
|
|
2
|
+
from collections.abc import Callable, Iterator
|
|
3
3
|
from typing import Self
|
|
4
4
|
|
|
5
5
|
__all__ = ("ExcCapture", "ExcDelay")
|
|
@@ -11,6 +11,13 @@ type EXC_T = type[BaseException] | tuple[type[BaseException]]
|
|
|
11
11
|
class ExcCapture:
|
|
12
12
|
"""A class that exposes a context manager which captures and suppresses any raised exception of a given type / tuple of types"""
|
|
13
13
|
|
|
14
|
+
# In python3.15 use sentinel
|
|
15
|
+
class _NoResult:
|
|
16
|
+
"""A sentinel for no result"""
|
|
17
|
+
|
|
18
|
+
type NoResultType = _NoResult
|
|
19
|
+
NoResult = _NoResult()
|
|
20
|
+
|
|
14
21
|
__slots__ = ("errors", "exc_t", "previous")
|
|
15
22
|
|
|
16
23
|
def __init__(self, exc_t: EXC_T | None = None) -> None:
|
|
@@ -43,6 +50,17 @@ class ExcCapture:
|
|
|
43
50
|
"""An alias for .capture"""
|
|
44
51
|
return self.capture(exc_t)
|
|
45
52
|
|
|
53
|
+
def run_fn[T, R](self, fn: Callable[[T], R], obj: T, *, exc_t: EXC_T | None = None) -> R | NoResultType:
|
|
54
|
+
"""
|
|
55
|
+
Run with self.capture(exc_t): fn(obj), return the result if found else self.NoResult
|
|
56
|
+
This can be a useful for brevity, like: map(partial(x.run_fn, fn), iterable)
|
|
57
|
+
"""
|
|
58
|
+
if not callable(fn):
|
|
59
|
+
raise TypeError("fn must be callable")
|
|
60
|
+
with self.capture(exc_t):
|
|
61
|
+
return fn(obj)
|
|
62
|
+
return self.NoResult
|
|
63
|
+
|
|
46
64
|
|
|
47
65
|
class ExcDelay(ExcCapture):
|
|
48
66
|
"""A context manager subclass of ExcCapture that raises on exit if errors are captured"""
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
from typing import ClassVar, Final, Self, Any, override, final
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
from threading import RLock, Lock
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from stat import S_ISREG
|
|
7
|
+
|
|
8
|
+
from fasteners import InterProcessLock
|
|
9
|
+
|
|
10
|
+
from .keyed_instance import KeyedInstance
|
|
11
|
+
from .util import normpath
|
|
12
|
+
|
|
13
|
+
__all__ = ("AbstractIPLock", "GlobalIPLock", "IPLock", "LockHung", "LockPathInUse", "NotAcquired", "RIPLock")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NotAcquired(RuntimeError):
|
|
17
|
+
"""Raised by AbstractIPLock.release if a lock is not acquired"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class LockHung(RuntimeError):
|
|
21
|
+
"""Raised when a non-reentrant lock attempts to reenter with blocking=True and no timeout"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AbstractIPLock(ABC):
|
|
25
|
+
"""An abstract interprocess lock that uses a Path for IPC synchronization"""
|
|
26
|
+
|
|
27
|
+
# Abstract Methods
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def path(self) -> Path:
|
|
32
|
+
"""The path this lock is synchronized across processes with"""
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def acquired(self) -> bool:
|
|
37
|
+
"""Whether the lock has been acquired or not"""
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def _acquire(self, blocking: bool, timeout_per: float | None) -> bool:
|
|
41
|
+
"""Acquire the lock, assumes blocking if timeout_per and args are valid"""
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def release(self) -> None:
|
|
45
|
+
"""Release the lock, raises NotAcquired if not self.acquired"""
|
|
46
|
+
|
|
47
|
+
# Concrete methods
|
|
48
|
+
|
|
49
|
+
def acquire(self, blocking: bool = True, *, timeout_per: int | float | None = None) -> bool:
|
|
50
|
+
"""
|
|
51
|
+
Acquire the lock, return False only if (timeout or not blocking) and acquisition fails
|
|
52
|
+
Note that timeout is per-lock acquisition, there may be multiple locks internally
|
|
53
|
+
Timeout is not allowed if blocking is False
|
|
54
|
+
"""
|
|
55
|
+
if isinstance(timeout_per, int):
|
|
56
|
+
timeout_per = float(timeout_per)
|
|
57
|
+
if not isinstance(timeout_per, float | None):
|
|
58
|
+
raise TypeError("timeout_per must be of type: int | float | None")
|
|
59
|
+
if timeout_per is not None and timeout_per < 0:
|
|
60
|
+
raise ValueError("Non-negative timeout is required")
|
|
61
|
+
if timeout_per and not blocking:
|
|
62
|
+
raise ValueError("Timeout requires blocking=True")
|
|
63
|
+
return self._acquire(blocking, timeout_per)
|
|
64
|
+
|
|
65
|
+
def __enter__(self) -> Self:
|
|
66
|
+
"""Acquire the lock"""
|
|
67
|
+
self.acquire(True)
|
|
68
|
+
return self
|
|
69
|
+
|
|
70
|
+
def __exit__(self, *_: object) -> None:
|
|
71
|
+
"""Release the lock"""
|
|
72
|
+
self.release()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@final
|
|
76
|
+
class GlobalIPLock(KeyedInstance, AbstractIPLock):
|
|
77
|
+
"""
|
|
78
|
+
A thread-safe reentrant process lock keyed by a normalized resolved absolute file path to a regular file
|
|
79
|
+
Basically a thread-safe wrapper around InterProcessLock that adds reference counting
|
|
80
|
+
Warning: The passed file should be a regular file with no symlinks or hardlinks to it; this is not checked
|
|
81
|
+
Warning: All locks of the same path are the same instance. Locking is per-process, not per-thread
|
|
82
|
+
Warning: This lock uses the given path to syncronize inter-process locking, do not edit underlying file
|
|
83
|
+
InterProcessLock may free the lock on exit if still held
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
__slots__ = ("_ip_lock", "_path", "_rc", "_t_lock")
|
|
87
|
+
|
|
88
|
+
def __init__(self, path: Path) -> None:
|
|
89
|
+
"""
|
|
90
|
+
Construct a GlobalIPLock from a normalized resolved absolute path to an unlinked regular file
|
|
91
|
+
Consider calling .new(path) instead, as this normalizes and checks path safety on every invocation
|
|
92
|
+
Because instances are keyed by path, path must be a normalized absolute pathlib.Path
|
|
93
|
+
"""
|
|
94
|
+
if not isinstance(path, Path):
|
|
95
|
+
raise TypeError("path should be a Path; consider using .new()")
|
|
96
|
+
if path != (path := self.normalize(path)):
|
|
97
|
+
raise ValueError("GlobalIPLock paths must be normalized; consider using .new()")
|
|
98
|
+
self._ip_lock: Final[InterProcessLock] = InterProcessLock(path)
|
|
99
|
+
self._path: Path = path # b/c their path is in bytes
|
|
100
|
+
self._t_lock = RLock()
|
|
101
|
+
self._rc: int = 0
|
|
102
|
+
# Try to create the underlying file, this isn't actually necessary at the moment
|
|
103
|
+
# but useful to prevent other users / programs from messing with the file path
|
|
104
|
+
with suppress(OSError):
|
|
105
|
+
self._path.touch(exist_ok=True)
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def new(cls, path: str | Path) -> Self:
|
|
109
|
+
"""Construct the AbstractIPLock by normalizing the given path; also checks path for safety"""
|
|
110
|
+
path = cls.normalize(path)
|
|
111
|
+
return cls(path)
|
|
112
|
+
|
|
113
|
+
@staticmethod
|
|
114
|
+
def normalize(path: str | Path, check: bool = True) -> Path:
|
|
115
|
+
"""
|
|
116
|
+
Normalize and resolve a path to one that GlobalIPLock might accept
|
|
117
|
+
If check: Also checks path for non-regular files / file with hardlinks to it
|
|
118
|
+
"""
|
|
119
|
+
if isinstance(path, str):
|
|
120
|
+
path = Path(path)
|
|
121
|
+
if not isinstance(path, Path):
|
|
122
|
+
raise TypeError("path must be a str | pathlib.Path")
|
|
123
|
+
if check and path.is_symlink():
|
|
124
|
+
raise FileExistsError(f"File is a symlink: {path}")
|
|
125
|
+
path = normpath(path.resolve()).absolute()
|
|
126
|
+
if check:
|
|
127
|
+
try:
|
|
128
|
+
info = path.lstat()
|
|
129
|
+
if not S_ISREG(info.st_mode) or info.st_nlink != 1:
|
|
130
|
+
raise FileExistsError(f"The lock file exists but is not a regular file: {path}")
|
|
131
|
+
except FileNotFoundError:
|
|
132
|
+
pass
|
|
133
|
+
return path
|
|
134
|
+
|
|
135
|
+
# Overrides
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
@override
|
|
139
|
+
def path(self) -> Path:
|
|
140
|
+
"""The path the lock is synchronized on"""
|
|
141
|
+
return self._path
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
@override
|
|
145
|
+
def acquired(self) -> bool:
|
|
146
|
+
"""Return true if acquired"""
|
|
147
|
+
return bool(self._rc)
|
|
148
|
+
|
|
149
|
+
@override
|
|
150
|
+
def _acquire(self, blocking: bool, timeout_per: float | None) -> bool:
|
|
151
|
+
ret: bool = True
|
|
152
|
+
with self._t_lock:
|
|
153
|
+
assert bool(self._rc) == self._ip_lock.acquired
|
|
154
|
+
if not self._rc or not self._ip_lock.acquire(blocking=False):
|
|
155
|
+
ret = self._ip_lock.acquire(timeout=timeout_per) if blocking else False
|
|
156
|
+
self._rc += 1
|
|
157
|
+
return ret
|
|
158
|
+
|
|
159
|
+
@override
|
|
160
|
+
def release(self) -> None:
|
|
161
|
+
"""Release the lock"""
|
|
162
|
+
if not self.acquired:
|
|
163
|
+
raise NotAcquired(f"{self.__class__.__name__}: {self.path}")
|
|
164
|
+
with self._t_lock:
|
|
165
|
+
assert bool(self._rc) == self._ip_lock.acquired
|
|
166
|
+
if self._rc <= 1:
|
|
167
|
+
self._ip_lock.release()
|
|
168
|
+
self._rc -= 1
|
|
169
|
+
assert bool(self._rc) == self._ip_lock.acquired
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class LockPathInUse(LookupError):
|
|
173
|
+
"""
|
|
174
|
+
Raised when a user attempts to create an IPLock lock for a given
|
|
175
|
+
GlobalIPLock that already exists with a different reentrancy setting
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class _IPLock(AbstractIPLock):
|
|
180
|
+
"""
|
|
181
|
+
This lock can only be acquired if no other IPLock's hold a GlobalIPLock on path
|
|
182
|
+
Acquiring this lock first internally acquires the lock GlobalIPLock(path)
|
|
183
|
+
It then competes with all other IPLocks to acquire a lock keyed on path
|
|
184
|
+
Warning: This lock only syncronizes on against other IPLocks on path, not other GlobalIPLock(path)'s
|
|
185
|
+
If another object has a GlobalIPLock(path) IPLock will *not* block during acquire() until they release
|
|
186
|
+
Warning: As this uses GlobalIPLock(path), do not manually release GlobalIPLock(path) without
|
|
187
|
+
acquiring first or remove path, doing so may break the inter-process synchronization
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
__slots__ = ("_gipl", "_instance_lock", "_instance_reentrant", "_rc", "_sync_lock")
|
|
191
|
+
_cls_reentrant: ClassVar[bool] # For subclass to set
|
|
192
|
+
_data: ClassVar[Final[dict[Path, tuple[bool, Lock]]]] = {}
|
|
193
|
+
_data_lock: ClassVar[Final[Lock]] = Lock()
|
|
194
|
+
|
|
195
|
+
def __init__(self, gipl: GlobalIPLock | Path | str, *args: Any, **kwargs: Any) -> None:
|
|
196
|
+
"""
|
|
197
|
+
Construct an inter process lock syncronized by gipl (or GlobalIPLock.new(gipl) if str | Path)
|
|
198
|
+
If a lock of a different reentrancy setting already exists for this gipl, raise LockPathInUse
|
|
199
|
+
"""
|
|
200
|
+
super().__init__(*args, **kwargs) # For MRO superclasses
|
|
201
|
+
if isinstance(gipl, Path | str):
|
|
202
|
+
gipl = GlobalIPLock.new(gipl)
|
|
203
|
+
if not isinstance(gipl, GlobalIPLock):
|
|
204
|
+
raise TypeError("gipl must be a GlobalIPLock or an argument to GlobalIPLock.new")
|
|
205
|
+
self._gipl: Final[GlobalIPLock] = gipl
|
|
206
|
+
with self._data_lock:
|
|
207
|
+
got: tuple[bool, Lock] | None = self._data.get(gipl.path)
|
|
208
|
+
if got is None:
|
|
209
|
+
got = (self._cls_reentrant, Lock())
|
|
210
|
+
self._data[gipl.path] = got
|
|
211
|
+
if got[0] != self._cls_reentrant:
|
|
212
|
+
raise LockPathInUse(f"Want reentrant={self._cls_reentrant} but existing lock is the opposite")
|
|
213
|
+
self._instance_reentrant: Final[bool] = got[0]
|
|
214
|
+
self._sync_lock: Final[Lock] = got[1]
|
|
215
|
+
self._instance_lock: Final[Lock] = Lock() # Allow multiple threads to use this instance at once
|
|
216
|
+
self._rc: int = 0
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
@override
|
|
220
|
+
def path(self) -> Path:
|
|
221
|
+
"""The path the lock is synchronized on"""
|
|
222
|
+
return self._gipl.path
|
|
223
|
+
|
|
224
|
+
@property
|
|
225
|
+
@override
|
|
226
|
+
def acquired(self) -> bool:
|
|
227
|
+
"""Return true if locked"""
|
|
228
|
+
return bool(self._rc) # Might return False during .release() after rc -=1, before .release()
|
|
229
|
+
|
|
230
|
+
@override
|
|
231
|
+
def _acquire(self, blocking: bool, timeout_per: float | None) -> bool:
|
|
232
|
+
ret = False
|
|
233
|
+
if not self._gipl.acquire(blocking, timeout_per=timeout_per):
|
|
234
|
+
return ret
|
|
235
|
+
try:
|
|
236
|
+
with self._instance_lock:
|
|
237
|
+
acquired = self.acquired
|
|
238
|
+
if acquired and not self._instance_reentrant:
|
|
239
|
+
if timeout_per is None:
|
|
240
|
+
raise LockHung(f"{self.__class__.__name__}: {self.path}")
|
|
241
|
+
return ret
|
|
242
|
+
timeout = -1 if timeout_per is None else timeout_per
|
|
243
|
+
if acquired or self._sync_lock.acquire(blocking, timeout=timeout):
|
|
244
|
+
self._rc += 1
|
|
245
|
+
ret = True
|
|
246
|
+
finally:
|
|
247
|
+
if not ret:
|
|
248
|
+
self._gipl.release()
|
|
249
|
+
return ret
|
|
250
|
+
|
|
251
|
+
@override
|
|
252
|
+
def release(self) -> None:
|
|
253
|
+
"""Release the lock"""
|
|
254
|
+
with self._instance_lock:
|
|
255
|
+
if not self.acquired:
|
|
256
|
+
raise NotAcquired(f"{self.__class__.__name__}: {self.path}")
|
|
257
|
+
self._rc -= 1
|
|
258
|
+
if self._rc == 0:
|
|
259
|
+
try:
|
|
260
|
+
self._sync_lock.release()
|
|
261
|
+
except RuntimeError as e:
|
|
262
|
+
if e.args[0] == "cannot release un-acquired lock": # This should not happen
|
|
263
|
+
raise RuntimeError("Representation invariant broken") from e
|
|
264
|
+
raise
|
|
265
|
+
try:
|
|
266
|
+
self._gipl.release()
|
|
267
|
+
except NotAcquired as e:
|
|
268
|
+
raise OSError("The GlobalIPLock lock was already unlocked by something else") from e
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class IPLock(_IPLock):
|
|
272
|
+
"""A non-reentrant python lock that is synchronized across processes via a normalized path"""
|
|
273
|
+
|
|
274
|
+
_cls_reentrant = False
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class RIPLock(_IPLock):
|
|
278
|
+
"""A reentrant python lock that is synchronized across processes via a normalized path"""
|
|
279
|
+
|
|
280
|
+
_cls_reentrant = True
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
assert (
|
|
284
|
+
isinstance(_IPLock.__doc__, str) and isinstance(IPLock.__doc__, str) and isinstance(RIPLock.__doc__, str)
|
|
285
|
+
)
|
|
286
|
+
IPLock.__doc__ = IPLock.__doc__ + _IPLock.__doc__
|
|
287
|
+
RIPLock.__doc__ = RIPLock.__doc__ + _IPLock.__doc__
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
from typing import Any, ClassVar,
|
|
1
|
+
from typing import Any, ClassVar, Never, final, cast
|
|
2
2
|
from threading import Condition, Lock, get_ident
|
|
3
3
|
from collections.abc import Hashable
|
|
4
|
+
from abc import ABCMeta
|
|
4
5
|
import sys
|
|
5
6
|
|
|
6
|
-
__all__ = ("
|
|
7
|
+
__all__ = ("CircularConstruction", "KeyedInstance", "KeyedInstanceProcessError")
|
|
7
8
|
|
|
8
9
|
|
|
9
|
-
class
|
|
10
|
+
class CircularConstruction(RuntimeError):
|
|
10
11
|
"""Raised when keyed constructors form a circular dependency."""
|
|
11
12
|
|
|
12
13
|
def __init__(self, type_: type) -> None:
|
|
@@ -14,19 +15,23 @@ class CircularConstructionError(RuntimeError):
|
|
|
14
15
|
super().__init__(f"Circular construction dependency for {type_.__qualname__}")
|
|
15
16
|
|
|
16
17
|
|
|
17
|
-
class _Constructing
|
|
18
|
-
|
|
18
|
+
class _Constructing: # An int that is a unique type
|
|
19
|
+
|
|
20
|
+
__slots__ = ("tid",)
|
|
21
|
+
|
|
22
|
+
def __init__(self, tid: int) -> None:
|
|
23
|
+
self.tid: int = tid
|
|
19
24
|
|
|
20
25
|
|
|
21
26
|
@final
|
|
22
|
-
class _KeyedInstanceMeta(
|
|
27
|
+
class _KeyedInstanceMeta(ABCMeta):
|
|
23
28
|
"""Metaclass implementing thread-safe keyed instance construction"""
|
|
24
29
|
|
|
25
|
-
type
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
+
type _KIInstanceKey = tuple[type[KeyedInstance], Hashable]
|
|
31
|
+
_ki_instances: ClassVar[dict[_KIInstanceKey, KeyedInstance | _Constructing]] = {}
|
|
32
|
+
_ki_waiting: ClassVar[dict[int, _KIInstanceKey]] = {}
|
|
33
|
+
_ki_base_class: ClassVar[type[Any] | None] = None # KeyedInstance, after construction
|
|
34
|
+
_ki_condition: ClassVar[Condition] = Condition(Lock())
|
|
30
35
|
|
|
31
36
|
def __new__(
|
|
32
37
|
mcs: type[_KeyedInstanceMeta],
|
|
@@ -39,16 +44,16 @@ class _KeyedInstanceMeta(type):
|
|
|
39
44
|
if mcs is not _KeyedInstanceMeta:
|
|
40
45
|
raise TypeError("_KeyedInstanceMeta cannot be subclassed")
|
|
41
46
|
# Ensure nothing is deriving KeyedInstance
|
|
42
|
-
root = mcs.
|
|
47
|
+
root = mcs._ki_base_class
|
|
43
48
|
if root is not None and (
|
|
44
49
|
not any(base is root for base in bases)
|
|
45
50
|
or any(isinstance(base, _KeyedInstanceMeta) and base is not root for base in bases)
|
|
46
51
|
):
|
|
47
52
|
raise TypeError(f"{name} must directly inherit from KeyedInstance")
|
|
48
|
-
cls =
|
|
53
|
+
cls = super().__new__(mcs, name, bases, namespace, **kwargs)
|
|
49
54
|
# Lock in KeyedInstance as the base class as needed
|
|
50
55
|
if root is None:
|
|
51
|
-
mcs.
|
|
56
|
+
mcs._ki_base_class = cls
|
|
52
57
|
return cls
|
|
53
58
|
|
|
54
59
|
def __call__[T](cls: type[T], key: Hashable, *args: Any, **kwargs: Any) -> T:
|
|
@@ -58,14 +63,14 @@ class _KeyedInstanceMeta(type):
|
|
|
58
63
|
cache_key = (cast(type[KeyedInstance], cls), key)
|
|
59
64
|
|
|
60
65
|
# Lock-free fast path
|
|
61
|
-
instances = _KeyedInstanceMeta.
|
|
66
|
+
instances = _KeyedInstanceMeta._ki_instances
|
|
62
67
|
ret: KeyedInstance | _Constructing | None = instances.get(cache_key)
|
|
63
68
|
if ret is not None and not isinstance(ret, _Constructing):
|
|
64
69
|
return cast(T, ret)
|
|
65
70
|
|
|
66
71
|
construction_permission: _Constructing | None = None
|
|
67
|
-
waiting = _KeyedInstanceMeta.
|
|
68
|
-
condition = _KeyedInstanceMeta.
|
|
72
|
+
waiting = _KeyedInstanceMeta._ki_waiting
|
|
73
|
+
condition = _KeyedInstanceMeta._ki_condition
|
|
69
74
|
tid: int = get_ident()
|
|
70
75
|
try:
|
|
71
76
|
while True: # Keep trying until some thread constructs the object
|
|
@@ -96,7 +101,7 @@ class _KeyedInstanceMeta(type):
|
|
|
96
101
|
break
|
|
97
102
|
blocking = dependency.tid
|
|
98
103
|
else:
|
|
99
|
-
raise
|
|
104
|
+
raise CircularConstruction(cls)
|
|
100
105
|
|
|
101
106
|
# Wait for a thread to finish construction then recheck if we can start
|
|
102
107
|
condition.wait()
|
|
@@ -105,7 +110,7 @@ class _KeyedInstanceMeta(type):
|
|
|
105
110
|
|
|
106
111
|
# Construct the object finally then store the result
|
|
107
112
|
assert construction_permission is not None
|
|
108
|
-
ret =
|
|
113
|
+
ret = super().__call__(key, *args, **kwargs) # type: ignore[misc] # cls is an mcs
|
|
109
114
|
assert isinstance(ret, KeyedInstance)
|
|
110
115
|
with condition:
|
|
111
116
|
instances[cache_key] = ret
|
|
@@ -134,9 +139,9 @@ class KeyedInstance(metaclass=_KeyedInstanceMeta):
|
|
|
134
139
|
The first thread to claim a cache key performs construction. If
|
|
135
140
|
construction fails, another waiting thread can attempt construction.
|
|
136
141
|
|
|
137
|
-
If items being constructed require constructing each other, a
|
|
142
|
+
If items being constructed require constructing each other, a CircularConstruction is raised
|
|
138
143
|
|
|
139
|
-
Do not mix this with fork
|
|
144
|
+
Do not mix this with fork (uses thread ids internally); multiprocessing spawn is ok
|
|
140
145
|
"""
|
|
141
146
|
|
|
142
147
|
def __reduce_ex__(self, *_: object) -> Never:
|
|
@@ -155,8 +160,8 @@ def _check_fork(event: str, *_: Any) -> None:
|
|
|
155
160
|
if event not in {"os.fork", "os.forkpty"}:
|
|
156
161
|
return
|
|
157
162
|
# pylint: disable=protected-access
|
|
158
|
-
with _KeyedInstanceMeta.
|
|
159
|
-
if _KeyedInstanceMeta.
|
|
163
|
+
with _KeyedInstanceMeta._ki_condition:
|
|
164
|
+
if _KeyedInstanceMeta._ki_instances or _KeyedInstanceMeta._ki_waiting: # Only raise if used
|
|
160
165
|
raise KeyedInstanceProcessError("Cannot fork after creating KeyedInstance instances")
|
|
161
166
|
# pylint: enable=protected-access
|
|
162
167
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from typing import ClassVar, Never, Any
|
|
1
|
+
from typing import ClassVar, Never, Any, cast
|
|
2
2
|
from collections import defaultdict
|
|
3
3
|
from threading import RLock
|
|
4
4
|
from functools import cache
|
|
@@ -46,30 +46,23 @@ class _SingletonType(type):
|
|
|
46
46
|
ret = cls._instances[cls] = super().__call__(*args, **kwargs)
|
|
47
47
|
return ret
|
|
48
48
|
|
|
49
|
-
@classmethod
|
|
50
49
|
@cache
|
|
51
|
-
def instance(
|
|
50
|
+
def instance[T: Singleton](cls: type[T]) -> T:
|
|
52
51
|
"""Get the instance of cls"""
|
|
53
|
-
|
|
54
|
-
|
|
52
|
+
# pylint: disable=protected-access
|
|
53
|
+
mcs = cast(_SingletonType, type(cls)) # mypy can't figure this out :/
|
|
55
54
|
with mcs._lock:
|
|
56
|
-
cls_lock = mcs._cls_locks[
|
|
55
|
+
cls_lock = mcs._cls_locks[cls]
|
|
57
56
|
with cls_lock:
|
|
58
|
-
if (got := mcs._instances.get(
|
|
59
|
-
raise NoInstanceError(f"No instance of {
|
|
60
|
-
|
|
57
|
+
if (got := mcs._instances.get(cls, None)) is None:
|
|
58
|
+
raise NoInstanceError(f"No instance of {cls.__qualname__} found")
|
|
59
|
+
# pylint: enable=protected-access
|
|
60
|
+
return cast(T, got)
|
|
61
61
|
|
|
62
62
|
|
|
63
63
|
class Singleton(metaclass=_SingletonType):
|
|
64
64
|
"""A thread-safe singleton base class"""
|
|
65
65
|
|
|
66
|
-
@classmethod
|
|
67
|
-
def instance(cls) -> Singleton:
|
|
68
|
-
"""Blocking get the instance of cls; raise if not constructed"""
|
|
69
|
-
assert isinstance(cls, _SingletonType), "Metaclass should be _SingletonType"
|
|
70
|
-
tc: type[_SingletonType] = type(cls)
|
|
71
|
-
return tc.instance(cls)
|
|
72
|
-
|
|
73
66
|
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
|
|
74
67
|
"""Disallow subclassing"""
|
|
75
68
|
cls.__init_subclass__ = _no_subclass # type: ignore[method-assign]
|
|
@@ -8,11 +8,13 @@ tests/test_exc_capture.py
|
|
|
8
8
|
tests/test_frozen.py
|
|
9
9
|
tests/test_hybridmethod.py
|
|
10
10
|
tests/test_io.py
|
|
11
|
+
tests/test_ip_lock.py
|
|
11
12
|
tests/test_keyed_instance.py
|
|
12
13
|
tests/test_lazy.py
|
|
13
14
|
tests/test_not_set.py
|
|
14
15
|
tests/test_prompt.py
|
|
15
16
|
tests/test_singleton.py
|
|
17
|
+
tests/test_util.py
|
|
16
18
|
tests/log/__init__.py
|
|
17
19
|
tests/log/base.py
|
|
18
20
|
tests/log/test_cute.py
|
|
@@ -24,6 +26,7 @@ zstdlib/exc_capture.py
|
|
|
24
26
|
zstdlib/frozen.py
|
|
25
27
|
zstdlib/hybridmethod.py
|
|
26
28
|
zstdlib/io.py
|
|
29
|
+
zstdlib/ip_lock.py
|
|
27
30
|
zstdlib/keyed_instance.py
|
|
28
31
|
zstdlib/lazy.py
|
|
29
32
|
zstdlib/macos.py
|
|
@@ -32,6 +35,7 @@ zstdlib/prompt.py
|
|
|
32
35
|
zstdlib/py.typed
|
|
33
36
|
zstdlib/signal_cm.py
|
|
34
37
|
zstdlib/singleton.py
|
|
38
|
+
zstdlib/util.py
|
|
35
39
|
zstdlib.egg-info/PKG-INFO
|
|
36
40
|
zstdlib.egg-info/SOURCES.txt
|
|
37
41
|
zstdlib.egg-info/dependency_links.txt
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|