async-anywhere 0.0.1__py3-none-any.whl

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.
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ __version__ = "0.0.1"
4
+ __author__ = "Zac Bentley"
5
+ __url__ = "https://github.com/zbentley/async-anywhere"
6
+ # Read documentation for this module at https://async-anywhere.readthedocs.io
7
+ __all__ = []
@@ -0,0 +1,214 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ import threading
6
+ from collections import deque
7
+ from collections.abc import Callable, Collection
8
+ from functools import cache
9
+ from threading import RLock, Thread, current_thread
10
+ from typing import final
11
+ from weakref import ref
12
+
13
+ from async_anywhere._util.fork_safety import ForkSafeInstanceTracker
14
+ from async_anywhere._util.trio import TrioRuntime
15
+ from async_anywhere.exceptions import WouldBlock
16
+
17
+
18
+ def AnyEventLoop() -> bool:
19
+ """Sentinel for the ``prevent_blocking_wait_within`` parameter of :py:meth:`AwaitableFuture.__init__`: raises
20
+ :py:class:`WouldBlock` instead of blocking if any event loop or :doc:`Trio <trio:index>` task is running."""
21
+ return asyncio._get_running_loop() is not None or TrioRuntime.in_task()
22
+
23
+
24
+ def BlockingNotAllowed() -> bool:
25
+ """Sentinel for the ``prevent_blocking_wait_within`` parameter of :py:meth:`AwaitableFuture.__init__`: raises
26
+ :py:class:`WouldBlock` instead of blocking in all cases."""
27
+ return True
28
+
29
+
30
+ # TODO better annotate: incorporate constant sentinels.
31
+ # TODO better annotate: refer to it elsewhere.
32
+ # TODO better annotate: inline in docs.
33
+ type BlockingEnvironments = Collection[asyncio.AbstractEventLoop | Thread | Callable[[], bool]]
34
+
35
+
36
+ @cache
37
+ def futures_logger() -> logging.Logger:
38
+ """
39
+ What :py:class:`AwaitableFuture` logs to when un-observed errors or warnings occur (e.g. an :py:class:`Exception`
40
+ is raised by a callback added via ``add_done_callback``--but not a :py:class:`BaseException`, those are raised
41
+ and abort callback handling!).
42
+
43
+ It's a child of the logger used internally by :py:class:`concurrent.futures.Future` for the same purpose, and is
44
+ constructed and cached lazily. Laziness and child-ness allow user environments which customize the logging behavior
45
+ of :py:class:`concurrent.futures.Future` to affect this logger as well.
46
+ """
47
+ import concurrent.futures._base
48
+
49
+ # TODO guard against the symbol moving?
50
+ return concurrent.futures._base.LOGGER.getChild("async_anywhere")
51
+
52
+
53
+ class Toggleable:
54
+ # TODO perf of having a __bool__ *property*?
55
+ __slots__ = ("_value",)
56
+
57
+ def __init__(self):
58
+ self._value = False
59
+
60
+ def set(self):
61
+ self._value = True
62
+
63
+ def __bool__(self):
64
+ return self._value
65
+
66
+
67
+ @final
68
+ class ConditionProtected[T](threading.Condition):
69
+ """A threading.Condition over an RLock, which also guards a value, which entering it gives. Never left held by a signal
70
+ handler's exception (see __enter__()), and reset in each child process os.fork()ed from one that has it, unless the
71
+ forking thread held it (see _at_fork_reinit())."""
72
+
73
+ # __exit__ is a slot, not a method: with-statements look it up on the class, whose slot descriptor gives them this
74
+ # instance's lock's own (C) __exit__, so leaving a with-block runs no Python frame
75
+ __slots__ = ("_value", "__exit__")
76
+ __exit__: Callable[..., None]
77
+
78
+ def __init__(self, value: T):
79
+ # threading.Condition.__init__()'s fields, set without calling it, or its checks of what an RLock has: this is
80
+ # made with each StateTracker. An RLock, not a Lock, which neither __enter__() nor _at_fork_reinit() can handle.
81
+ # Of the lock's methods, copied are just those each completed future uses, and _acquire_restore(): a Python
82
+ # forwarder's entry runs a check, where a KeyboardInterrupt would leave wait() without the lock back. The rest are
83
+ # forwarded below, saving each construction their bound methods.
84
+ self._lock = lock = RLock()
85
+ self.acquire = lock.acquire
86
+ self._is_owned = lock._is_owned
87
+ self._acquire_restore = lock._acquire_restore
88
+ self.__exit__ = lock.__exit__
89
+ self._waiters = deque()
90
+ self._value = value
91
+ _conditions.ensure_registered(self)
92
+
93
+ def __enter__(self) -> T:
94
+ """
95
+ Acquires the lock and returns the value, making sure the lock is released if anything goes wrong during
96
+ acquisition.
97
+
98
+ All RLocks and things based on them are, in CPython, interrupt (as in KeyboardInterrupt/signals) unsafe: they
99
+ can, if interrupted while being acquired, be left held. This sucks a lot with regards to context managers,
100
+ because __enter__ can raise before the manager is entered (meaning that __exit__ isn't run) but after the
101
+ manager was mutated (lock was acquired), leaving things in a super deadlock-prone state.
102
+
103
+ This problem can't be solved; interrupt-unsafety is a feature of basically all Python code that doesn't manage
104
+ signal delivery directly: https://docs.python.org/3/library/signal.html#note-on-signal-handlers-and-exceptions
105
+
106
+ Several things make this worse nowadays for this module's code:
107
+ - Python 3.14 made the window during which context-manager-entry corruption can occur with a stdlib lock wider;
108
+ https://github.com/python/cpython/issues/74174.
109
+ - Lots of code in this module is coordinated with locks and designed to be used from synchronous main-thread
110
+ Python, where signals get delivered by default.
111
+ - We heavily use RLocks and Python context manager wrappers around locks, widening the window further.
112
+ - EventLoopExecutor futures being waited on in the main thread are an area where CTRL+C is likely to hit a lot.
113
+ If it hits during a lock acquire, the executor can get stuck inside its worker thread trying to interact with
114
+ the job. Then, anyone using the executor itself as a contextmanager will hit a deadlock-wait with executor
115
+ shutdown on exit, requiring CTRL+C spamming to shut the process down.
116
+
117
+ This method slightly mitigates those risk factors. NOTE, again, that there are plenty of places in this module
118
+ where CTRL+C will cause a hang. This method's "release on BaseException during context manager entry" just
119
+ shaves off a few digits from the probability of it happening in one common case. This module provides no general
120
+ facilities for interrupt-safe Python code. If you want that, run your whole program inside an event loop, move
121
+ signal-sensitive code onto a thread, or use Trio.
122
+ """
123
+ try:
124
+ self.acquire()
125
+ except BaseException:
126
+ try:
127
+ # The lock's own (C) release(), not this class's: entering a Python one runs a check before letting go
128
+ self._lock.release() # Taken, unless acquire() was interrupted waiting: an RLock this thread holds never waits
129
+ except RuntimeError: # Not taken
130
+ pass
131
+ raise
132
+ return self._value
133
+
134
+ def release(self):
135
+ self._lock.release()
136
+
137
+ def locked(self) -> bool:
138
+ return self._lock.locked()
139
+
140
+ def _release_save(self): # threading.Condition's own is for a plain Lock, which has no recursion level to save
141
+ return self._lock._release_save()
142
+
143
+ def replace_value(self, value: T) -> T:
144
+ """Replaces the value. Not thread-safe unless called inside this class's context manager."""
145
+ self._value = value
146
+ return value
147
+
148
+ def _at_fork_reinit(self):
149
+ # As threading.Condition's, but leaving the lock alone if the forking thread holds it, as that thread lets go
150
+ self._waiters.clear() # Their threads aren't here
151
+ if not self._is_owned():
152
+ self._lock._at_fork_reinit()
153
+
154
+
155
+ class _ConditionForkSafety(ForkSafeInstanceTracker):
156
+ def after_fork_in_child(self):
157
+ for condition in self: # A WeakSet iterates a copy of itself
158
+ condition._at_fork_reinit()
159
+
160
+
161
+ # Every ConditionProtected. Made, so its fork handler registered, as this module is imported: before this package's
162
+ # others (in its _fork_safety modules), which so find every condition reset
163
+ _conditions = _ConditionForkSafety()
164
+
165
+
166
+ @final
167
+ class BlockingChecker:
168
+ """Where blocking waits for a future would deadlock, so are refused: on given threads, in given event loops (both held
169
+ weakly), in any running event loop or trio task (AnyEventLoop), or anywhere (BlockingNotAllowed)."""
170
+
171
+ __slots__ = ("_environments",)
172
+
173
+ def __init__(self, environments: BlockingEnvironments = ()):
174
+ # TODO check for perf improvements to be had by combining init and weakened and re-calling init elsewhere?
175
+ self._environments = BlockingChecker._weakened(environments)
176
+
177
+ @staticmethod
178
+ def _weakened(environments: Collection) -> tuple:
179
+ # Threads and loops as weak references, so that futures never keep them alive: AnyEventLoop and
180
+ # BlockingNotAllowed as they are
181
+ weakened = []
182
+ for environment in environments:
183
+ if isinstance(environment, (asyncio.AbstractEventLoop, Thread)):
184
+ weakened.append(ref(environment))
185
+ elif environment is AnyEventLoop or environment is BlockingNotAllowed:
186
+ weakened.append(environment)
187
+ else:
188
+ raise TypeError(
189
+ f"Blocking waits can be refused in event loops, on threads, or by AnyEventLoop or BlockingNotAllowed, not {environment!r}"
190
+ )
191
+ return tuple(weakened)
192
+
193
+ def copy(self, *, add: BlockingEnvironments = ()) -> BlockingChecker:
194
+ """A new checker, refusing what this one does now, and `environments` too."""
195
+ new = BlockingChecker.__new__(BlockingChecker)
196
+ new._environments = self._environments + BlockingChecker._weakened(add)
197
+ return new
198
+
199
+ def add(self, environment: asyncio.AbstractEventLoop | Thread | Callable[[], bool]):
200
+ # Dropping what's gone, as a SingletonEventLoopExecutor's checker gets a thread for every executor it makes
201
+ kept = [env for env in self._environments if not isinstance(env, ref) or env() is not None]
202
+ self._environments = (*kept, *BlockingChecker._weakened((environment,)))
203
+
204
+ def check(self, subject):
205
+ thread, loop, culprit = current_thread(), asyncio._get_running_loop(), None
206
+ try:
207
+ for environment in self._environments:
208
+ if isinstance(environment, ref): # A thread or loop, or None once it's gone
209
+ if (culprit := environment()) is thread or (loop is not None and culprit is loop):
210
+ raise WouldBlock(subject, culprit)
211
+ elif environment(): # AnyEventLoop or BlockingNotAllowed
212
+ raise WouldBlock(subject, environment)
213
+ finally:
214
+ del subject, thread, loop, culprit # Else what this raises would keep them alive, through its traceback
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from abc import ABC, abstractmethod
5
+ from weakref import WeakSet
6
+
7
+
8
+ class ForkSafeInstanceTracker(WeakSet, ABC):
9
+ __slots__ = ("ensure_registered", "ensure_unregistered")
10
+
11
+ def __init__(self):
12
+ super().__init__()
13
+
14
+ if hasattr(os, "register_at_fork"):
15
+ self.ensure_registered = self.add
16
+ self.ensure_unregistered = self.discard
17
+ os.register_at_fork(after_in_child=self.after_fork_in_child)
18
+ else:
19
+ self.ensure_registered = self.ensure_unregistered = lambda _: None
20
+
21
+ @abstractmethod
22
+ def after_fork_in_child(self):
23
+ raise NotImplementedError
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.util import find_spec
4
+ from typing import Callable, TYPE_CHECKING
5
+
6
+ import sniffio
7
+
8
+ if TYPE_CHECKING:
9
+ import trio as _trio
10
+
11
+
12
+ class TrioRuntime:
13
+ current_token: Callable[[], _trio.lowlevel.TrioToken] # trio's own, bound by _in_trio_task() on first use
14
+
15
+ if find_spec("trio") is None: # Then nothing can be awaiting in trio
16
+ in_task = bool
17
+ else:
18
+
19
+ @staticmethod
20
+ def in_task() -> bool:
21
+ # trio.run() and guest ticks set it: cheaper than in_trio_task(), which raises internally outside trio
22
+ return sniffio.thread_local.name == "trio" and TrioRuntime._in_trio_task()
23
+
24
+ @staticmethod
25
+ def _in_trio_task() -> bool:
26
+ # Only reached in a trio run, which has imported trio: so unused or absent, trio costs nothing
27
+ import trio as _trio
28
+
29
+ TrioRuntime._in_trio_task = _trio.lowlevel.in_trio_task # In place of this one, from now on
30
+ TrioRuntime.current_token = staticmethod(_trio.lowlevel.current_trio_token)
31
+ return _trio.lowlevel.in_trio_task()
@@ -0,0 +1,195 @@
1
+ r"""
2
+ Note:
3
+ Users interacting with exception classes defined in this module must follow these rules:
4
+
5
+ - Do not subclass or manually construct :py:class:`AsyncAnywhereException` or any subclass thereof from user code.
6
+ - Treat instances of :py:class:`AsyncAnywhereException` as immutable. Changing any fields on them may break
7
+ functionality. Standard automatic mutation via the Python runtime (e.g. call stack stitching) is permitted.
8
+
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import concurrent.futures
15
+ import copyreg
16
+ import os
17
+ from abc import ABC
18
+ from copy import copy
19
+ from typing import TYPE_CHECKING, final, Self
20
+
21
+ if TYPE_CHECKING:
22
+ from async_anywhere.state_tracker import State, StateTracker
23
+
24
+
25
+ __all__ = [
26
+ "AsyncAnywhereException",
27
+ "CleanStop",
28
+ "StateTrackerError",
29
+ "EventLoopExecutorBroken",
30
+ "EventLoopExecutorForked",
31
+ "JobCancelledByExecutorShutdown",
32
+ "EventLoopExecutorStopped",
33
+ "WouldBlock",
34
+ ]
35
+
36
+
37
+ # ABC in a class's own bases marks one we never instantiate: only a marker, as BaseException.__new__() checks nothing
38
+ class AsyncAnywhereException(ABC, Exception):
39
+ r"""
40
+ All custom (non-stdlib) exceptions raised by this library are subclasses of this class.
41
+
42
+ All :py:class:`AsyncAnywhereException`\ s can be pickled/unpickled/copied and shared between processes.
43
+
44
+ Code in this library that raises exceptions (including stdlib Exceptions and :py:class:`AsyncAnywhereException`\ s)
45
+ does so in a way that does not artificially prolong object lifetimes (e.g. this library will not raise errors whose
46
+ handling or storage results in an event loop not being garbage collected when it should be). If you find that this is
47
+ not the case in a specific situation, :ref:`file a bug <reporting_issues>`.
48
+ """
49
+
50
+ __slots__ = ()
51
+
52
+ def __reduce__(self):
53
+ # For copy and pickle: recreate from args (for some, a formatted message) without calling __init__, which may
54
+ # not take them
55
+ return copyreg.__newobj__, (type(self), *self.args), vars(self)
56
+
57
+ def copy(self, *causes: BaseException) -> Self:
58
+ """Returns a deep copy of this exception object, optionally with additional ``__causes__`` added to its lineage.
59
+
60
+ :meta private:
61
+ """
62
+ return AsyncAnywhereException.copy_exception(self, *causes)
63
+
64
+ @final
65
+ @staticmethod
66
+ def copy_exception[E: BaseException](error: E, *causes: BaseException) -> E:
67
+ """A copy of `error` to raise in its place: the interpreter changes an exception's traceback and context as it's
68
+ raised, as add_note() does its notes, so raising one that others may be raising too would mix theirs into it. The
69
+ copy starts from the original's traceback, and is raised from `causes`, each from the next, if any are given, or
70
+ else from what the original was. Only for exceptions that copy.copy() round-trips: builtins and ours, not users'
71
+ in general.
72
+
73
+ :meta private:
74
+ """
75
+ new = copy(error).with_traceback(error.__traceback__)
76
+ new.__context__ = error.__context__
77
+ if len(notes := getattr(error, "__notes__", ())) > 0:
78
+ new.__notes__ = list(notes)
79
+ if len(causes) > 0:
80
+ # Copying all but the last, whose cause is kept
81
+ new.__cause__ = AsyncAnywhereException.copy_exception(*causes) if len(causes) > 1 else causes[0]
82
+ else:
83
+ new.__cause__, new.__suppress_context__ = error.__cause__, error.__suppress_context__
84
+ return new
85
+
86
+
87
+ # Futures
88
+
89
+
90
+ class WouldBlock(AsyncAnywhereException, RuntimeError):
91
+ """Raised when synchronously waiting for an action performed by ``async_anywhere`` would block in an environment
92
+ where blocking is not allowed.
93
+
94
+ For example, this is raised from :py:meth:`AwaitableFuture.result` when that method needs to synchronously wait for
95
+ a future to complete from a thread or event loop that the user marked as forbidden for blocking waits via the
96
+ ``prevent_blocking_wait_within`` parameter of :py:meth:`AwaitableFuture.__init__`.
97
+ """
98
+
99
+ def __init__(self, subject, environment) -> None:
100
+ """:meta private:"""
101
+ # A thread or loop, or else AnyEventLoop or BlockingNotAllowed, from _util: named as users find them
102
+ if getattr(environment, "__module__", None) == "async_anywhere._util": # Instances of builtins have none
103
+ environment = f"- AwaitableFuture.{environment.__name__}"
104
+ else:
105
+ environment = f"in {environment!r}"
106
+ super().__init__(
107
+ f"Waiting for {subject!r} would deadlock {environment} (configured via prevent_blocking_wait_within)"
108
+ )
109
+
110
+
111
+ # State trackers
112
+
113
+
114
+ class StateTrackerError(AsyncAnywhereException, asyncio.InvalidStateError, concurrent.futures.InvalidStateError):
115
+ r"""Raised when invalid configuration is requested for or invalid actions are performed on a
116
+ :py:class:`StateTracker`."""
117
+
118
+ def __init__(
119
+ self,
120
+ source: StateTracker,
121
+ msg: str,
122
+ *states: State,
123
+ ):
124
+ """:meta private:"""
125
+ desc = self._state_names(*states)
126
+ errprefix = f"{source.__class__.__qualname__}[state={source.state.name}]"
127
+ super().__init__(f"{errprefix}: {msg.strip(" :")}: {desc}")
128
+
129
+ @classmethod
130
+ def _state_names(cls, *states: State) -> str:
131
+ assert len(states) > 0
132
+ if len(states) == 1:
133
+ return states[0].name
134
+ return f'one of {", ".join(sorted(s.name for s in states))}'
135
+
136
+
137
+ # Executors
138
+
139
+
140
+ class EventLoopExecutorStopped(AsyncAnywhereException, Exception):
141
+ """
142
+ Indicates that an :py:class:`EventLoopExecutor` has :ref:`stopped <stopping>`, and why.
143
+
144
+ Raised (and sometimes returned) from various EventLoopExecutor functions, and may also be raised from :term:`job`
145
+ futures when jobs are aborted due to executor stop."""
146
+
147
+ def __init__(self, summary: str, cause: BaseException | None = None):
148
+ """:meta private:"""
149
+ super().__init__(summary)
150
+ self.__cause__ = cause
151
+
152
+
153
+ class CleanStop(EventLoopExecutorStopped):
154
+ r"""Indicates that an :py:class:`EventLoopExecutor` stopped without :ref:`cancelling <cancellation>` any :term:`job`\ s (the
155
+ :term:`main task` is always cancelled regardless)."""
156
+
157
+
158
+ class EventLoopExecutorBroken(EventLoopExecutorStopped, ABC):
159
+ """Indicates that an :py:class:`EventLoopExecutor` cannot perform the requested action(s) because it was stopped
160
+ due to an internal error or unsupported state."""
161
+
162
+
163
+ class EventLoopExecutorForked(EventLoopExecutorBroken):
164
+ """Indicates that an :py:class:`EventLoopExecutor` cannot perform the requested action(s) because it was created in
165
+ a parent process and cannot be used in a forked child. See
166
+ :ref:`fork_safety` for more information."""
167
+
168
+ def __init__(self, summary: str = "", cause: BaseException | None = None):
169
+ """:meta private:"""
170
+ super().__init__(summary or f"forked into process {os.getpid()}", cause)
171
+
172
+
173
+ class JobCancelledByExecutorShutdown(AsyncAnywhereException, concurrent.futures.CancelledError):
174
+ r"""Raised from attempts to wait on an :py:class:`EventLoopExecutor`'s :term:`job` that has been :ref:`cancelled <cancellation>` due to
175
+ an executor stop condition that cancels running work (e.g. ``EventLoopExecutor.shutdown(cancel_futures=True)``)."""
176
+
177
+ @classmethod
178
+ def from_cancellation(
179
+ cls,
180
+ cancelled: asyncio.CancelledError | EventLoopExecutorStopped,
181
+ stopped: EventLoopExecutorStopped | None = None,
182
+ ) -> Self:
183
+ """For a job cancelled by a stop: given its asyncio.CancelledError, and why the executor stopped; or, for a job
184
+ never started, why the executor stopped. Always ``raise from`` -ed a copy of the original stop cause.
185
+
186
+ :meta private:
187
+ """
188
+ if isinstance(cancelled, EventLoopExecutorStopped):
189
+ interrupted, stopped = cls(), cancelled
190
+ else:
191
+ interrupted = cls(*cancelled.args).with_traceback(
192
+ cancelled.__traceback__
193
+ ) # Ending where the job was cancelled
194
+ interrupted.__cause__ = stopped.copy()
195
+ return interrupted