Debian Codegraph @

src/trio/_core/_asyncgens.py

raw
1 from __future__ import annotations
2
3 import logging
4 import sys
5 import warnings
6 import weakref
7 from typing import TYPE_CHECKING, NoReturn, TypeVar
8
9 import attrs
10
11 from .. import _core
12 from .._util import name_asyncgen
13 from . import _run
14
15 # Used to log exceptions in async generator finalizers
16 ASYNCGEN_LOGGER = logging.getLogger("trio.async_generator_errors")
17
18 if TYPE_CHECKING:
19 from collections.abc import Callable
20 from types import AsyncGeneratorType
21
22 from typing_extensions import ParamSpec
23
24 _P = ParamSpec("_P")
25
26 _WEAK_ASYNC_GEN_SET = weakref.WeakSet[AsyncGeneratorType[object, NoReturn]]
27 _ASYNC_GEN_SET = set[AsyncGeneratorType[object, NoReturn]]
28 else:
29 _WEAK_ASYNC_GEN_SET = weakref.WeakSet
30 _ASYNC_GEN_SET = set
31
32 _R = TypeVar("_R")
33
34
35 @_core.disable_ki_protection
36 def _call_without_ki_protection(
37 f: Callable[_P, _R],
38 /,
39 *args: _P.args,
40 **kwargs: _P.kwargs,
41 ) -> _R:
42 return f(*args, **kwargs)
43
44
45 @attrs.define(eq=False)
46 class AsyncGenerators:
47 # Async generators are added to this set when first iterated. Any
48 # left after the main task exits will be closed before trio.run()
49 # returns. During most of the run, this is a WeakSet so GC works.
50 # During shutdown, when we're finalizing all the remaining
51 # asyncgens after the system nursery has been closed, it's a
52 # regular set so we don't have to deal with GC firing at
53 # unexpected times.
54 alive: _WEAK_ASYNC_GEN_SET | _ASYNC_GEN_SET = attrs.Factory(_WEAK_ASYNC_GEN_SET)
55 # The ids of foreign async generators are added to this set when first
56 # iterated. Usually it is not safe to refer to ids like this, but because
57 # we're using a finalizer we can ensure ids in this set do not outlive
58 # their async generator.
59 foreign: set[int] = attrs.Factory(set)
60
61 # This collects async generators that get garbage collected during
62 # the one-tick window between the system nursery closing and the
63 # init task starting end-of-run asyncgen finalization.
64 trailing_needs_finalize: _ASYNC_GEN_SET = attrs.Factory(_ASYNC_GEN_SET)
65
66 prev_hooks: sys._asyncgen_hooks = attrs.field(init=False)
67
68 def install_hooks(self, runner: _run.Runner) -> None:
69 def firstiter(agen: AsyncGeneratorType[object, NoReturn]) -> None:
70 if hasattr(_run.GLOBAL_RUN_CONTEXT, "task"):
71 self.alive.add(agen)
72 else:
73 # An async generator first iterated outside of a Trio
74 # task doesn't belong to Trio. Probably we're in guest
75 # mode and the async generator belongs to our host.
76 # A strong set of ids is one of the only good places to
77 # remember this fact, at least until
78 # https://github.com/python/cpython/issues/85093 is implemented.
79 self.foreign.add(id(agen))
80 if self.prev_hooks.firstiter is not None:
81 self.prev_hooks.firstiter(agen)
82
83 def finalize_in_trio_context(
84 agen: AsyncGeneratorType[object, NoReturn],
85 agen_name: str,
86 ) -> None:
87 try:
88 runner.spawn_system_task(
89 self._finalize_one,
90 agen,
91 agen_name,
92 name=f"close asyncgen {agen_name} (abandoned)",
93 )
94 except RuntimeError:
95 # There is a one-tick window where the system nursery
96 # is closed but the init task hasn't yet made
97 # self.asyncgens a strong set to disable GC. We seem to
98 # have hit it.
99 self.trailing_needs_finalize.add(agen)
100
101 @_core.enable_ki_protection
102 def finalizer(agen: AsyncGeneratorType[object, NoReturn]) -> None:
103 try:
104 self.foreign.remove(id(agen))
105 except KeyError:
106 is_ours = True
107 else:
108 is_ours = False
109
110 agen_name = name_asyncgen(agen)
111 if is_ours:
112 runner.entry_queue.run_sync_soon(
113 finalize_in_trio_context,
114 agen,
115 agen_name,
116 )
117
118 # Do this last, because it might raise an exception
119 # depending on the user's warnings filter. (That
120 # exception will be printed to the terminal and
121 # ignored, since we're running in GC context.)
122 warnings.warn(
123 f"Async generator {agen_name!r} was garbage collected before it "
124 "had been exhausted. Surround its use in 'async with "
125 "aclosing(...):' to ensure that it gets cleaned up as soon as "
126 "you're done using it.",
127 ResourceWarning,
128 stacklevel=2,
129 source=agen,
130 )
131 else:
132 # Not ours -> forward to the host loop's async generator finalizer
133 finalizer = self.prev_hooks.finalizer
134 if finalizer is not None:
135 _call_without_ki_protection(finalizer, agen)
136 else:
137 # Host has no finalizer. Reimplement the default
138 # Python behavior with no hooks installed: throw in
139 # GeneratorExit, step once, raise RuntimeError if
140 # it doesn't exit.
141 closer = agen.aclose()
142 try:
143 # If the next thing is a yield, this will raise RuntimeError
144 # which we allow to propagate
145 _call_without_ki_protection(closer.send, None)
146 except StopIteration:
147 pass
148 else:
149 # If the next thing is an await, we get here. Give a nicer
150 # error than the default "async generator ignored GeneratorExit"
151 raise RuntimeError(
152 f"Non-Trio async generator {agen_name!r} awaited something "
153 "during finalization; install a finalization hook to "
154 "support this, or wrap it in 'async with aclosing(...):'",
155 )
156
157 self.prev_hooks = sys.get_asyncgen_hooks()
158 sys.set_asyncgen_hooks(firstiter=firstiter, finalizer=finalizer) # type: ignore[arg-type] # Finalizer doesn't use AsyncGeneratorType
159
160 async def finalize_remaining(self, runner: _run.Runner) -> None:
161 # This is called from init after shutting down the system nursery.
162 # The only tasks running at this point are init and
163 # the run_sync_soon task, and since the system nursery is closed,
164 # there's no way for user code to spawn more.
165 assert _core.current_task() is runner.init_task
166 assert len(runner.tasks) == 2
167
168 # To make async generator finalization easier to reason
169 # about, we'll shut down asyncgen garbage collection by turning
170 # the alive WeakSet into a regular set.
171 self.alive = set(self.alive)
172
173 # Process all pending run_sync_soon callbacks, in case one of
174 # them was an asyncgen finalizer that snuck in under the wire.
175 runner.entry_queue.run_sync_soon(runner.reschedule, runner.init_task)
176 await _core.wait_task_rescheduled(
177 lambda _: _core.Abort.FAILED, # pragma: no cover
178 )
179 self.alive.update(self.trailing_needs_finalize)
180 self.trailing_needs_finalize.clear()
181
182 # None of the still-living tasks use async generators, so
183 # every async generator must be suspended at a yield point --
184 # there's no one to be doing the iteration. That's good,
185 # because aclose() only works on an asyncgen that's suspended
186 # at a yield point. (If it's suspended at an event loop trap,
187 # because someone is in the middle of iterating it, then you
188 # get a RuntimeError on 3.8+, and a nasty surprise on earlier
189 # versions due to https://bugs.python.org/issue32526.)
190 #
191 # However, once we start aclose() of one async generator, it
192 # might start fetching the next value from another, thus
193 # preventing us from closing that other (at least until
194 # aclose() of the first one is complete). This constraint
195 # effectively requires us to finalize the remaining asyncgens
196 # in arbitrary order, rather than doing all of them at the
197 # same time. On 3.8+ we could defer any generator with
198 # ag_running=True to a later batch, but that only catches
199 # the case where our aclose() starts after the user's
200 # asend()/etc. If our aclose() starts first, then the
201 # user's asend()/etc will raise RuntimeError, since they're
202 # probably not checking ag_running.
203 #
204 # It might be possible to allow some parallelized cleanup if
205 # we can determine that a certain set of asyncgens have no
206 # interdependencies, using gc.get_referents() and such.
207 # But just doing one at a time will typically work well enough
208 # (since each aclose() executes in a cancelled scope) and
209 # is much easier to reason about.
210
211 # It's possible that that cleanup code will itself create
212 # more async generators, so we iterate repeatedly until
213 # all are gone.
214 while self.alive:
215 batch = self.alive
216 self.alive = _ASYNC_GEN_SET()
217 for agen in batch:
218 await self._finalize_one(agen, name_asyncgen(agen))
219
220 def close(self) -> None:
221 sys.set_asyncgen_hooks(*self.prev_hooks)
222
223 async def _finalize_one(
224 self,
225 agen: AsyncGeneratorType[object, NoReturn],
226 name: object,
227 ) -> None:
228 try:
229 # This shield ensures that finalize_asyncgen never exits
230 # with an exception, not even a Cancelled. The inside
231 # is cancelled so there's no deadlock risk.
232 with _core.CancelScope(shield=True) as cancel_scope:
233 cancel_scope.cancel(
234 reason="disallow async work when closing async generators during trio shutdown"
235 )
236 await agen.aclose()
237 except BaseException:
238 ASYNCGEN_LOGGER.exception(
239 "Exception ignored during finalization of async generator %r -- "
240 "surround your use of the generator in 'async with aclosing(...):' "
241 "to raise exceptions like this in the context where they're generated",
242 name,
243 )