relay-runtime 0.2.0__tar.gz → 0.3.0__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.
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/PKG-INFO +165 -1
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/README.md +164 -0
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/pyproject.toml +1 -1
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/__init__.py +1 -1
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/__init__.py +7 -1
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/_cleanup.py +79 -7
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/_execution.py +14 -1
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/_graph.py +100 -13
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/_handler.py +15 -2
- relay_runtime-0.3.0/src/relay_runtime/dependencies/_override.py +254 -0
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/_state.py +107 -20
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/LICENSE +0 -0
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/dependencies/_model.py +0 -0
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/py.typed +0 -0
- {relay_runtime-0.2.0 → relay_runtime-0.3.0}/src/relay_runtime/typing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: relay-runtime
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Official Python library and public handler interfaces for Relay applications.
|
|
5
5
|
Keywords: relay,application-development,handlers
|
|
6
6
|
Author: Relay Contributors
|
|
@@ -245,6 +245,170 @@ resource is attempted. Container-scoped dependencies use the same normal
|
|
|
245
245
|
teardown and close when Relay's long-lived event loop exits, without replaying
|
|
246
246
|
an older invocation's error.
|
|
247
247
|
|
|
248
|
+
### Overriding dependencies
|
|
249
|
+
|
|
250
|
+
`relay_runtime.dependencies.override_dependencies` temporarily replaces
|
|
251
|
+
providers for the current context. It is available only from the
|
|
252
|
+
`relay_runtime.dependencies` module; the top-level `relay_runtime` package does
|
|
253
|
+
not export it.
|
|
254
|
+
|
|
255
|
+
A test can replace the production email provider with a fake and call the bound
|
|
256
|
+
handler inside the context:
|
|
257
|
+
|
|
258
|
+
```python
|
|
259
|
+
import asyncio
|
|
260
|
+
from typing import Protocol
|
|
261
|
+
|
|
262
|
+
from relay_runtime import Depends, bind
|
|
263
|
+
from relay_runtime.dependencies import override_dependencies
|
|
264
|
+
from relay_runtime.typing import HandlerContext
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class EmailSender(Protocol):
|
|
268
|
+
def send(self, address: str, subject: str) -> None: ...
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def get_email_sender() -> EmailSender:
|
|
272
|
+
... # return the production SES-backed sender
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@bind
|
|
276
|
+
async def handler(
|
|
277
|
+
event: dict[str, object],
|
|
278
|
+
context: HandlerContext,
|
|
279
|
+
email: EmailSender = Depends(get_email_sender),
|
|
280
|
+
) -> None:
|
|
281
|
+
email.send(str(event["address"]), "Welcome")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class FakeEmailSender:
|
|
285
|
+
def __init__(self) -> None:
|
|
286
|
+
self.sent: list[tuple[str, str]] = []
|
|
287
|
+
|
|
288
|
+
def send(self, address: str, subject: str) -> None:
|
|
289
|
+
self.sent.append((address, subject))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def test_handler_sends_welcome_email(context: HandlerContext) -> None:
|
|
293
|
+
fake = FakeEmailSender()
|
|
294
|
+
with override_dependencies({get_email_sender: lambda: fake}):
|
|
295
|
+
asyncio.run(handler({"address": "user@example.com"}, context))
|
|
296
|
+
assert fake.sent == [("user@example.com", "Welcome")]
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
`context` is the invocation context Relay supplies; a unit test can pass a stub
|
|
300
|
+
that implements `HandlerContext`.
|
|
301
|
+
|
|
302
|
+
Keys are matched by provider identity, not equality. The mapping is snapshotted
|
|
303
|
+
and validated when the context is entered; later changes to the mapping object
|
|
304
|
+
do not affect an active context. Mapping a provider to itself is a no-op.
|
|
305
|
+
For parametrized provider factories, use the same cached provider object in the
|
|
306
|
+
handler declaration and override mapping; for example, cache `get_table("users")`
|
|
307
|
+
with `functools.cache` if it is constructed at both sites.
|
|
308
|
+
Nested contexts compose: an inner context inherits the outer overrides and its
|
|
309
|
+
entries take precedence. Leaving the inner context restores the outer mapping.
|
|
310
|
+
|
|
311
|
+
Overrides apply only where a `Depends(...)` declaration references the original
|
|
312
|
+
provider. The replacement inherits that declaration's `scope` and `use_cache`.
|
|
313
|
+
The replacement's own dependencies are resolved with the same overrides, but
|
|
314
|
+
the replacement root is not replaced again. An override chain is therefore not
|
|
315
|
+
followed recursively, and a replacement that depends on the provider it replaces
|
|
316
|
+
is reported as a dependency cycle. Container and invocation caches are keyed by
|
|
317
|
+
the original declaration, so two different originals mapped to one replacement
|
|
318
|
+
remain separate cache entries and own separate resource instances. The effective
|
|
319
|
+
graph is compiled lazily the first time a bound handler runs under the context;
|
|
320
|
+
replacement signatures, cycles, and scope rules are validated then.
|
|
321
|
+
|
|
322
|
+
Each active context owns an isolated container cache. Container-scoped values
|
|
323
|
+
created inside the context are not shared with the global warm container or with
|
|
324
|
+
another context, and their managed resources are closed when that context exits.
|
|
325
|
+
Nested contexts each own their own cache; an inner context does not see the
|
|
326
|
+
outer context's container values, and leaving the inner context closes only the
|
|
327
|
+
resources it created.
|
|
328
|
+
|
|
329
|
+
Use `with` for synchronous code and `async with` when container-scoped async
|
|
330
|
+
generator providers may be involved:
|
|
331
|
+
|
|
332
|
+
- `with` closes synchronous generator container resources without starting an
|
|
333
|
+
event loop. A container-scoped async generator is rejected before it is
|
|
334
|
+
started, including when another callable returns it indirectly; the error
|
|
335
|
+
asks for `async with`.
|
|
336
|
+
- `async with` closes both synchronous and asynchronous container resources.
|
|
337
|
+
- Invocation-scoped resources are always cleaned up inside the handler call, so
|
|
338
|
+
either form works for them.
|
|
339
|
+
|
|
340
|
+
Container-scoped async generator replacements require `async with` so their
|
|
341
|
+
cleanup path can run:
|
|
342
|
+
|
|
343
|
+
```python
|
|
344
|
+
from collections.abc import AsyncIterator
|
|
345
|
+
|
|
346
|
+
from relay_runtime import Depends, bind
|
|
347
|
+
from relay_runtime.dependencies import override_dependencies
|
|
348
|
+
from relay_runtime.typing import HandlerContext
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class Bucket:
|
|
352
|
+
async def put(self, key: str, body: bytes) -> None: ...
|
|
353
|
+
async def close(self) -> None: ...
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
async def get_bucket() -> AsyncIterator[Bucket]:
|
|
357
|
+
bucket = Bucket()
|
|
358
|
+
try:
|
|
359
|
+
yield bucket
|
|
360
|
+
finally:
|
|
361
|
+
await bucket.close()
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
@bind
|
|
365
|
+
async def upload(
|
|
366
|
+
event: dict[str, object],
|
|
367
|
+
context: HandlerContext,
|
|
368
|
+
bucket: Bucket = Depends(get_bucket, scope="container"),
|
|
369
|
+
) -> None:
|
|
370
|
+
await bucket.put(str(event["key"]), b"...")
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
async def get_fake_bucket() -> AsyncIterator[Bucket]:
|
|
374
|
+
bucket = Bucket()
|
|
375
|
+
try:
|
|
376
|
+
yield bucket
|
|
377
|
+
finally:
|
|
378
|
+
await bucket.close()
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
async def test_upload_uses_fake_bucket(context: HandlerContext) -> None:
|
|
382
|
+
async with override_dependencies({get_bucket: get_fake_bucket}):
|
|
383
|
+
await upload({"key": "report.csv"}, context)
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
`get_fake_bucket` is a container-scoped async generator, so its resource is
|
|
387
|
+
started and closed by `async with`. A synchronous `with` rejects that
|
|
388
|
+
replacement before the generator starts and reports that `async with` is
|
|
389
|
+
required.
|
|
390
|
+
|
|
391
|
+
If cleanup fails on exit, the error is raised when no other exception is active;
|
|
392
|
+
the context variable is restored first. If an exception is already propagating,
|
|
393
|
+
cleanup failures are logged and the original exception is preserved.
|
|
394
|
+
Invocation-scoped resources are cleaned up inside the handler on success,
|
|
395
|
+
failure, and cancellation; container-scoped resources are cleaned up when their
|
|
396
|
+
owning override context exits.
|
|
397
|
+
|
|
398
|
+
The active context is stored in a `contextvars.ContextVar`. It is visible in the
|
|
399
|
+
task that entered the context and in child tasks created while it is active.
|
|
400
|
+
Contexts are independent across tasks. A child task that outlives the context
|
|
401
|
+
and tries to resolve a dependency after the owner exits fails instead of using
|
|
402
|
+
the closed container. That inherited task context also cannot enter a new
|
|
403
|
+
override context after its parent has exited; create longer-lived tasks outside
|
|
404
|
+
the override context. Enter and exit the context in the same task; do not move a
|
|
405
|
+
context manager object to another task or thread.
|
|
406
|
+
|
|
407
|
+
Overrides affect only dependency resolution performed by `@bind` and
|
|
408
|
+
`Depends(...)`. They do not monkeypatch providers, change direct calls to a
|
|
409
|
+
provider, or alter container values that were resolved outside dependency
|
|
410
|
+
injection. Relay's at-least-once delivery contract is unchanged.
|
|
411
|
+
|
|
248
412
|
### Integration example
|
|
249
413
|
|
|
250
414
|
The following app uses `pymongo` and `httpx` as application dependencies; they
|
|
@@ -232,6 +232,170 @@ resource is attempted. Container-scoped dependencies use the same normal
|
|
|
232
232
|
teardown and close when Relay's long-lived event loop exits, without replaying
|
|
233
233
|
an older invocation's error.
|
|
234
234
|
|
|
235
|
+
### Overriding dependencies
|
|
236
|
+
|
|
237
|
+
`relay_runtime.dependencies.override_dependencies` temporarily replaces
|
|
238
|
+
providers for the current context. It is available only from the
|
|
239
|
+
`relay_runtime.dependencies` module; the top-level `relay_runtime` package does
|
|
240
|
+
not export it.
|
|
241
|
+
|
|
242
|
+
A test can replace the production email provider with a fake and call the bound
|
|
243
|
+
handler inside the context:
|
|
244
|
+
|
|
245
|
+
```python
|
|
246
|
+
import asyncio
|
|
247
|
+
from typing import Protocol
|
|
248
|
+
|
|
249
|
+
from relay_runtime import Depends, bind
|
|
250
|
+
from relay_runtime.dependencies import override_dependencies
|
|
251
|
+
from relay_runtime.typing import HandlerContext
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class EmailSender(Protocol):
|
|
255
|
+
def send(self, address: str, subject: str) -> None: ...
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def get_email_sender() -> EmailSender:
|
|
259
|
+
... # return the production SES-backed sender
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@bind
|
|
263
|
+
async def handler(
|
|
264
|
+
event: dict[str, object],
|
|
265
|
+
context: HandlerContext,
|
|
266
|
+
email: EmailSender = Depends(get_email_sender),
|
|
267
|
+
) -> None:
|
|
268
|
+
email.send(str(event["address"]), "Welcome")
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class FakeEmailSender:
|
|
272
|
+
def __init__(self) -> None:
|
|
273
|
+
self.sent: list[tuple[str, str]] = []
|
|
274
|
+
|
|
275
|
+
def send(self, address: str, subject: str) -> None:
|
|
276
|
+
self.sent.append((address, subject))
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def test_handler_sends_welcome_email(context: HandlerContext) -> None:
|
|
280
|
+
fake = FakeEmailSender()
|
|
281
|
+
with override_dependencies({get_email_sender: lambda: fake}):
|
|
282
|
+
asyncio.run(handler({"address": "user@example.com"}, context))
|
|
283
|
+
assert fake.sent == [("user@example.com", "Welcome")]
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
`context` is the invocation context Relay supplies; a unit test can pass a stub
|
|
287
|
+
that implements `HandlerContext`.
|
|
288
|
+
|
|
289
|
+
Keys are matched by provider identity, not equality. The mapping is snapshotted
|
|
290
|
+
and validated when the context is entered; later changes to the mapping object
|
|
291
|
+
do not affect an active context. Mapping a provider to itself is a no-op.
|
|
292
|
+
For parametrized provider factories, use the same cached provider object in the
|
|
293
|
+
handler declaration and override mapping; for example, cache `get_table("users")`
|
|
294
|
+
with `functools.cache` if it is constructed at both sites.
|
|
295
|
+
Nested contexts compose: an inner context inherits the outer overrides and its
|
|
296
|
+
entries take precedence. Leaving the inner context restores the outer mapping.
|
|
297
|
+
|
|
298
|
+
Overrides apply only where a `Depends(...)` declaration references the original
|
|
299
|
+
provider. The replacement inherits that declaration's `scope` and `use_cache`.
|
|
300
|
+
The replacement's own dependencies are resolved with the same overrides, but
|
|
301
|
+
the replacement root is not replaced again. An override chain is therefore not
|
|
302
|
+
followed recursively, and a replacement that depends on the provider it replaces
|
|
303
|
+
is reported as a dependency cycle. Container and invocation caches are keyed by
|
|
304
|
+
the original declaration, so two different originals mapped to one replacement
|
|
305
|
+
remain separate cache entries and own separate resource instances. The effective
|
|
306
|
+
graph is compiled lazily the first time a bound handler runs under the context;
|
|
307
|
+
replacement signatures, cycles, and scope rules are validated then.
|
|
308
|
+
|
|
309
|
+
Each active context owns an isolated container cache. Container-scoped values
|
|
310
|
+
created inside the context are not shared with the global warm container or with
|
|
311
|
+
another context, and their managed resources are closed when that context exits.
|
|
312
|
+
Nested contexts each own their own cache; an inner context does not see the
|
|
313
|
+
outer context's container values, and leaving the inner context closes only the
|
|
314
|
+
resources it created.
|
|
315
|
+
|
|
316
|
+
Use `with` for synchronous code and `async with` when container-scoped async
|
|
317
|
+
generator providers may be involved:
|
|
318
|
+
|
|
319
|
+
- `with` closes synchronous generator container resources without starting an
|
|
320
|
+
event loop. A container-scoped async generator is rejected before it is
|
|
321
|
+
started, including when another callable returns it indirectly; the error
|
|
322
|
+
asks for `async with`.
|
|
323
|
+
- `async with` closes both synchronous and asynchronous container resources.
|
|
324
|
+
- Invocation-scoped resources are always cleaned up inside the handler call, so
|
|
325
|
+
either form works for them.
|
|
326
|
+
|
|
327
|
+
Container-scoped async generator replacements require `async with` so their
|
|
328
|
+
cleanup path can run:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
from collections.abc import AsyncIterator
|
|
332
|
+
|
|
333
|
+
from relay_runtime import Depends, bind
|
|
334
|
+
from relay_runtime.dependencies import override_dependencies
|
|
335
|
+
from relay_runtime.typing import HandlerContext
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
class Bucket:
|
|
339
|
+
async def put(self, key: str, body: bytes) -> None: ...
|
|
340
|
+
async def close(self) -> None: ...
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
async def get_bucket() -> AsyncIterator[Bucket]:
|
|
344
|
+
bucket = Bucket()
|
|
345
|
+
try:
|
|
346
|
+
yield bucket
|
|
347
|
+
finally:
|
|
348
|
+
await bucket.close()
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
@bind
|
|
352
|
+
async def upload(
|
|
353
|
+
event: dict[str, object],
|
|
354
|
+
context: HandlerContext,
|
|
355
|
+
bucket: Bucket = Depends(get_bucket, scope="container"),
|
|
356
|
+
) -> None:
|
|
357
|
+
await bucket.put(str(event["key"]), b"...")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
async def get_fake_bucket() -> AsyncIterator[Bucket]:
|
|
361
|
+
bucket = Bucket()
|
|
362
|
+
try:
|
|
363
|
+
yield bucket
|
|
364
|
+
finally:
|
|
365
|
+
await bucket.close()
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
async def test_upload_uses_fake_bucket(context: HandlerContext) -> None:
|
|
369
|
+
async with override_dependencies({get_bucket: get_fake_bucket}):
|
|
370
|
+
await upload({"key": "report.csv"}, context)
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
`get_fake_bucket` is a container-scoped async generator, so its resource is
|
|
374
|
+
started and closed by `async with`. A synchronous `with` rejects that
|
|
375
|
+
replacement before the generator starts and reports that `async with` is
|
|
376
|
+
required.
|
|
377
|
+
|
|
378
|
+
If cleanup fails on exit, the error is raised when no other exception is active;
|
|
379
|
+
the context variable is restored first. If an exception is already propagating,
|
|
380
|
+
cleanup failures are logged and the original exception is preserved.
|
|
381
|
+
Invocation-scoped resources are cleaned up inside the handler on success,
|
|
382
|
+
failure, and cancellation; container-scoped resources are cleaned up when their
|
|
383
|
+
owning override context exits.
|
|
384
|
+
|
|
385
|
+
The active context is stored in a `contextvars.ContextVar`. It is visible in the
|
|
386
|
+
task that entered the context and in child tasks created while it is active.
|
|
387
|
+
Contexts are independent across tasks. A child task that outlives the context
|
|
388
|
+
and tries to resolve a dependency after the owner exits fails instead of using
|
|
389
|
+
the closed container. That inherited task context also cannot enter a new
|
|
390
|
+
override context after its parent has exited; create longer-lived tasks outside
|
|
391
|
+
the override context. Enter and exit the context in the same task; do not move a
|
|
392
|
+
context manager object to another task or thread.
|
|
393
|
+
|
|
394
|
+
Overrides affect only dependency resolution performed by `@bind` and
|
|
395
|
+
`Depends(...)`. They do not monkeypatch providers, change direct calls to a
|
|
396
|
+
provider, or alter container values that were resolved outside dependency
|
|
397
|
+
injection. Relay's at-least-once delivery contract is unchanged.
|
|
398
|
+
|
|
235
399
|
### Integration example
|
|
236
400
|
|
|
237
401
|
The following app uses `pymongo` and `httpx` as application dependencies; they
|
|
@@ -31,15 +31,21 @@ generator. Generator providers yield exactly one value; the remainder of the
|
|
|
31
31
|
generator is the cleanup path and runs when the scope ends. Cleanups run in
|
|
32
32
|
reverse creation order and are attempted even when the handler fails or is
|
|
33
33
|
cancelled.
|
|
34
|
+
|
|
35
|
+
:func:`override_dependencies` temporarily replaces providers for the current
|
|
36
|
+
context. Each active context owns an isolated container cache and resource
|
|
37
|
+
lifecycle; overrides never mutate the compiled handler graph or the global
|
|
38
|
+
container state.
|
|
34
39
|
"""
|
|
35
40
|
|
|
36
41
|
from __future__ import annotations
|
|
37
42
|
|
|
38
43
|
from ._handler import bind
|
|
39
44
|
from ._model import Depends
|
|
45
|
+
from ._override import override_dependencies
|
|
40
46
|
from ._state import CONTAINER_STATE
|
|
41
47
|
|
|
42
|
-
__all__ = ["Depends", "bind"]
|
|
48
|
+
__all__ = ["Depends", "bind", "override_dependencies"]
|
|
43
49
|
|
|
44
50
|
|
|
45
51
|
async def _shutdown_container_dependencies() -> list[BaseException]:
|
|
@@ -167,15 +167,12 @@ def _cleanup_failure(name: str, exc: BaseException) -> BaseException:
|
|
|
167
167
|
|
|
168
168
|
|
|
169
169
|
def _yielded_after_failure(name: str) -> BaseException:
|
|
170
|
-
return _DependencyError(
|
|
171
|
-
f"dependency {name!r} yielded after an invocation failure"
|
|
172
|
-
)
|
|
170
|
+
return _DependencyError(f"dependency {name!r} yielded after an invocation failure")
|
|
173
171
|
|
|
174
172
|
|
|
175
173
|
def _exactly_one_yield_failure(name: str) -> BaseException:
|
|
176
174
|
return _DependencyError(
|
|
177
|
-
f"dependency {name!r} must yield exactly once; "
|
|
178
|
-
"it yielded again during cleanup"
|
|
175
|
+
f"dependency {name!r} must yield exactly once; it yielded again during cleanup"
|
|
179
176
|
)
|
|
180
177
|
|
|
181
178
|
|
|
@@ -203,7 +200,7 @@ async def _finalize_successfully(
|
|
|
203
200
|
# yield, not GeneratorExit from close(). Resume it and require termination.
|
|
204
201
|
try:
|
|
205
202
|
result = finalizer.resume()
|
|
206
|
-
except
|
|
203
|
+
except StopIteration, StopAsyncIteration:
|
|
207
204
|
return [], False
|
|
208
205
|
except BaseException as exc:
|
|
209
206
|
return [_cleanup_failure(finalizer.name, exc)], False
|
|
@@ -233,7 +230,7 @@ async def _throw_finalizer(
|
|
|
233
230
|
) -> tuple[list[BaseException], bool]:
|
|
234
231
|
try:
|
|
235
232
|
result = finalizer.throw(active)
|
|
236
|
-
except
|
|
233
|
+
except StopIteration, StopAsyncIteration:
|
|
237
234
|
return [], False
|
|
238
235
|
except BaseException as exc:
|
|
239
236
|
if exc is active:
|
|
@@ -290,6 +287,81 @@ async def _run_cleanups(
|
|
|
290
287
|
return errors, cancelled
|
|
291
288
|
|
|
292
289
|
|
|
290
|
+
def _force_close_sync(
|
|
291
|
+
finalizer: _SyncGeneratorFinalizer,
|
|
292
|
+
) -> list[BaseException]:
|
|
293
|
+
try:
|
|
294
|
+
finalizer.close()
|
|
295
|
+
except BaseException as exc:
|
|
296
|
+
return [_cleanup_failure(finalizer.name, exc)]
|
|
297
|
+
return []
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _finalize_successfully_sync(
|
|
301
|
+
finalizer: _SyncGeneratorFinalizer,
|
|
302
|
+
) -> list[BaseException]:
|
|
303
|
+
try:
|
|
304
|
+
finalizer.resume()
|
|
305
|
+
except StopIteration, StopAsyncIteration:
|
|
306
|
+
return []
|
|
307
|
+
except BaseException as exc:
|
|
308
|
+
return [_cleanup_failure(finalizer.name, exc)]
|
|
309
|
+
|
|
310
|
+
close_errors = _force_close_sync(finalizer)
|
|
311
|
+
return [_exactly_one_yield_failure(finalizer.name), *close_errors]
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _throw_finalizer_sync(
|
|
315
|
+
finalizer: _SyncGeneratorFinalizer, active: BaseException
|
|
316
|
+
) -> list[BaseException]:
|
|
317
|
+
try:
|
|
318
|
+
finalizer.throw(active)
|
|
319
|
+
except StopIteration, StopAsyncIteration:
|
|
320
|
+
return []
|
|
321
|
+
except BaseException as exc:
|
|
322
|
+
if exc is active:
|
|
323
|
+
return []
|
|
324
|
+
return [_cleanup_failure(finalizer.name, exc)]
|
|
325
|
+
|
|
326
|
+
close_errors = _force_close_sync(finalizer)
|
|
327
|
+
return [_yielded_after_failure(finalizer.name), *close_errors]
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _run_sync_cleanups(
|
|
331
|
+
finalizers: list[_Finalizer],
|
|
332
|
+
active_exception: BaseException | None = None,
|
|
333
|
+
) -> list[BaseException]:
|
|
334
|
+
"""Close finalizers without creating or requiring an event loop.
|
|
335
|
+
|
|
336
|
+
Only synchronous generator providers can be finalized this way. An
|
|
337
|
+
asynchronous generator is reported instead of being closed on a hidden
|
|
338
|
+
loop.
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
errors: list[BaseException] = []
|
|
342
|
+
for finalizer in reversed(finalizers):
|
|
343
|
+
if not isinstance(finalizer, _SyncGeneratorFinalizer):
|
|
344
|
+
errors.append(
|
|
345
|
+
_DependencyError(
|
|
346
|
+
f"dependency {finalizer.name!r} requires asynchronous "
|
|
347
|
+
"cleanup; use 'async with override_dependencies(...)'"
|
|
348
|
+
)
|
|
349
|
+
)
|
|
350
|
+
continue
|
|
351
|
+
|
|
352
|
+
try:
|
|
353
|
+
if active_exception is None:
|
|
354
|
+
found = _finalize_successfully_sync(finalizer)
|
|
355
|
+
else:
|
|
356
|
+
found = _throw_finalizer_sync(finalizer, active_exception)
|
|
357
|
+
except BaseException as exc:
|
|
358
|
+
found = [_cleanup_failure(finalizer.name, exc)]
|
|
359
|
+
|
|
360
|
+
errors.extend(found)
|
|
361
|
+
|
|
362
|
+
return errors
|
|
363
|
+
|
|
364
|
+
|
|
293
365
|
class _FinalizerStack:
|
|
294
366
|
"""Invocation-owned LIFO stack of started generator providers."""
|
|
295
367
|
|
|
@@ -65,7 +65,12 @@ async def call(plan: _CallablePlan, state: _Resolver) -> _CallOutcome:
|
|
|
65
65
|
return _CallOutcome(result, False)
|
|
66
66
|
|
|
67
67
|
|
|
68
|
-
async def produce(
|
|
68
|
+
async def produce(
|
|
69
|
+
node: _CompiledNode,
|
|
70
|
+
state: _Resolver,
|
|
71
|
+
*,
|
|
72
|
+
reject_async_generator: bool = False,
|
|
73
|
+
) -> _Produced:
|
|
69
74
|
try:
|
|
70
75
|
outcome = await call(node.plan, state)
|
|
71
76
|
except BaseException as exc:
|
|
@@ -75,6 +80,14 @@ async def produce(node: _CompiledNode, state: _Resolver) -> _Produced:
|
|
|
75
80
|
result = outcome.value
|
|
76
81
|
try:
|
|
77
82
|
if inspect.isasyncgen(result):
|
|
83
|
+
if reject_async_generator:
|
|
84
|
+
await result.aclose()
|
|
85
|
+
raise _DependencyError(
|
|
86
|
+
f"dependency {node.plan.name!r} produced an async "
|
|
87
|
+
"generator; a synchronous override_dependencies context "
|
|
88
|
+
"cannot start or clean it up. Use 'async with "
|
|
89
|
+
"override_dependencies(...)'."
|
|
90
|
+
)
|
|
78
91
|
value, finalizer = await start_async_generator(node.name, result)
|
|
79
92
|
return _Produced(value, finalizer, True)
|
|
80
93
|
if inspect.isgenerator(result):
|
|
@@ -2,21 +2,80 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import enum
|
|
5
6
|
import inspect
|
|
6
7
|
from dataclasses import dataclass, field
|
|
7
|
-
from typing import Any, ForwardRef, get_type_hints
|
|
8
|
+
from typing import Any, ForwardRef, Protocol, get_type_hints
|
|
8
9
|
|
|
9
10
|
from ._model import (
|
|
10
11
|
_RESERVED_PARAMETERS,
|
|
12
|
+
_callable_name,
|
|
11
13
|
_DependencyError,
|
|
12
14
|
_Depends,
|
|
13
15
|
_Injection,
|
|
14
16
|
_ProviderCallable,
|
|
15
17
|
_Scope,
|
|
16
|
-
_callable_name,
|
|
17
18
|
)
|
|
18
19
|
|
|
19
20
|
|
|
21
|
+
class _CleanupKind(enum.Enum):
|
|
22
|
+
"""How a provider's value must be torn down."""
|
|
23
|
+
|
|
24
|
+
NONE = "none"
|
|
25
|
+
SYNC = "sync"
|
|
26
|
+
ASYNC = "async"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _cleanup_kind(func: _ProviderCallable) -> _CleanupKind:
|
|
30
|
+
targets: list[Any] = [func]
|
|
31
|
+
partial_target = getattr(func, "func", None)
|
|
32
|
+
if callable(partial_target):
|
|
33
|
+
targets.append(partial_target)
|
|
34
|
+
|
|
35
|
+
call = getattr(func, "__call__", None)
|
|
36
|
+
if call is not None:
|
|
37
|
+
targets.append(call)
|
|
38
|
+
|
|
39
|
+
for candidate in targets:
|
|
40
|
+
try:
|
|
41
|
+
target = inspect.unwrap(candidate)
|
|
42
|
+
except ValueError:
|
|
43
|
+
target = candidate
|
|
44
|
+
|
|
45
|
+
if inspect.isasyncgenfunction(target):
|
|
46
|
+
return _CleanupKind.ASYNC
|
|
47
|
+
if inspect.isgeneratorfunction(target):
|
|
48
|
+
return _CleanupKind.SYNC
|
|
49
|
+
return _CleanupKind.NONE
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _OverrideLookup(Protocol):
|
|
53
|
+
"""Resolve an effective provider for one original declaration."""
|
|
54
|
+
|
|
55
|
+
def replacement_for(
|
|
56
|
+
self, provider: _ProviderCallable
|
|
57
|
+
) -> _ProviderCallable | None: ...
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class _ReplacementFailure(_DependencyError):
|
|
61
|
+
"""A provider could not be compiled after an override substitution."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _replacement_failure(
|
|
65
|
+
original: _ProviderCallable,
|
|
66
|
+
replacement: _ProviderCallable,
|
|
67
|
+
path: str,
|
|
68
|
+
cause: _DependencyError,
|
|
69
|
+
) -> _ReplacementFailure:
|
|
70
|
+
"""Add override context to a replacement compilation failure."""
|
|
71
|
+
|
|
72
|
+
return _ReplacementFailure(
|
|
73
|
+
f"dependency {_callable_name(original)!r} is overridden by "
|
|
74
|
+
f"{_callable_name(replacement)!r}; compiling the replacement "
|
|
75
|
+
f"failed: {cause} (effective dependency path: {path})"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
20
79
|
@dataclass(frozen=True)
|
|
21
80
|
class _Parameter:
|
|
22
81
|
"""One argument to supply when the compiled callable is invoked."""
|
|
@@ -50,6 +109,7 @@ class _CompiledNode:
|
|
|
50
109
|
scope: _Scope
|
|
51
110
|
use_cache: bool
|
|
52
111
|
plan: _CallablePlan = field(repr=False)
|
|
112
|
+
cleanup: _CleanupKind = _CleanupKind.NONE
|
|
53
113
|
|
|
54
114
|
|
|
55
115
|
def _annotation_depends(
|
|
@@ -118,9 +178,16 @@ def _resolved_annotations(
|
|
|
118
178
|
|
|
119
179
|
|
|
120
180
|
class _GraphCompiler:
|
|
121
|
-
"""Compile one handler's graph, reusing each provider by declaration.
|
|
181
|
+
"""Compile one handler's graph, reusing each provider by declaration.
|
|
182
|
+
|
|
183
|
+
An optional override lookup substitutes a provider at each original
|
|
184
|
+
``Depends(...)`` reference. The original callable remains the node's
|
|
185
|
+
identity and cache key; the replacement only supplies the plan and the
|
|
186
|
+
cleanup kind.
|
|
187
|
+
"""
|
|
122
188
|
|
|
123
|
-
def __init__(self) -> None:
|
|
189
|
+
def __init__(self, overrides: _OverrideLookup | None = None) -> None:
|
|
190
|
+
self._overrides = overrides
|
|
124
191
|
self._completed: dict[tuple[int, _Scope, bool], _CompiledNode] = {}
|
|
125
192
|
self._active: list[tuple[tuple[int, _Scope, bool], str]] = []
|
|
126
193
|
|
|
@@ -142,19 +209,38 @@ class _GraphCompiler:
|
|
|
142
209
|
return existing
|
|
143
210
|
|
|
144
211
|
name = _callable_name(dependency)
|
|
212
|
+
replacement: _ProviderCallable | None = None
|
|
213
|
+
if self._overrides is not None:
|
|
214
|
+
replacement = self._overrides.replacement_for(dependency)
|
|
215
|
+
if replacement is dependency:
|
|
216
|
+
replacement = None
|
|
217
|
+
provider = dependency if replacement is None else replacement
|
|
218
|
+
provider_name = _callable_name(provider)
|
|
219
|
+
active_name = (
|
|
220
|
+
name if replacement is None else f"{name} (overridden by {provider_name})"
|
|
221
|
+
)
|
|
222
|
+
|
|
145
223
|
if any(active_key == key for active_key, _ in self._active):
|
|
146
|
-
path = " -> ".join(
|
|
224
|
+
path = " -> ".join(
|
|
225
|
+
[active_name for _, active_name in self._active] + [name]
|
|
226
|
+
)
|
|
147
227
|
raise _DependencyError(f"dependency cycle detected: {path}")
|
|
148
228
|
|
|
149
|
-
self._active.append((key,
|
|
229
|
+
self._active.append((key, active_name))
|
|
150
230
|
try:
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
231
|
+
try:
|
|
232
|
+
plan = self._plan_callable(
|
|
233
|
+
provider,
|
|
234
|
+
provider_name,
|
|
235
|
+
scope,
|
|
236
|
+
reserved_allowed=scope is _Scope.INVOCATION,
|
|
237
|
+
is_handler=False,
|
|
238
|
+
)
|
|
239
|
+
except _DependencyError as exc:
|
|
240
|
+
if replacement is None or isinstance(exc, _ReplacementFailure):
|
|
241
|
+
raise
|
|
242
|
+
path = " -> ".join(active for _, active in self._active)
|
|
243
|
+
raise _replacement_failure(dependency, replacement, path, exc) from exc
|
|
158
244
|
finally:
|
|
159
245
|
self._active.pop()
|
|
160
246
|
|
|
@@ -164,6 +250,7 @@ class _GraphCompiler:
|
|
|
164
250
|
scope=scope,
|
|
165
251
|
use_cache=use_cache,
|
|
166
252
|
plan=plan,
|
|
253
|
+
cleanup=_cleanup_kind(provider),
|
|
167
254
|
)
|
|
168
255
|
self._completed[key] = node
|
|
169
256
|
return node
|
|
@@ -14,6 +14,7 @@ from relay_runtime.typing import HandlerContext
|
|
|
14
14
|
from ._execution import call
|
|
15
15
|
from ._graph import _CallablePlan, _GraphCompiler
|
|
16
16
|
from ._model import _DependencyError, _ProviderCallable
|
|
17
|
+
from ._override import _current_override
|
|
17
18
|
from ._state import CONTAINER_STATE, InvocationState
|
|
18
19
|
|
|
19
20
|
_R = TypeVar("_R")
|
|
@@ -105,9 +106,21 @@ class _HandlerGraph:
|
|
|
105
106
|
self._plan: _CallablePlan = _GraphCompiler().compile_handler(handler)
|
|
106
107
|
|
|
107
108
|
async def invoke(self, event: Any, context: HandlerContext) -> Any:
|
|
108
|
-
|
|
109
|
+
scope = _current_override()
|
|
110
|
+
if scope is None:
|
|
111
|
+
plan = self._plan
|
|
112
|
+
state = InvocationState(event, context, CONTAINER_STATE)
|
|
113
|
+
else:
|
|
114
|
+
plan = scope.plan_for(self._plan)
|
|
115
|
+
state = InvocationState(
|
|
116
|
+
event,
|
|
117
|
+
context,
|
|
118
|
+
scope.container,
|
|
119
|
+
is_closed=lambda: scope.closed,
|
|
120
|
+
)
|
|
121
|
+
|
|
109
122
|
try:
|
|
110
|
-
outcome = await call(
|
|
123
|
+
outcome = await call(plan, state)
|
|
111
124
|
except BaseException as exc:
|
|
112
125
|
errors, cancelled = await state.close(exc)
|
|
113
126
|
for error in errors:
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Context-scoped dependency overrides.
|
|
2
|
+
|
|
3
|
+
Overrides are matched by provider identity and applied only at ``Depends(...)``
|
|
4
|
+
references. Each active context owns an isolated container cache and its
|
|
5
|
+
resources, so entering or leaving a context never mutates the global container
|
|
6
|
+
state or another context's cache.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextvars
|
|
12
|
+
import logging
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
from typing import Literal
|
|
16
|
+
|
|
17
|
+
from ._graph import _CallablePlan, _GraphCompiler
|
|
18
|
+
from ._model import _DependencyError, _ProviderCallable
|
|
19
|
+
from ._state import ContainerState
|
|
20
|
+
|
|
21
|
+
_LOGGER = logging.getLogger("relay_runtime.dependencies")
|
|
22
|
+
|
|
23
|
+
_OverrideTable = dict[int, tuple[_ProviderCallable, _ProviderCallable]]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _OverrideScope:
|
|
27
|
+
"""The effective overrides, container cache, and compiled plans."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, overrides: _OverrideTable, *, sync_only: bool) -> None:
|
|
30
|
+
self._overrides = overrides
|
|
31
|
+
self.closed = False
|
|
32
|
+
self._plans: dict[int, tuple[_CallablePlan, _CallablePlan]] = {}
|
|
33
|
+
self.container = ContainerState(
|
|
34
|
+
reject_async_cleanup=sync_only,
|
|
35
|
+
is_closed=lambda: self.closed,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
def replacement_for(self, provider: _ProviderCallable) -> _ProviderCallable | None:
|
|
39
|
+
entry = self._overrides.get(id(provider))
|
|
40
|
+
if entry is None:
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
original, replacement = entry
|
|
44
|
+
if original is not provider:
|
|
45
|
+
return None
|
|
46
|
+
if replacement is provider:
|
|
47
|
+
return None
|
|
48
|
+
return replacement
|
|
49
|
+
|
|
50
|
+
def plan_for(self, plan: _CallablePlan) -> _CallablePlan:
|
|
51
|
+
self.ensure_open()
|
|
52
|
+
key = id(plan)
|
|
53
|
+
cached = self._plans.get(key)
|
|
54
|
+
if cached is not None and cached[0] is plan:
|
|
55
|
+
return cached[1]
|
|
56
|
+
|
|
57
|
+
compiled = _GraphCompiler(self).compile_handler(plan.func)
|
|
58
|
+
self._plans[key] = (plan, compiled)
|
|
59
|
+
return compiled
|
|
60
|
+
|
|
61
|
+
def ensure_open(self) -> None:
|
|
62
|
+
if self.closed:
|
|
63
|
+
raise _DependencyError(
|
|
64
|
+
"override_dependencies context has exited; dependency "
|
|
65
|
+
"overrides cannot be used after the context manager exits"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def close_sync(self) -> list[BaseException]:
|
|
69
|
+
if self.closed:
|
|
70
|
+
return []
|
|
71
|
+
self.closed = True
|
|
72
|
+
try:
|
|
73
|
+
return self.container.shutdown_sync()
|
|
74
|
+
finally:
|
|
75
|
+
self._plans.clear()
|
|
76
|
+
|
|
77
|
+
async def close_async(self) -> list[BaseException]:
|
|
78
|
+
if self.closed:
|
|
79
|
+
return []
|
|
80
|
+
self.closed = True
|
|
81
|
+
try:
|
|
82
|
+
return await self.container.shutdown()
|
|
83
|
+
finally:
|
|
84
|
+
self._plans.clear()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_ACTIVE_OVERRIDE: contextvars.ContextVar[_OverrideScope | None] = (
|
|
88
|
+
contextvars.ContextVar("relay_runtime_dependency_overrides", default=None)
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _current_override() -> _OverrideScope | None:
|
|
93
|
+
return _ACTIVE_OVERRIDE.get()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _OverrideContext:
|
|
97
|
+
"""A reusable sync/async context manager for dependency overrides."""
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self, overrides: Mapping[_ProviderCallable, _ProviderCallable]
|
|
101
|
+
) -> None:
|
|
102
|
+
self._requested = overrides
|
|
103
|
+
self._scope: _OverrideScope | None = None
|
|
104
|
+
self._token: contextvars.Token[_OverrideScope | None] | None = None
|
|
105
|
+
|
|
106
|
+
def __enter__(self) -> _OverrideContext:
|
|
107
|
+
return self._enter(sync_only=True)
|
|
108
|
+
|
|
109
|
+
def __exit__(
|
|
110
|
+
self,
|
|
111
|
+
exc_type: type[BaseException] | None,
|
|
112
|
+
exc: BaseException | None,
|
|
113
|
+
tb: TracebackType | None,
|
|
114
|
+
) -> Literal[False]:
|
|
115
|
+
scope, token = self._detach()
|
|
116
|
+
try:
|
|
117
|
+
errors = scope.close_sync()
|
|
118
|
+
finally:
|
|
119
|
+
_ACTIVE_OVERRIDE.reset(token)
|
|
120
|
+
self._scope = None
|
|
121
|
+
self._token = None
|
|
122
|
+
_report_cleanup_errors(errors, exc)
|
|
123
|
+
return False
|
|
124
|
+
|
|
125
|
+
async def __aenter__(self) -> _OverrideContext:
|
|
126
|
+
return self._enter(sync_only=False)
|
|
127
|
+
|
|
128
|
+
async def __aexit__(
|
|
129
|
+
self,
|
|
130
|
+
exc_type: type[BaseException] | None,
|
|
131
|
+
exc: BaseException | None,
|
|
132
|
+
tb: TracebackType | None,
|
|
133
|
+
) -> Literal[False]:
|
|
134
|
+
scope, token = self._detach()
|
|
135
|
+
try:
|
|
136
|
+
errors = await scope.close_async()
|
|
137
|
+
finally:
|
|
138
|
+
_ACTIVE_OVERRIDE.reset(token)
|
|
139
|
+
self._scope = None
|
|
140
|
+
self._token = None
|
|
141
|
+
_report_cleanup_errors(errors, exc)
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
def _enter(self, *, sync_only: bool) -> _OverrideContext:
|
|
145
|
+
if self._token is not None:
|
|
146
|
+
raise RuntimeError(
|
|
147
|
+
"override_dependencies context manager is already active"
|
|
148
|
+
)
|
|
149
|
+
if not isinstance(self._requested, Mapping):
|
|
150
|
+
raise TypeError(
|
|
151
|
+
"override_dependencies() expects a mapping of provider callables"
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
inherited = _ACTIVE_OVERRIDE.get()
|
|
155
|
+
if inherited is not None and inherited.closed:
|
|
156
|
+
raise _DependencyError(
|
|
157
|
+
"override_dependencies cannot be entered from a task whose "
|
|
158
|
+
"parent context has already exited"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
requested = _snapshot_overrides(self._requested)
|
|
162
|
+
scope = _OverrideScope(
|
|
163
|
+
_merge_overrides(inherited, requested),
|
|
164
|
+
sync_only=sync_only,
|
|
165
|
+
)
|
|
166
|
+
token = _ACTIVE_OVERRIDE.set(scope)
|
|
167
|
+
self._scope = scope
|
|
168
|
+
self._token = token
|
|
169
|
+
return self
|
|
170
|
+
|
|
171
|
+
def _detach(
|
|
172
|
+
self,
|
|
173
|
+
) -> tuple[_OverrideScope, contextvars.Token[_OverrideScope | None]]:
|
|
174
|
+
scope = self._scope
|
|
175
|
+
token = self._token
|
|
176
|
+
if scope is None or token is None:
|
|
177
|
+
raise RuntimeError("override_dependencies context manager was not entered")
|
|
178
|
+
return scope, token
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _snapshot_overrides(
|
|
182
|
+
overrides: Mapping[_ProviderCallable, _ProviderCallable],
|
|
183
|
+
) -> _OverrideTable:
|
|
184
|
+
table: _OverrideTable = {}
|
|
185
|
+
for original, replacement in overrides.items():
|
|
186
|
+
if not callable(original):
|
|
187
|
+
raise TypeError(
|
|
188
|
+
"override_dependencies() keys must be provider callables, "
|
|
189
|
+
f"got {original!r}"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
if not callable(replacement):
|
|
193
|
+
raise TypeError(
|
|
194
|
+
"override_dependencies() values must be provider callables, "
|
|
195
|
+
f"got {replacement!r}"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
if replacement is original:
|
|
199
|
+
continue
|
|
200
|
+
|
|
201
|
+
table[id(original)] = (original, replacement)
|
|
202
|
+
|
|
203
|
+
return table
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _merge_overrides(
|
|
207
|
+
inherited: _OverrideScope | None, requested: _OverrideTable
|
|
208
|
+
) -> _OverrideTable:
|
|
209
|
+
merged: _OverrideTable = {} if inherited is None else dict(inherited._overrides)
|
|
210
|
+
merged.update(requested)
|
|
211
|
+
return merged
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _report_cleanup_errors(
|
|
215
|
+
errors: list[BaseException], active: BaseException | None
|
|
216
|
+
) -> None:
|
|
217
|
+
if not errors:
|
|
218
|
+
return
|
|
219
|
+
|
|
220
|
+
if active is not None:
|
|
221
|
+
for error in errors:
|
|
222
|
+
_LOGGER.error(
|
|
223
|
+
"override_dependencies cleanup failed after an active error",
|
|
224
|
+
exc_info=(type(error), error, error.__traceback__),
|
|
225
|
+
)
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
for error in errors[1:]:
|
|
229
|
+
_LOGGER.error(
|
|
230
|
+
"additional override_dependencies cleanup failure",
|
|
231
|
+
exc_info=(type(error), error, error.__traceback__),
|
|
232
|
+
)
|
|
233
|
+
raise errors[0]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def override_dependencies(
|
|
237
|
+
overrides: Mapping[_ProviderCallable, _ProviderCallable],
|
|
238
|
+
) -> _OverrideContext:
|
|
239
|
+
"""Override providers for the current context.
|
|
240
|
+
|
|
241
|
+
``overrides`` maps each original provider callable to a replacement
|
|
242
|
+
callable. Keys are matched by identity, the mapping is snapshotted when the
|
|
243
|
+
context is entered, and the replacement inherits the original declaration's
|
|
244
|
+
scope and ``use_cache`` setting. Use the result as either ``with`` or
|
|
245
|
+
``async with``.
|
|
246
|
+
|
|
247
|
+
Only dependencies resolved through ``@bind`` and ``Depends(...)`` are
|
|
248
|
+
affected. The mapping is applied at each original declaration; a
|
|
249
|
+
replacement provider's own dependencies are also resolved under the same
|
|
250
|
+
overrides, but the replacement root is not replaced again. Mapping a
|
|
251
|
+
provider to itself is a no-op.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
return _OverrideContext(overrides)
|
|
@@ -3,16 +3,25 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Callable
|
|
6
8
|
from dataclasses import dataclass
|
|
7
|
-
from typing import Any
|
|
9
|
+
from typing import Any, NoReturn
|
|
8
10
|
|
|
9
11
|
from relay_runtime.typing import HandlerContext
|
|
10
12
|
|
|
11
|
-
from ._cleanup import
|
|
13
|
+
from ._cleanup import (
|
|
14
|
+
_Finalizer,
|
|
15
|
+
_FinalizerStack,
|
|
16
|
+
_run_cleanups,
|
|
17
|
+
_run_sync_cleanups,
|
|
18
|
+
)
|
|
12
19
|
from ._execution import _Resolver, produce
|
|
13
|
-
from ._graph import _CompiledNode
|
|
20
|
+
from ._graph import _CleanupKind, _CompiledNode
|
|
14
21
|
from ._model import _DependencyError, _ProviderCallable, _Scope
|
|
15
22
|
|
|
23
|
+
_LOGGER = logging.getLogger("relay_runtime.dependencies")
|
|
24
|
+
|
|
16
25
|
|
|
17
26
|
@dataclass(frozen=True)
|
|
18
27
|
class _ContainerEntry:
|
|
@@ -21,29 +30,57 @@ class _ContainerEntry:
|
|
|
21
30
|
|
|
22
31
|
|
|
23
32
|
class ContainerState:
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
Relay
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
33
|
+
"""Container cache, provider identities, resources, and shutdown.
|
|
34
|
+
|
|
35
|
+
Relay's warm container owns one instance. An override context owns an
|
|
36
|
+
isolated instance with the same behavior. Relay serializes invocations in
|
|
37
|
+
one process on one event loop, so the state needs no lock. It owns cached
|
|
38
|
+
values, the loop each asynchronous value was created on, strong provider
|
|
39
|
+
references that keep identity cache keys stable, the LIFO cleanup stack,
|
|
40
|
+
and the shutdown transition.
|
|
31
41
|
"""
|
|
32
42
|
|
|
33
|
-
def __init__(
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
*,
|
|
46
|
+
reject_async_cleanup: bool = False,
|
|
47
|
+
is_closed: Callable[[], bool] | None = None,
|
|
48
|
+
) -> None:
|
|
34
49
|
self._providers: dict[int, _ProviderCallable] = {}
|
|
35
50
|
self._entries: dict[int, _ContainerEntry] = {}
|
|
36
51
|
self._finalizers: list[_Finalizer] = []
|
|
37
52
|
self._shutting_down = False
|
|
53
|
+
self._reject_async_cleanup = reject_async_cleanup
|
|
54
|
+
self._is_closed = is_closed
|
|
38
55
|
|
|
39
56
|
async def resolve(self, node: _CompiledNode, invocation: _Resolver) -> Any:
|
|
57
|
+
self._ensure_open()
|
|
58
|
+
|
|
59
|
+
if self._reject_async_cleanup and node.cleanup is _CleanupKind.ASYNC:
|
|
60
|
+
raise _DependencyError(
|
|
61
|
+
f"container-scoped dependency {node.plan.name!r} is an async "
|
|
62
|
+
"generator; a synchronous override_dependencies context cannot "
|
|
63
|
+
"clean it up. Use 'async with override_dependencies(...)'."
|
|
64
|
+
)
|
|
65
|
+
|
|
40
66
|
key = id(node.dependency)
|
|
41
67
|
entry = self._entries.get(key)
|
|
42
68
|
if entry is not None:
|
|
43
69
|
self._check_loop(node, entry)
|
|
44
70
|
return entry.value
|
|
45
71
|
|
|
46
|
-
produced = await produce(
|
|
72
|
+
produced = await produce(
|
|
73
|
+
node,
|
|
74
|
+
invocation,
|
|
75
|
+
reject_async_generator=self._reject_async_cleanup,
|
|
76
|
+
)
|
|
77
|
+
if self._is_closed is not None and self._is_closed():
|
|
78
|
+
await self._close_and_raise(
|
|
79
|
+
produced.finalizer,
|
|
80
|
+
"override_dependencies context has exited; its container "
|
|
81
|
+
"dependencies cannot be resolved",
|
|
82
|
+
)
|
|
83
|
+
|
|
47
84
|
# Only asynchronous creation can bind a value to a loop; sync values
|
|
48
85
|
# remain usable from any loop that drives the same warm container.
|
|
49
86
|
loop = asyncio.get_running_loop() if produced.async_created else None
|
|
@@ -56,13 +93,37 @@ class ContainerState:
|
|
|
56
93
|
self._finalizers.append(produced.finalizer)
|
|
57
94
|
return produced.value
|
|
58
95
|
|
|
96
|
+
def _ensure_open(self) -> None:
|
|
97
|
+
if self._is_closed is not None and self._is_closed():
|
|
98
|
+
raise _DependencyError(
|
|
99
|
+
"override_dependencies context has exited; its container "
|
|
100
|
+
"dependencies cannot be resolved"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
async def _close_and_raise(
|
|
104
|
+
self, finalizer: _Finalizer | None, message: str
|
|
105
|
+
) -> NoReturn:
|
|
106
|
+
if finalizer is not None:
|
|
107
|
+
errors, cancelled = await _run_cleanups([finalizer])
|
|
108
|
+
for error in errors:
|
|
109
|
+
_LOGGER.error(
|
|
110
|
+
"container dependency cleanup failed while rejecting it",
|
|
111
|
+
exc_info=(type(error), error, error.__traceback__),
|
|
112
|
+
)
|
|
113
|
+
if cancelled:
|
|
114
|
+
raise asyncio.CancelledError
|
|
115
|
+
|
|
116
|
+
raise _DependencyError(message)
|
|
117
|
+
|
|
59
118
|
def _check_loop(self, node: _CompiledNode, entry: _ContainerEntry) -> None:
|
|
60
119
|
if entry.loop is None:
|
|
61
120
|
return
|
|
121
|
+
|
|
62
122
|
try:
|
|
63
123
|
loop = asyncio.get_running_loop()
|
|
64
124
|
except RuntimeError:
|
|
65
125
|
return
|
|
126
|
+
|
|
66
127
|
if loop is not entry.loop:
|
|
67
128
|
raise _DependencyError(
|
|
68
129
|
f"container-scoped dependency {node.name!r} was created on a "
|
|
@@ -83,13 +144,9 @@ class ContainerState:
|
|
|
83
144
|
try:
|
|
84
145
|
errors, cancelled = await _run_cleanups(finalizers)
|
|
85
146
|
except asyncio.CancelledError:
|
|
86
|
-
return [
|
|
87
|
-
_DependencyError("container dependency cleanup was cancelled")
|
|
88
|
-
]
|
|
147
|
+
return [_DependencyError("container dependency cleanup was cancelled")]
|
|
89
148
|
except BaseException as exc:
|
|
90
|
-
return [
|
|
91
|
-
_DependencyError(f"container dependency cleanup failed: {exc}")
|
|
92
|
-
]
|
|
149
|
+
return [_DependencyError(f"container dependency cleanup failed: {exc}")]
|
|
93
150
|
finally:
|
|
94
151
|
self._shutting_down = False
|
|
95
152
|
|
|
@@ -97,8 +154,25 @@ class ContainerState:
|
|
|
97
154
|
errors.append(
|
|
98
155
|
_DependencyError("container dependency cleanup was cancelled")
|
|
99
156
|
)
|
|
157
|
+
|
|
100
158
|
return errors
|
|
101
159
|
|
|
160
|
+
def shutdown_sync(self) -> list[BaseException]:
|
|
161
|
+
"""Close synchronous container resources without an event loop."""
|
|
162
|
+
|
|
163
|
+
if self._shutting_down:
|
|
164
|
+
return []
|
|
165
|
+
self._shutting_down = True
|
|
166
|
+
|
|
167
|
+
finalizers, self._finalizers = self._finalizers, []
|
|
168
|
+
self._entries.clear()
|
|
169
|
+
self._providers.clear()
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
return _run_sync_cleanups(finalizers)
|
|
173
|
+
finally:
|
|
174
|
+
self._shutting_down = False
|
|
175
|
+
|
|
102
176
|
|
|
103
177
|
class InvocationState:
|
|
104
178
|
"""Per-invocation event/context values, cache, and cleanup stack."""
|
|
@@ -108,14 +182,19 @@ class InvocationState:
|
|
|
108
182
|
event: Any,
|
|
109
183
|
context: HandlerContext,
|
|
110
184
|
container: ContainerState,
|
|
185
|
+
*,
|
|
186
|
+
is_closed: Callable[[], bool] | None = None,
|
|
111
187
|
) -> None:
|
|
112
188
|
self.event = event
|
|
113
189
|
self.context = context
|
|
114
190
|
self._container = container
|
|
191
|
+
self._is_closed = is_closed
|
|
115
192
|
self._cache: dict[_CompiledNode, Any] = {}
|
|
116
193
|
self._finalizers = _FinalizerStack()
|
|
117
194
|
|
|
118
195
|
async def resolve(self, node: _CompiledNode) -> Any:
|
|
196
|
+
self._ensure_open()
|
|
197
|
+
|
|
119
198
|
if node.scope is _Scope.CONTAINER:
|
|
120
199
|
return await self._container.resolve(node, self)
|
|
121
200
|
|
|
@@ -123,12 +202,20 @@ class InvocationState:
|
|
|
123
202
|
return self._cache[node]
|
|
124
203
|
|
|
125
204
|
produced = await produce(node, self)
|
|
126
|
-
if node.use_cache:
|
|
127
|
-
self._cache[node] = produced.value
|
|
128
205
|
if produced.finalizer is not None:
|
|
129
206
|
self._finalizers.append(produced.finalizer)
|
|
207
|
+
self._ensure_open()
|
|
208
|
+
if node.use_cache:
|
|
209
|
+
self._cache[node] = produced.value
|
|
130
210
|
return produced.value
|
|
131
211
|
|
|
212
|
+
def _ensure_open(self) -> None:
|
|
213
|
+
if self._is_closed is not None and self._is_closed():
|
|
214
|
+
raise _DependencyError(
|
|
215
|
+
"override_dependencies context has exited; dependencies cannot "
|
|
216
|
+
"be resolved after the context manager exits"
|
|
217
|
+
)
|
|
218
|
+
|
|
132
219
|
async def close(
|
|
133
220
|
self, active_exception: BaseException | None = None
|
|
134
221
|
) -> tuple[list[BaseException], bool]:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|