Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ASGI support #1635

Merged
merged 49 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
c5c8ec5
feat: initial ASGI support
Lancetnik Aug 3, 2024
15aa02a
docs: generate API References
Lancetnik Aug 3, 2024
8ac39f8
feat: add make_asyncapi_html method
Lancetnik Aug 3, 2024
f2afe38
Merge branch 'feat/asgi' of github.com:airtai/faststream into feat/asgi
Lancetnik Aug 3, 2024
32b68db
feat: detail make_asyncapi_asgi params
Lancetnik Aug 3, 2024
4ef0d06
refactor: reuse app.mount to add asyncapi url
Lancetnik Aug 3, 2024
94bb690
refactor: remove useless charset
Lancetnik Aug 3, 2024
6618d1a
refactor: add AsgiFastStream args comment
Lancetnik Aug 3, 2024
df75d67
refactor: rename AsgiFastStream lifespan
Lancetnik Aug 3, 2024
54c4ae6
tests: cover asgi
Lancetnik Aug 3, 2024
f742c9c
docs: add ASGI page
Lancetnik Aug 3, 2024
a5b26c9
tests: fix 3.8 compatibility
Lancetnik Aug 3, 2024
b4e171e
chore: make detail tests CI output
Lancetnik Aug 3, 2024
6223ff2
test: make asyncapi asgi test in-memory
Lancetnik Aug 3, 2024
6518a33
docs: add asgi and OTEL to Public API
Lancetnik Aug 3, 2024
cc14939
docs: run API generator
Lancetnik Aug 3, 2024
50655c0
Merge branch 'main' into feat/asgi
Lancetnik Aug 4, 2024
b4db46e
fix: use classmethod
Lancetnik Aug 4, 2024
42c2e3f
test: increase confuent testclient timeout
Lancetnik Aug 4, 2024
768bf3d
Merge branch 'main' into feat/asgi
Lancetnik Aug 4, 2024
99b0f70
tests: fix confluent
Lancetnik Aug 4, 2024
f0b9727
Merge branch 'feat/asgi' of github.com:airtai/faststream into feat/asgi
Lancetnik Aug 4, 2024
70c51a5
refactor: clarify BatchKafkaParser behavior
Lancetnik Aug 4, 2024
1893fcb
lint: run ruff
Lancetnik Aug 4, 2024
8f23bba
lint: fix mypy
Lancetnik Aug 4, 2024
8e64d6f
Update ASGI docs
kumaranvpl Aug 4, 2024
636cd1b
Merge branch 'feat/asgi' of github.com:airtai/faststream into feat/asgi
kumaranvpl Aug 4, 2024
b51b4ab
tests: fix confluent
Lancetnik Aug 5, 2024
ef4ecf1
chore: bump dependencies
Lancetnik Aug 5, 2024
16a2085
chore: bump version
Lancetnik Aug 5, 2024
2a7a875
chore: add kafka devcontainer
Lancetnik Aug 5, 2024
b49ed38
refactor: optimize confluent a bit
Lancetnik Aug 5, 2024
9bd52b9
refactor: optimize confluent client calls
Lancetnik Aug 6, 2024
aa2f44c
docs: generate API
Lancetnik Aug 6, 2024
f73d8fc
docs: remove useless API
Lancetnik Aug 6, 2024
4a2e2fc
chore: detail confluent tests
Lancetnik Aug 6, 2024
e432e29
tests: refactor to use custom args, kwargs for subscriber
Lancetnik Aug 6, 2024
9faa325
tests: fix confluent
Lancetnik Aug 7, 2024
d203fbf
docs: generate API References
Lancetnik Aug 7, 2024
a11f604
tests: fix asyncapi FastAPI
Lancetnik Aug 7, 2024
680bfe9
Merge branch 'feat/asgi' of github.com:airtai/faststream into feat/asgi
Lancetnik Aug 7, 2024
3fe4847
chore: revert FastAPI changes
Lancetnik Aug 7, 2024
92a2988
tests: increase confluent tests timeouts
Lancetnik Aug 7, 2024
3924a13
fix: fix Nats router subjects
Lancetnik Aug 7, 2024
24a0de6
lint: fix formating
Lancetnik Aug 7, 2024
81771b5
tests: increase confluent tests timeouts
Lancetnik Aug 7, 2024
6f2ebb8
lint: run ruff
Lancetnik Aug 7, 2024
741a22a
tests: remove explicit confluent address
Lancetnik Aug 7, 2024
83fe454
tests: run docs tests first
Lancetnik Aug 7, 2024
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
2 changes: 1 addition & 1 deletion .github/workflows/pr_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ jobs:
run: pip install --pre "pydantic>=2.0.0b2,<3.0.0"
- run: mkdir coverage
- name: Test
run: bash scripts/test.sh -m "(slow and (not nats and not kafka and not confluent and not rabbit and not redis)) or (not nats and not kafka and not confluent and not rabbit and not redis)"
run: bash scripts/test.sh -vv -m "(slow and (not nats and not kafka and not confluent and not rabbit and not redis)) or (not nats and not kafka and not confluent and not rabbit and not redis)"
env:
COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.pydantic-version }}
CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.pydantic-version }}
Expand Down
2 changes: 2 additions & 0 deletions docs/create_api_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@


PUBLIC_API_FILES = [
"faststream/opentelemetry/__init__.py",
"faststream/asgi/__init__.py",
"faststream/asyncapi/__init__.py",
"faststream/__init__.py",
"faststream/nats/__init__.py",
Expand Down
28 changes: 28 additions & 0 deletions docs/docs/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ search:
- [FastAPI Plugin](getting-started/integrations/fastapi/index.md)
- [Django](getting-started/integrations/django/index.md)
- [CLI commands](getting-started/cli/index.md)
- [ASGI](getting-started/asgi.md)
- [OpenTelemetry](getting-started/opentelemetry/index.md)
- [Logging](getting-started/logging.md)
- [Config Management](getting-started/config/index.md)
Expand Down Expand Up @@ -120,6 +121,12 @@ search:
- [Response](public_api/faststream/Response.md)
- [TestApp](public_api/faststream/TestApp.md)
- [apply_types](public_api/faststream/apply_types.md)
- asgi
- [AsgiFastStream](public_api/faststream/asgi/AsgiFastStream.md)
- [AsgiResponse](public_api/faststream/asgi/AsgiResponse.md)
- [get](public_api/faststream/asgi/get.md)
- [make_asyncapi_asgi](public_api/faststream/asgi/make_asyncapi_asgi.md)
- [make_ping_asgi](public_api/faststream/asgi/make_ping_asgi.md)
- asyncapi
- [get_app_schema](public_api/faststream/asyncapi/get_app_schema.md)
- [get_asyncapi_html](public_api/faststream/asyncapi/get_asyncapi_html.md)
Expand Down Expand Up @@ -164,6 +171,9 @@ search:
- [StreamSource](public_api/faststream/nats/StreamSource.md)
- [TestApp](public_api/faststream/nats/TestApp.md)
- [TestNatsBroker](public_api/faststream/nats/TestNatsBroker.md)
- opentelemetry
- [TelemetryMiddleware](public_api/faststream/opentelemetry/TelemetryMiddleware.md)
- [TelemetrySettingsProvider](public_api/faststream/opentelemetry/TelemetrySettingsProvider.md)
- rabbit
- [ExchangeType](public_api/faststream/rabbit/ExchangeType.md)
- [RabbitBroker](public_api/faststream/rabbit/RabbitBroker.md)
Expand Down Expand Up @@ -200,6 +210,23 @@ search:
- [apply_types](api/faststream/apply_types.md)
- app
- [FastStream](api/faststream/app/FastStream.md)
- asgi
- [AsgiFastStream](api/faststream/asgi/AsgiFastStream.md)
- [AsgiResponse](api/faststream/asgi/AsgiResponse.md)
- [get](api/faststream/asgi/get.md)
- [make_asyncapi_asgi](api/faststream/asgi/make_asyncapi_asgi.md)
- [make_ping_asgi](api/faststream/asgi/make_ping_asgi.md)
- app
- [AsgiFastStream](api/faststream/asgi/app/AsgiFastStream.md)
- factories
- [make_asyncapi_asgi](api/faststream/asgi/factories/make_asyncapi_asgi.md)
- [make_ping_asgi](api/faststream/asgi/factories/make_ping_asgi.md)
- handlers
- [get](api/faststream/asgi/handlers/get.md)
- response
- [AsgiResponse](api/faststream/asgi/response/AsgiResponse.md)
- websocket
- [WebSocketClose](api/faststream/asgi/websocket/WebSocketClose.md)
- asyncapi
- [get_app_schema](api/faststream/asyncapi/get_app_schema.md)
- [get_asyncapi_html](api/faststream/asyncapi/get_asyncapi_html.md)
Expand All @@ -214,6 +241,7 @@ search:
- [get_response_schema](api/faststream/asyncapi/message/get_response_schema.md)
- [parse_handler_params](api/faststream/asyncapi/message/parse_handler_params.md)
- proto
- [AsyncAPIApplication](api/faststream/asyncapi/proto/AsyncAPIApplication.md)
- [AsyncAPIProto](api/faststream/asyncapi/proto/AsyncAPIProto.md)
- schema
- [Channel](api/faststream/asyncapi/schema/Channel.md)
Expand Down
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/AsgiFastStream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.AsgiFastStream
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/AsgiResponse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.AsgiResponse
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/app/AsgiFastStream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.app.AsgiFastStream
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/factories/make_asyncapi_asgi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.factories.make_asyncapi_asgi
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/factories/make_ping_asgi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.factories.make_ping_asgi
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/get.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.get
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/handlers/get.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.handlers.get
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/make_asyncapi_asgi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.make_asyncapi_asgi
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/make_ping_asgi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.make_ping_asgi
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/response/AsgiResponse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.response.AsgiResponse
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asgi/websocket/WebSocketClose.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asgi.websocket.WebSocketClose
11 changes: 11 additions & 0 deletions docs/docs/en/api/faststream/asyncapi/proto/AsyncAPIApplication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 0.5
---

::: faststream.asyncapi.proto.AsyncAPIApplication
145 changes: 145 additions & 0 deletions docs/docs/en/getting-started/asgi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 10
---

# ASGI support

Often you need to not just run your application to consume messages, but make it the real part of your services ecosystem: with *Prometheus metrics*, K8S *leviness* and *readiness probes*, *traces* and other observability staff.

Unfortunately, such functional can't be implemented by broker-features only and you have to provide several **HTTP** endpoints in your app.

For sure, you can use **FastStream** as a part of your any **ASGI** frameworks ([integrations](./integrations/frameworks/index.md){.internal-link}), but the fewer dependencies, the better, right?

## AsgiFastStream

Helpfully, we have built-in **ASGI** support. It is very limited, but good enough to provides you with basic functional for metrics and healthcheks endpoints implementation.

Let's take a look at the following example:

```python linenums="1" hl_lines="2 5" title="main.py"
from faststream.nats import NatsBroker
from faststream.asgi import AsgiFastStream

broker = NatsBroker()
app = AsgiFastStream(broker)
```

This simple example just provides you with an ability to run the app using regular **ASGI** servers:

```shell
uvicorn main:app
```

Now it does nothing but launches the app itself as a **ASGI lifespan**.


### ASGI routes

It doesn't look really helpful, so let's add some **HTTP** endpoints.

At first, we have already written wrapper on top of broker to make ready-to-use **ASGI** healthcheck endpoint for you

```python linenums="1" hl_lines="2 9"
from faststream.nats import NatsBroker
from faststream.asgi import AsgiFastStream, make_ping_asgi

broker = NatsBroker()

app = AsgiFastStream(
broker,
asgi_routes=[
("/health", make_ping_asgi(broker, timeout=5.0)),
]
)
```

!!! note
This `/health` endpoint calls `#!python broker.ping()` method and return **HTTP 204** or **HTTP 500** statuses.

### Custom ASGI routes

**AsgiFastStream** is able to call any **ASGI**-compatible callable objects, so you can use any endpoints from other libraries if they are compatible with the protocol.

But, if you need to write you own simple **HTTP**-endpoint you can use our `#!python @get` decorator as in the following example:

```python linenums="1" hl_lines="2 6-8 12"
from faststream.nats import NatsBroker
from faststream.asgi import AsgiFastStream, AsgiResponse, get

broker = NatsBroker()

@get
async def liveness_ping(scope):
return AsgiResponse(b"", status_code=200)

app = AsgiFastStream(
broker,
asgi_routes=[("/health", liveness_ping)]
)
```

Or you can write **ASGI** endpoint by yourself

```python
async def liveness_ping(scope, receive, send):
return AsgiResponse(b"", status_code=200)
```

!!! tip
You need no to setup all routes by `asgi_routes=[]` initial option.<br/>
You can use `#!python app.mount("/healh", asgi_endpoint)` method instead.

### AsyncAPI documentation

Also, you can host your **AsyncAPI** documentation without new process, run by [`#!shell faststream docs serve ...`](./asyncapi/hosting.md){.internal-link}, but in the same container and runtime.

Just create `AsgiFastStream` object with a special option:

```python linenums="1" hl_lines="8"
from faststream.nats import NatsBroker
from faststream.asgi import AsgiFastStream

broker = NatsBroker()

app = AsgiFastStream(
broker,
asyncapi_path="/docs",
)
```

Now, your **AsyncAPI HTML** representation can be founded in the net by `/docs` url.

## Another ASGI compatibility

Moreover, our wrappers can be used as a ready-to-use endpoins for other **ASGI** frameworks. It can be very helpful in cases, then you are running **FastStream** in the same runtime with any **ASGI** framework.

Just follow the example in such cases:

```python linenums="1" hl_lines="6 19-20"
from contextlib import asynccontextmanager

from fastapi import FastAPI
from faststream import FastStream
from faststream.nats import NatsBroker
from faststream.asgi import make_ping_asgi, make_asyncapi_asgi

broker = NatsBroker()

@asynccontextmanager
async def start_broker(app):
"""Start the broker with the app."""
async with broker:
await broker.start()
yield

app = FastAPI(lifespan=start_broker)

app.mount("/health", make_ping_asgi(broker, timeout=5.0))
app.mount("/asyncapi", make_asyncapi_asgi(FastStream(broker)))
```
1 change: 1 addition & 0 deletions docs/docs/navigation_template.txt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ search:
- [FastAPI Plugin](getting-started/integrations/fastapi/index.md)
- [Django](getting-started/integrations/django/index.md)
- [CLI commands](getting-started/cli/index.md)
- [ASGI](getting-started/asgi.md)
- [OpenTelemetry](getting-started/opentelemetry/index.md)
- [Logging](getting-started/logging.md)
- [Config Management](getting-started/config/index.md)
Expand Down
4 changes: 1 addition & 3 deletions faststream/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ def json_dumps(*a: Any, **kw: Any) -> bytes:
try:
from fastapi import __version__ as FASTAPI_VERSION # noqa: N812

HAS_FASTAPI = True

major, minor, *_ = map(int, FASTAPI_VERSION.split("."))
FASTAPI_V2 = major > 0 or minor > 100
FASTAPI_V106 = major > 0 or minor >= 106
Expand All @@ -70,7 +68,7 @@ def raise_fastapi_validation_error(errors: List[Any], body: AnyDict) -> Never:
raise RequestValidationError(errors, ROUTER_VALIDATION_ERROR_MODEL) # type: ignore[misc]

except ImportError:
HAS_FASTAPI = False
pass

JsonSchemaValue = Mapping[str, Any]

Expand Down
Loading
Loading