Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ _build
# coverage
.coverage
.coverage.*
coverage.xml
coverage.xml

# benchmarks
.benchmarks
6 changes: 3 additions & 3 deletions packages/amgi-types/src/amgi_types/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
from collections.abc import Awaitable
from collections.abc import Callable
from collections.abc import Iterable
from collections.abc import Sequence
from typing import Any
from typing import Literal
from typing import TypedDict
Expand Down Expand Up @@ -96,7 +96,7 @@ class MessageReceiveEvent(TypedDict):

type: Literal["message.receive"]
id: str
headers: Iterable[tuple[bytes, bytes]]
headers: Sequence[tuple[bytes, bytes]]
payload: NotRequired[bytes | None]
bindings: NotRequired[dict[str, dict[str, Any]]]
more_messages: NotRequired[bool]
Expand Down Expand Up @@ -136,7 +136,7 @@ class MessageSendEvent(TypedDict):

type: Literal["message.send"]
address: str
headers: Iterable[tuple[bytes, bytes]]
headers: Sequence[tuple[bytes, bytes]]
payload: NotRequired[bytes | None]
bindings: NotRequired[dict[str, dict[str, Any]]]

Expand Down
57 changes: 57 additions & 0 deletions packages/asyncfast/docs/dependencies.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
##############
Dependencies
##############

Dependencies let you share common logic across channel handlers. They are declared with ``Depends`` and injected using
``typing.Annotated``.

A dependency function can be ``def`` or ``async def``. It can also be a generator (sync or async) to provide setup and
cleanup logic.

******************
Basic Dependency
******************

Use ``Depends`` inside ``Annotated`` to tell AsyncFast to resolve a value and pass it to your handler:

.. async-fast-example:: examples/dependency_basic.py

**********************************
Dependencies Use The Same Inputs
**********************************

Dependency functions can declare the same kinds of parameters as a channel handler:

- ``Payload`` (the message body)
- ``Header`` values
- channel parameters (from the address template)
- bindings (via protocol binding types)
- ``MessageSender`` for sending follow-up messages

These inputs are resolved for dependencies exactly the same way they are for handlers.

******************
Sub-dependencies
******************

Dependencies can depend on other dependencies using the same ``Depends`` pattern:

.. async-fast-example:: examples/dependency_sub_dependency.py

********************
Cleanup With Yield
********************

If a dependency is a generator, AsyncFast treats it like a context manager and runs cleanup after the handler returns.
This works for both ``def`` generators and ``async def`` generators:

.. async-fast-example:: examples/dependency_yield.py

*********
Caching
*********

By default, a dependency result is cached per message and reused if requested multiple times. To disable caching, set
``use_cache=False`` on ``Depends``:

.. async-fast-example:: examples/dependency_cache.py
20 changes: 20 additions & 0 deletions packages/asyncfast/docs/examples/dependency_basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import Annotated

from asyncfast import AsyncFast
from asyncfast import Depends
from asyncfast import Header

app = AsyncFast()


def get_context(
request_id: Annotated[str, Header(alias="request-id")],
) -> dict[str, str]:
return {"request_id": request_id}


@app.channel("orders.created")
async def handle_orders(
context: Annotated[dict[str, str], Depends(get_context)],
) -> None:
print(context["request_id"])
19 changes: 19 additions & 0 deletions packages/asyncfast/docs/examples/dependency_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import Annotated

from asyncfast import AsyncFast
from asyncfast import Depends
from asyncfast import Header

app = AsyncFast()


def get_request_id(request_id: Annotated[str, Header(alias="request-id")]) -> str:
return request_id


@app.channel("events")
async def handle_events(
request_id: Annotated[str, Depends(get_request_id, use_cache=False)],
request_id_again: Annotated[str, Depends(get_request_id, use_cache=False)],
) -> None:
print(request_id, request_id_again)
24 changes: 24 additions & 0 deletions packages/asyncfast/docs/examples/dependency_sub_dependency.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from typing import Annotated

from asyncfast import AsyncFast
from asyncfast import Depends
from asyncfast import Header

app = AsyncFast()


def get_tenant_id(tenant_id: Annotated[str, Header(alias="tenant-id")]) -> str:
return tenant_id


def get_context(
tenant_id: Annotated[str, Depends(get_tenant_id)],
) -> dict[str, str]:
return {"tenant_id": tenant_id}


@app.channel("billing")
async def handle_billing(
context: Annotated[dict[str, str], Depends(get_context)],
) -> None:
print(context["tenant_id"])
23 changes: 23 additions & 0 deletions packages/asyncfast/docs/examples/dependency_yield.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from collections.abc import AsyncGenerator
from typing import Annotated

from asyncfast import AsyncFast
from asyncfast import Depends

app = AsyncFast()


async def get_resource() -> AsyncGenerator[str, None]:
resource = "connected"
try:
yield resource
finally:
# Cleanup happens after the handler returns.
pass


@app.channel("ping")
async def handle_ping(
resource: Annotated[str, Depends(get_resource)],
) -> None:
print(resource)
1 change: 1 addition & 0 deletions packages/asyncfast/docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ Taking ideas from:

receiving
sending
dependencies
lifespan

.. _amgi: https://amgi.readthedocs.io/en/latest/
Expand Down
9 changes: 9 additions & 0 deletions packages/asyncfast/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ scripts.asyncfast = "asyncfast.cli:main"
dev = [
"pytest>=8.4.1",
"pytest-asyncio>=1.1",
"pytest-benchmark>=5.2.3",
"pytest-cov>=7.0.0",
"pytest-timeout>=2.4.0",
]
Expand All @@ -60,3 +61,11 @@ workspace = true

[tool.uv.sources.asyncfast-cli]
workspace = true

[tool.pytest.ini_options]
asyncio_mode = "auto"
timeout = 10
timeout_func_only = true
addopts = [
"--benchmark-max-time=0.1",
]
Loading