faststream_fastapi 1.3.1__tar.gz → 1.5.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.
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/PKG-INFO +2 -3
- faststream_fastapi-1.5.0/pyproject.toml +147 -0
- faststream_fastapi-1.3.1/pyproject.toml → faststream_fastapi-1.5.0/pyproject.toml.orig +18 -14
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/background_middleware.py +2 -0
- faststream_fastapi-1.5.0/src/faststream_fastapi/_internal/config.py +17 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fastapi_compat.py +23 -13
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/_compat.py +2 -1
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/get_dependant.py +12 -5
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/replace_context.py +37 -27
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/wrap_callable_to_fastapi_compatible.py +111 -34
- faststream_fastapi-1.5.0/src/faststream_fastapi/context.py +39 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/faststream_api.py +88 -36
- faststream_fastapi-1.5.0/src/faststream_fastapi/stream_message.py +90 -0
- faststream_fastapi-1.3.1/src/faststream_fastapi/_internal/config.py +0 -23
- faststream_fastapi-1.3.1/src/faststream_fastapi/context.py +0 -31
- faststream_fastapi-1.3.1/src/faststream_fastapi/stream_message.py +0 -25
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/LICENSE +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/README.md +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/__about__.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/__init__.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/__init__.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/asyncapi_router.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/__init__.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/application.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/broker.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/constants.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/context.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/di.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/fs_re_exports/logger.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/logger.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/asyncapi_config.py +0 -0
- {faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: faststream_fastapi
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.5.0
|
|
4
4
|
Summary: FastAPI integration for FastStream
|
|
5
5
|
Keywords: rabbitmq,kafka,nats,redis,mqtt,asyncapi,framework,message brokers,fastapi
|
|
6
6
|
Author: Ivan Kirpichnikov
|
|
@@ -12,7 +12,6 @@ Classifier: Programming Language :: Python
|
|
|
12
12
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
13
13
|
Classifier: Programming Language :: Python :: 3
|
|
14
14
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.11
|
|
17
16
|
Classifier: Programming Language :: Python :: 3.12
|
|
18
17
|
Classifier: Programming Language :: Python :: 3.13
|
|
@@ -35,7 +34,7 @@ Classifier: Framework :: Pydantic :: 1
|
|
|
35
34
|
Classifier: Framework :: Pydantic :: 2
|
|
36
35
|
Requires-Dist: fastapi<1.0.0
|
|
37
36
|
Requires-Dist: faststream>=0.7.0
|
|
38
|
-
Requires-Python: >=3.
|
|
37
|
+
Requires-Python: >=3.11
|
|
39
38
|
Description-Content-Type: text/markdown
|
|
40
39
|
|
|
41
40
|
# FastAPI Plugin for FastStream
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "faststream_fastapi"
|
|
7
|
+
description = "FastAPI integration for FastStream"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
license = "MIT"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
version = "1.5.0"
|
|
13
|
+
keywords = [
|
|
14
|
+
"rabbitmq",
|
|
15
|
+
"kafka",
|
|
16
|
+
"nats",
|
|
17
|
+
"redis",
|
|
18
|
+
"mqtt",
|
|
19
|
+
"asyncapi",
|
|
20
|
+
"framework",
|
|
21
|
+
"message brokers",
|
|
22
|
+
"fastapi",
|
|
23
|
+
]
|
|
24
|
+
classifiers = [
|
|
25
|
+
"Development Status :: 5 - Production/Stable",
|
|
26
|
+
"Programming Language :: Python",
|
|
27
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
28
|
+
"Programming Language :: Python :: 3",
|
|
29
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
30
|
+
"Programming Language :: Python :: 3.11",
|
|
31
|
+
"Programming Language :: Python :: 3.12",
|
|
32
|
+
"Programming Language :: Python :: 3.13",
|
|
33
|
+
"Programming Language :: Python :: 3.14",
|
|
34
|
+
"Operating System :: OS Independent",
|
|
35
|
+
"Topic :: Software Development :: Libraries :: Application Frameworks",
|
|
36
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
37
|
+
"Topic :: Software Development :: Libraries",
|
|
38
|
+
"Topic :: Software Development",
|
|
39
|
+
"Topic :: System :: Networking",
|
|
40
|
+
"Topic :: System :: Distributed Computing",
|
|
41
|
+
"Typing :: Typed",
|
|
42
|
+
"Intended Audience :: Developers",
|
|
43
|
+
"Intended Audience :: Information Technology",
|
|
44
|
+
"Intended Audience :: System Administrators",
|
|
45
|
+
"Environment :: Web Environment",
|
|
46
|
+
"Framework :: AsyncIO",
|
|
47
|
+
"Framework :: Pydantic",
|
|
48
|
+
"Framework :: Pydantic :: 1",
|
|
49
|
+
"Framework :: Pydantic :: 2",
|
|
50
|
+
]
|
|
51
|
+
dependencies = [
|
|
52
|
+
"fastapi<1.0.0",
|
|
53
|
+
"faststream>=0.7.0",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
[[project.authors]]
|
|
57
|
+
name = "Ivan Kirpichnikov"
|
|
58
|
+
email = "mmssvvvv570@gmail.com"
|
|
59
|
+
|
|
60
|
+
[dependency-groups]
|
|
61
|
+
linters = [
|
|
62
|
+
"ruff==0.17.6",
|
|
63
|
+
"typos==1.52.2",
|
|
64
|
+
"codespell==2.4.3",
|
|
65
|
+
]
|
|
66
|
+
static_analysis = [
|
|
67
|
+
"mypy==2.4.1",
|
|
68
|
+
"bandit==1.9.4",
|
|
69
|
+
"semgrep==1.186.0",
|
|
70
|
+
"zizmor==1.32.0",
|
|
71
|
+
]
|
|
72
|
+
docs = [
|
|
73
|
+
"zensical==0.1.3",
|
|
74
|
+
"mkdocstrings[python]==1.0.8",
|
|
75
|
+
]
|
|
76
|
+
testing = [
|
|
77
|
+
"pytest==9.2.0",
|
|
78
|
+
"pytest-asyncio==1.5.0",
|
|
79
|
+
"pytest-xdist==3.8.0",
|
|
80
|
+
"pytest-timeout==2.4.0",
|
|
81
|
+
"pytest-cov==7.1.0",
|
|
82
|
+
"covdefaults==2.3.0",
|
|
83
|
+
"syrupy==6.1.1",
|
|
84
|
+
{ include-group = "testing-dependencies" },
|
|
85
|
+
]
|
|
86
|
+
testing-dependencies = [
|
|
87
|
+
"httpx2==2.16.2",
|
|
88
|
+
"asgi_lifespan==2.1.0",
|
|
89
|
+
"faststream[rabbit,kafka,confluent,nats,redis,mqtt]>=0.7.0",
|
|
90
|
+
"pyyaml==6.0.3",
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
[[dependency-groups.dev]]
|
|
94
|
+
include-group = "docs"
|
|
95
|
+
|
|
96
|
+
[[dependency-groups.dev]]
|
|
97
|
+
include-group = "testing"
|
|
98
|
+
|
|
99
|
+
[[dependency-groups.dev]]
|
|
100
|
+
include-group = "linters"
|
|
101
|
+
|
|
102
|
+
[[dependency-groups.dev]]
|
|
103
|
+
include-group = "static_analysis"
|
|
104
|
+
|
|
105
|
+
[tool.uv]
|
|
106
|
+
default-groups = []
|
|
107
|
+
|
|
108
|
+
[tool.uv.build-backend]
|
|
109
|
+
module-root = "src"
|
|
110
|
+
module-name = "faststream_fastapi"
|
|
111
|
+
|
|
112
|
+
[tool.pytest.ini_options]
|
|
113
|
+
minversion = "7.0"
|
|
114
|
+
timeout = 30
|
|
115
|
+
addopts = "--strict-markers --strict-config -q -m 'not slow'"
|
|
116
|
+
testpaths = ["tests"]
|
|
117
|
+
markers = [
|
|
118
|
+
"rabbit",
|
|
119
|
+
"kafka",
|
|
120
|
+
"confluent",
|
|
121
|
+
"nats",
|
|
122
|
+
"redis",
|
|
123
|
+
"redis_cluster",
|
|
124
|
+
"mqtt",
|
|
125
|
+
"slow",
|
|
126
|
+
"connected",
|
|
127
|
+
"all",
|
|
128
|
+
]
|
|
129
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
130
|
+
|
|
131
|
+
[tool.coverage.run]
|
|
132
|
+
source = ["src/"]
|
|
133
|
+
relative_files = true
|
|
134
|
+
|
|
135
|
+
[tool.coverage.paths]
|
|
136
|
+
source = [
|
|
137
|
+
"src/",
|
|
138
|
+
"/app/src/",
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
[tool.coverage.report]
|
|
142
|
+
exclude_lines = [
|
|
143
|
+
"pass",
|
|
144
|
+
"def __str__",
|
|
145
|
+
"raise AssertionError",
|
|
146
|
+
"raise NotImplementedError",
|
|
147
|
+
]
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["uv_build
|
|
2
|
+
requires = ["uv_build"]
|
|
3
3
|
build-backend = "uv_build"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
@@ -12,8 +12,8 @@ authors = [
|
|
|
12
12
|
license = "MIT"
|
|
13
13
|
license-files = ["LICENSE"]
|
|
14
14
|
|
|
15
|
-
requires-python = ">=3.
|
|
16
|
-
version = "1.
|
|
15
|
+
requires-python = ">=3.11"
|
|
16
|
+
version = "1.5.0"
|
|
17
17
|
|
|
18
18
|
keywords = [
|
|
19
19
|
"rabbitmq",
|
|
@@ -33,7 +33,6 @@ classifiers = [
|
|
|
33
33
|
"Programming Language :: Python :: Implementation :: CPython",
|
|
34
34
|
"Programming Language :: Python :: 3",
|
|
35
35
|
"Programming Language :: Python :: 3 :: Only",
|
|
36
|
-
"Programming Language :: Python :: 3.10",
|
|
37
36
|
"Programming Language :: Python :: 3.11",
|
|
38
37
|
"Programming Language :: Python :: 3.12",
|
|
39
38
|
"Programming Language :: Python :: 3.13",
|
|
@@ -63,34 +62,36 @@ dependencies = [
|
|
|
63
62
|
|
|
64
63
|
[dependency-groups]
|
|
65
64
|
linters = [
|
|
66
|
-
"ruff==0.
|
|
67
|
-
"typos==1.
|
|
65
|
+
"ruff==0.17.6",
|
|
66
|
+
"typos==1.52.2",
|
|
68
67
|
"codespell==2.4.3",
|
|
69
68
|
]
|
|
70
69
|
static_analysis = [
|
|
71
|
-
"mypy==2.
|
|
70
|
+
"mypy==2.4.1",
|
|
72
71
|
"bandit==1.9.4",
|
|
73
|
-
"semgrep==1.
|
|
74
|
-
"zizmor==1.
|
|
72
|
+
"semgrep==1.186.0",
|
|
73
|
+
"zizmor==1.32.0",
|
|
75
74
|
]
|
|
76
75
|
docs = [
|
|
77
|
-
"zensical==0.
|
|
78
|
-
"mkdocstrings[python]==1.0.
|
|
76
|
+
"zensical==0.1.3",
|
|
77
|
+
"mkdocstrings[python]==1.0.8",
|
|
79
78
|
]
|
|
80
79
|
|
|
81
80
|
testing = [
|
|
82
|
-
"pytest==9.
|
|
83
|
-
"pytest-asyncio==1.
|
|
81
|
+
"pytest==9.2.0",
|
|
82
|
+
"pytest-asyncio==1.5.0",
|
|
84
83
|
"pytest-xdist==3.8.0",
|
|
85
84
|
"pytest-timeout==2.4.0",
|
|
86
85
|
"pytest-cov==7.1.0",
|
|
87
86
|
"covdefaults==2.3.0",
|
|
87
|
+
"syrupy==6.1.1",
|
|
88
88
|
{ include-group = "testing-dependencies" },
|
|
89
89
|
]
|
|
90
90
|
testing-dependencies = [
|
|
91
|
-
"httpx2==2.
|
|
91
|
+
"httpx2==2.16.2",
|
|
92
92
|
"asgi_lifespan==2.1.0",
|
|
93
93
|
"faststream[rabbit,kafka,confluent,nats,redis,mqtt]>=0.7.0",
|
|
94
|
+
"pyyaml==6.0.3",
|
|
94
95
|
]
|
|
95
96
|
|
|
96
97
|
dev = [
|
|
@@ -100,6 +101,9 @@ dev = [
|
|
|
100
101
|
{ include-group = "static_analysis" },
|
|
101
102
|
]
|
|
102
103
|
|
|
104
|
+
[tool.uv]
|
|
105
|
+
default-groups = []
|
|
106
|
+
|
|
103
107
|
[tool.uv.build-backend]
|
|
104
108
|
module-root = "src"
|
|
105
109
|
module-name = "faststream_fastapi"
|
|
@@ -3,9 +3,11 @@ from typing import cast
|
|
|
3
3
|
|
|
4
4
|
from fastapi.background import BackgroundTasks
|
|
5
5
|
from faststream.middlewares import BaseMiddleware
|
|
6
|
+
from typing_extensions import override
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
class _BackgroundMiddleware(BaseMiddleware):
|
|
10
|
+
@override
|
|
9
11
|
async def __aexit__(
|
|
10
12
|
self,
|
|
11
13
|
exc_type: type[BaseException] | None = None,
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from threading import RLock
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI
|
|
6
|
+
|
|
7
|
+
from faststream_fastapi._internal.fs_re_exports.context import ContextRepo
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Config:
|
|
12
|
+
application: FastAPI
|
|
13
|
+
dependency_overrides_provider: Any | None
|
|
14
|
+
context: ContextRepo
|
|
15
|
+
max_streaming_reply_size: int
|
|
16
|
+
context_init_lock: RLock = field(default_factory=RLock)
|
|
17
|
+
asgi_state: dict[str, Any] = field(default_factory=dict)
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
from dataclasses import dataclass
|
|
2
|
-
from typing import Any
|
|
2
|
+
from typing import Any, Never
|
|
3
3
|
|
|
4
4
|
from fastapi import __version__ as FASTAPI_VERSION # noqa: N812
|
|
5
5
|
from fastapi.dependencies.models import Dependant
|
|
6
6
|
from fastapi.dependencies.utils import solve_dependencies
|
|
7
|
-
from fastapi.requests import Request
|
|
8
7
|
from starlette.background import BackgroundTasks
|
|
9
|
-
from
|
|
8
|
+
from starlette.responses import Response
|
|
9
|
+
|
|
10
|
+
from faststream_fastapi._internal.get_dependant import iter_dependants
|
|
11
|
+
from faststream_fastapi.stream_message import StreamMessage
|
|
10
12
|
|
|
11
13
|
major, minor, patch, *_ = FASTAPI_VERSION.split(".")
|
|
12
14
|
|
|
@@ -47,6 +49,7 @@ class SolvedDependency:
|
|
|
47
49
|
values: dict[str, Any]
|
|
48
50
|
errors: list[Any]
|
|
49
51
|
background_tasks: BackgroundTasks | None
|
|
52
|
+
response: Response
|
|
50
53
|
|
|
51
54
|
|
|
52
55
|
if FASTAPI_V128:
|
|
@@ -54,7 +57,7 @@ if FASTAPI_V128:
|
|
|
54
57
|
|
|
55
58
|
def raise_fastapi_validation_error(
|
|
56
59
|
errors: list[Any],
|
|
57
|
-
body:
|
|
60
|
+
body: Any,
|
|
58
61
|
) -> Never:
|
|
59
62
|
raise RequestValidationError(errors, body=body)
|
|
60
63
|
|
|
@@ -64,7 +67,7 @@ elif FASTAPI_V2:
|
|
|
64
67
|
|
|
65
68
|
def raise_fastapi_validation_error(
|
|
66
69
|
errors: list[Any],
|
|
67
|
-
body:
|
|
70
|
+
body: Any,
|
|
68
71
|
) -> Never:
|
|
69
72
|
raise RequestValidationError(_normalize_errors(errors), body=body)
|
|
70
73
|
|
|
@@ -80,7 +83,7 @@ else:
|
|
|
80
83
|
|
|
81
84
|
def raise_fastapi_validation_error(
|
|
82
85
|
errors: list[Any],
|
|
83
|
-
body:
|
|
86
|
+
body: Any,
|
|
84
87
|
) -> Never:
|
|
85
88
|
raise RequestValidationError(errors, ROUTER_VALIDATION_ERROR_MODEL) # type: ignore[call-arg]
|
|
86
89
|
|
|
@@ -90,17 +93,22 @@ if FASTAPI_v102_3:
|
|
|
90
93
|
create_model_field as create_response_field,
|
|
91
94
|
)
|
|
92
95
|
|
|
93
|
-
extra = {"embed_body_fields": False} if FASTAPI_v102_4 else {}
|
|
94
|
-
|
|
95
96
|
async def solve_faststream_dependency(
|
|
96
|
-
request:
|
|
97
|
+
request: StreamMessage,
|
|
97
98
|
dependant: Dependant,
|
|
98
99
|
dependency_overrides_provider: Any | None,
|
|
99
100
|
**kwargs: Any,
|
|
100
101
|
) -> SolvedDependency:
|
|
102
|
+
body_fields = [
|
|
103
|
+
field for dependency in iter_dependants(dependant) for field in dependency.body_params
|
|
104
|
+
]
|
|
105
|
+
embed_body_fields = len({field.name for field in body_fields}) > 1 or any(
|
|
106
|
+
getattr(field.field_info, "embed", False) for field in body_fields
|
|
107
|
+
)
|
|
108
|
+
extra = {"embed_body_fields": embed_body_fields} if FASTAPI_v102_4 else {}
|
|
101
109
|
solved_result = await solve_dependencies(
|
|
102
110
|
request=request,
|
|
103
|
-
body=request.
|
|
111
|
+
body=request.decoded_body,
|
|
104
112
|
dependant=dependant,
|
|
105
113
|
dependency_overrides_provider=dependency_overrides_provider,
|
|
106
114
|
**extra, # type: ignore[arg-type]
|
|
@@ -116,6 +124,7 @@ if FASTAPI_v102_3:
|
|
|
116
124
|
values=values,
|
|
117
125
|
errors=errors,
|
|
118
126
|
background_tasks=background,
|
|
127
|
+
response=solved_result.response,
|
|
119
128
|
)
|
|
120
129
|
|
|
121
130
|
else:
|
|
@@ -124,14 +133,14 @@ else:
|
|
|
124
133
|
)
|
|
125
134
|
|
|
126
135
|
async def solve_faststream_dependency(
|
|
127
|
-
request:
|
|
136
|
+
request: StreamMessage,
|
|
128
137
|
dependant: Dependant,
|
|
129
138
|
dependency_overrides_provider: Any | None,
|
|
130
139
|
**kwargs: Any,
|
|
131
140
|
) -> SolvedDependency:
|
|
132
141
|
solved_result = await solve_dependencies(
|
|
133
142
|
request=request,
|
|
134
|
-
body=request.
|
|
143
|
+
body=request.decoded_body,
|
|
135
144
|
dependant=dependant,
|
|
136
145
|
dependency_overrides_provider=dependency_overrides_provider,
|
|
137
146
|
**kwargs,
|
|
@@ -141,7 +150,7 @@ else:
|
|
|
141
150
|
values,
|
|
142
151
|
errors,
|
|
143
152
|
background,
|
|
144
|
-
|
|
153
|
+
response,
|
|
145
154
|
_dependency_cache,
|
|
146
155
|
) = solved_result # type: ignore[misc]
|
|
147
156
|
|
|
@@ -149,4 +158,5 @@ else:
|
|
|
149
158
|
values=values, # type: ignore[has-type]
|
|
150
159
|
errors=errors, # type: ignore[has-type]
|
|
151
160
|
background_tasks=background, # type: ignore[has-type]
|
|
161
|
+
response=response, # type: ignore[has-type]
|
|
152
162
|
)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import inspect
|
|
2
|
-
from collections.abc import Callable, Iterable
|
|
2
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
3
3
|
from dataclasses import fields
|
|
4
4
|
from typing import Annotated, Any, Final, cast, get_args, get_origin
|
|
5
5
|
|
|
@@ -60,10 +60,11 @@ def get_fastapi_native_dependant(
|
|
|
60
60
|
|
|
61
61
|
def _patch_fastapi_dependent(dependant: Dependant) -> _FastStreamDependant:
|
|
62
62
|
dependant = _extend_fastapi_dependant(dependant)
|
|
63
|
-
params =
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
63
|
+
params = [
|
|
64
|
+
field
|
|
65
|
+
for dependency in iter_dependants(dependant)
|
|
66
|
+
for field in (*dependency.query_params, *dependency.body_params)
|
|
67
|
+
]
|
|
67
68
|
|
|
68
69
|
params_unique = {}
|
|
69
70
|
|
|
@@ -147,6 +148,12 @@ def _patch_fastapi_dependent(dependant: Dependant) -> _FastStreamDependant:
|
|
|
147
148
|
return dependant
|
|
148
149
|
|
|
149
150
|
|
|
151
|
+
def iter_dependants(dependant: Dependant) -> Iterator[Dependant]:
|
|
152
|
+
yield dependant
|
|
153
|
+
for dependency in dependant.dependencies:
|
|
154
|
+
yield from iter_dependants(dependency)
|
|
155
|
+
|
|
156
|
+
|
|
150
157
|
def has_forbidden_types( # noqa: C901
|
|
151
158
|
orig_call: Callable[..., Any],
|
|
152
159
|
forbidden_types: tuple[Any, ...],
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import functools
|
|
2
2
|
import inspect
|
|
3
|
+
import sys
|
|
3
4
|
from collections.abc import Callable, Mapping
|
|
4
5
|
from typing import (
|
|
5
6
|
Annotated,
|
|
@@ -9,10 +10,9 @@ from typing import (
|
|
|
9
10
|
cast,
|
|
10
11
|
get_args,
|
|
11
12
|
get_origin,
|
|
12
|
-
get_type_hints,
|
|
13
13
|
)
|
|
14
14
|
|
|
15
|
-
from fastapi.dependencies.utils import
|
|
15
|
+
from fastapi.dependencies.utils import get_typed_annotation
|
|
16
16
|
from faststream._internal.context import Context as ContextCls
|
|
17
17
|
|
|
18
18
|
from faststream_fastapi import Context as PluginContext
|
|
@@ -24,30 +24,52 @@ T_HandlerReturn = TypeVar("T_HandlerReturn")
|
|
|
24
24
|
def replace_context(
|
|
25
25
|
func: Callable[P_HandlerParams, T_HandlerReturn],
|
|
26
26
|
) -> Callable[P_HandlerParams, T_HandlerReturn]:
|
|
27
|
-
|
|
27
|
+
annotation_source: Any = func
|
|
28
|
+
while isinstance(annotation_source, functools.partial):
|
|
29
|
+
annotation_source = annotation_source.func
|
|
30
|
+
|
|
31
|
+
if not inspect.isroutine(annotation_source) and not inspect.isclass(annotation_source):
|
|
32
|
+
annotation_source = annotation_source.__call__
|
|
33
|
+
|
|
34
|
+
if inspect.iscoroutinefunction(annotation_source):
|
|
28
35
|
|
|
29
36
|
@functools.wraps(func)
|
|
30
37
|
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
31
|
-
return await func(*args, **kwargs)
|
|
38
|
+
return await cast(Callable[..., Any], func)(*args, **kwargs)
|
|
32
39
|
else:
|
|
33
40
|
|
|
34
41
|
@functools.wraps(func)
|
|
35
42
|
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
36
43
|
return func(*args, **kwargs)
|
|
37
44
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
45
|
+
# The callable's effective signature may have been supplied by a decorator.
|
|
46
|
+
try:
|
|
47
|
+
signature = inspect.signature(func, eval_str=True)
|
|
48
|
+
except NameError:
|
|
49
|
+
signature = inspect.signature(func)
|
|
50
|
+
|
|
51
|
+
source = inspect.unwrap(annotation_source)
|
|
52
|
+
module = sys.modules.get(getattr(source, "__module__", ""))
|
|
53
|
+
globalns = getattr(source, "__globals__", vars(module) if module is not None else {})
|
|
54
|
+
parameters = {
|
|
55
|
+
name: param.replace(annotation=get_typed_annotation(param.annotation, globalns))
|
|
56
|
+
for name, param in signature.parameters.items()
|
|
57
|
+
}
|
|
58
|
+
new_params = get_new_parameters(parameters)
|
|
59
|
+
new_annotations = {
|
|
60
|
+
param.name: param.annotation
|
|
61
|
+
for param in new_params
|
|
62
|
+
if param.annotation is not inspect.Parameter.empty
|
|
63
|
+
}
|
|
64
|
+
if signature.return_annotation is not inspect.Signature.empty:
|
|
65
|
+
new_annotations["return"] = signature.return_annotation
|
|
66
|
+
|
|
67
|
+
wrapper.__name__ = getattr(func, "__name__", type(func).__name__)
|
|
68
|
+
wrapper.__qualname__ = getattr(func, "__qualname__", wrapper.__name__)
|
|
44
69
|
wrapper.__doc__ = func.__doc__
|
|
45
|
-
wrapper.__module__ = func
|
|
70
|
+
wrapper.__module__ = getattr(func, "__module__", getattr(source, "__module__", __name__))
|
|
46
71
|
wrapper.__annotations__ = new_annotations
|
|
47
|
-
wrapper.__signature__ =
|
|
48
|
-
parameters=new_params,
|
|
49
|
-
return_annotation=endpoint_signature.return_annotation,
|
|
50
|
-
)
|
|
72
|
+
wrapper.__signature__ = signature.replace(parameters=new_params) # type: ignore[attr-defined]
|
|
51
73
|
|
|
52
74
|
return cast(Callable[P_HandlerParams, T_HandlerReturn], wrapper)
|
|
53
75
|
|
|
@@ -84,18 +106,6 @@ def get_new_parameters(
|
|
|
84
106
|
return new_params
|
|
85
107
|
|
|
86
108
|
|
|
87
|
-
def get_new_annotations(type_hints: Mapping[str, Any]) -> dict[str, Any]:
|
|
88
|
-
new_annotations = {}
|
|
89
|
-
|
|
90
|
-
for param_name, type_hint in type_hints.items():
|
|
91
|
-
if get_origin(type_hint) is Annotated:
|
|
92
|
-
new_annotations[param_name] = replace_annotated(type_hint, param_name)
|
|
93
|
-
else:
|
|
94
|
-
new_annotations[param_name] = type_hint
|
|
95
|
-
|
|
96
|
-
return new_annotations
|
|
97
|
-
|
|
98
|
-
|
|
99
109
|
def replace_annotated(type_hint: Any, parameter_name: str) -> Any:
|
|
100
110
|
annotated_args = get_args(type_hint)
|
|
101
111
|
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import inspect
|
|
2
|
-
from
|
|
2
|
+
from asyncio import Event
|
|
3
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable
|
|
3
4
|
from contextlib import AsyncExitStack
|
|
5
|
+
from copy import copy
|
|
4
6
|
from functools import wraps
|
|
5
|
-
from itertools import dropwhile
|
|
6
7
|
from typing import Any, ParamSpec, TypeVar
|
|
7
8
|
|
|
8
9
|
from fast_depends.dependencies import Dependant
|
|
@@ -12,6 +13,10 @@ from fastapi.routing import run_endpoint_function, serialize_response
|
|
|
12
13
|
from faststream.exceptions import SetupError
|
|
13
14
|
from faststream.message import StreamMessage as NativeMessage
|
|
14
15
|
from faststream.response import Response, ensure_response
|
|
16
|
+
from starlette.datastructures import Headers
|
|
17
|
+
from starlette.responses import Response as HTTPResponse
|
|
18
|
+
from starlette.responses import StreamingResponse
|
|
19
|
+
from starlette.types import Message, Scope
|
|
15
20
|
|
|
16
21
|
from faststream_fastapi._internal.config import Config
|
|
17
22
|
from faststream_fastapi._internal.fastapi_compat import (
|
|
@@ -25,6 +30,7 @@ from faststream_fastapi._internal.get_dependant import (
|
|
|
25
30
|
get_fastapi_native_dependant,
|
|
26
31
|
has_forbidden_types,
|
|
27
32
|
is_faststream_decorated,
|
|
33
|
+
iter_dependants,
|
|
28
34
|
mark_faststream_decorated,
|
|
29
35
|
)
|
|
30
36
|
from faststream_fastapi._internal.replace_context import replace_context
|
|
@@ -77,46 +83,44 @@ def build_faststream_to_fastapi_parser(
|
|
|
77
83
|
config=config,
|
|
78
84
|
)
|
|
79
85
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
first_arg = next(
|
|
83
|
-
dropwhile(
|
|
84
|
-
lambda i: i in dependencies_names,
|
|
85
|
-
inspect.signature(dependent.call).parameters,
|
|
86
|
-
),
|
|
87
|
-
None,
|
|
88
|
-
)
|
|
86
|
+
first_arg = _get_scalar_payload_alias(dependent)
|
|
89
87
|
|
|
90
88
|
async def parsed_consumer(message: NativeMessage[Any]) -> Any:
|
|
91
89
|
body = await message.decode()
|
|
92
90
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
path = fastapi_body = body or {}
|
|
98
|
-
elif isinstance(body, list):
|
|
99
|
-
fastapi_body, path = body, {}
|
|
100
|
-
else:
|
|
101
|
-
path = fastapi_body = {first_arg: body}
|
|
102
|
-
|
|
103
|
-
stream_message = StreamMessage(
|
|
104
|
-
body=fastapi_body,
|
|
105
|
-
headers={"context__": context, **message.headers},
|
|
106
|
-
path={**path, **message.path},
|
|
107
|
-
)
|
|
108
|
-
|
|
91
|
+
if isinstance(body, dict):
|
|
92
|
+
path = body
|
|
93
|
+
elif first_arg is not None and not isinstance(body, list):
|
|
94
|
+
path = {first_arg: body}
|
|
109
95
|
else:
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
96
|
+
path = {}
|
|
97
|
+
|
|
98
|
+
stream_message = StreamMessage(
|
|
99
|
+
body=body,
|
|
100
|
+
headers=message.headers,
|
|
101
|
+
path={**path, **message.path},
|
|
102
|
+
raw_body=message.body if isinstance(message.body, bytes) else None,
|
|
103
|
+
)
|
|
104
|
+
stream_message.scope["faststream_context__"] = context
|
|
105
|
+
stream_message.scope["faststream_config__"] = config
|
|
115
106
|
return await consume(stream_message, message)
|
|
116
107
|
|
|
117
108
|
return parsed_consumer
|
|
118
109
|
|
|
119
110
|
|
|
111
|
+
def _get_scalar_payload_alias(dependant: FastAPIDependant) -> str | None:
|
|
112
|
+
for dependency in iter_dependants(dependant):
|
|
113
|
+
fields = {
|
|
114
|
+
field.name: field.alias
|
|
115
|
+
for field in (*dependency.query_params, *dependency.path_params)
|
|
116
|
+
}
|
|
117
|
+
if fields and dependency.call is not None:
|
|
118
|
+
for name in inspect.signature(dependency.call).parameters:
|
|
119
|
+
if name in fields:
|
|
120
|
+
return fields[name]
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
120
124
|
def make_fastapi_execution(
|
|
121
125
|
*,
|
|
122
126
|
dependent: FastAPIDependant,
|
|
@@ -146,7 +150,7 @@ def make_fastapi_execution(
|
|
|
146
150
|
request.scope["fastapi_astack"] = stack
|
|
147
151
|
|
|
148
152
|
request.scope["app"] = config.application
|
|
149
|
-
request.scope["state"] = config.asgi_state
|
|
153
|
+
request.scope["state"] = config.asgi_state.copy()
|
|
150
154
|
|
|
151
155
|
solved_result = await solve_faststream_dependency(
|
|
152
156
|
request=request,
|
|
@@ -158,7 +162,7 @@ def make_fastapi_execution(
|
|
|
158
162
|
raw_message.background = solved_result.background_tasks # type: ignore[attr-defined]
|
|
159
163
|
|
|
160
164
|
if solved_result.errors:
|
|
161
|
-
raise_fastapi_validation_error(solved_result.errors, request.
|
|
165
|
+
raise_fastapi_validation_error(solved_result.errors, request.decoded_body)
|
|
162
166
|
|
|
163
167
|
function_result = await run_endpoint_function(
|
|
164
168
|
dependant=dependent,
|
|
@@ -166,7 +170,22 @@ def make_fastapi_execution(
|
|
|
166
170
|
is_coroutine=is_coroutine,
|
|
167
171
|
)
|
|
168
172
|
|
|
173
|
+
if isinstance(function_result, HTTPResponse):
|
|
174
|
+
raw_message.background = ( # type: ignore[attr-defined]
|
|
175
|
+
function_result.background or solved_result.background_tasks
|
|
176
|
+
)
|
|
177
|
+
return await _to_broker_response(
|
|
178
|
+
function_result,
|
|
179
|
+
request.scope,
|
|
180
|
+
config.max_streaming_reply_size,
|
|
181
|
+
)
|
|
182
|
+
|
|
169
183
|
response = ensure_response(function_result)
|
|
184
|
+
if solved_result.response.raw_headers:
|
|
185
|
+
response.headers = {
|
|
186
|
+
**_broker_headers(solved_result.response.headers),
|
|
187
|
+
**response.headers,
|
|
188
|
+
}
|
|
170
189
|
|
|
171
190
|
response.body = await serialize_response(
|
|
172
191
|
response_content=response.body,
|
|
@@ -178,3 +197,61 @@ def make_fastapi_execution(
|
|
|
178
197
|
raise AssertionError("unreachable")
|
|
179
198
|
|
|
180
199
|
return app
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
async def _to_broker_response(
|
|
203
|
+
response: HTTPResponse,
|
|
204
|
+
scope: Scope,
|
|
205
|
+
max_streaming_reply_size: int,
|
|
206
|
+
) -> Response:
|
|
207
|
+
if hasattr(response, "body"):
|
|
208
|
+
return Response(bytes(response.body), headers=_broker_headers(response.headers))
|
|
209
|
+
|
|
210
|
+
# A broker reply carries one payload. Collect the ASGI stream before publishing it.
|
|
211
|
+
payload = bytearray()
|
|
212
|
+
headers: dict[str, str] = {}
|
|
213
|
+
finished = Event()
|
|
214
|
+
|
|
215
|
+
async def receive() -> Message:
|
|
216
|
+
await finished.wait()
|
|
217
|
+
return {"type": "http.disconnect"}
|
|
218
|
+
|
|
219
|
+
async def send(message: Message) -> None:
|
|
220
|
+
nonlocal headers
|
|
221
|
+
if message["type"] == "http.response.start":
|
|
222
|
+
headers = _broker_headers(Headers(raw=message["headers"]))
|
|
223
|
+
elif message["type"] == "http.response.body":
|
|
224
|
+
chunk = message.get("body", b"")
|
|
225
|
+
chunk_size = chunk.nbytes if isinstance(chunk, memoryview) else len(chunk)
|
|
226
|
+
if len(payload) + chunk_size > max_streaming_reply_size:
|
|
227
|
+
msg = f"Broker reply exceeds the {max_streaming_reply_size}-byte streaming limit."
|
|
228
|
+
raise ValueError(msg)
|
|
229
|
+
payload.extend(chunk)
|
|
230
|
+
if not message.get("more_body", False):
|
|
231
|
+
finished.set()
|
|
232
|
+
|
|
233
|
+
# The broker middleware runs the original background task after processing.
|
|
234
|
+
stream = copy(response)
|
|
235
|
+
stream.background = None
|
|
236
|
+
try:
|
|
237
|
+
await stream({**scope, "asgi": {"version": "3.0", "spec_version": "2.4"}}, receive, send)
|
|
238
|
+
finally:
|
|
239
|
+
if isinstance(stream, StreamingResponse) and isinstance(
|
|
240
|
+
stream.body_iterator,
|
|
241
|
+
AsyncGenerator,
|
|
242
|
+
):
|
|
243
|
+
await stream.body_iterator.aclose()
|
|
244
|
+
return Response(bytes(payload), headers=headers)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _broker_headers(headers: Headers) -> dict[str, str]:
|
|
248
|
+
result: dict[str, str] = {}
|
|
249
|
+
for name, value in headers.items():
|
|
250
|
+
if name not in result:
|
|
251
|
+
result[name] = value
|
|
252
|
+
elif name == "set-cookie":
|
|
253
|
+
msg = "Broker response headers cannot represent multiple Set-Cookie values."
|
|
254
|
+
raise ValueError(msg)
|
|
255
|
+
else:
|
|
256
|
+
result[name] += ", " + value
|
|
257
|
+
return result
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from fastapi import Request, params
|
|
5
|
+
|
|
6
|
+
from faststream_fastapi._internal.config import Config
|
|
7
|
+
from faststream_fastapi._internal.fs_re_exports.constants import EMPTY
|
|
8
|
+
from faststream_fastapi._internal.fs_re_exports.context import (
|
|
9
|
+
ContextRepo,
|
|
10
|
+
resolve_context_by_name,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def Context( # noqa: N802
|
|
15
|
+
name: str = "",
|
|
16
|
+
*,
|
|
17
|
+
default: Any = EMPTY,
|
|
18
|
+
initial: Callable[..., Any] | None = None,
|
|
19
|
+
) -> Any:
|
|
20
|
+
def solve_context(request: Request) -> Any:
|
|
21
|
+
context: ContextRepo = request.scope["faststream_context__"]
|
|
22
|
+
try:
|
|
23
|
+
return context.resolve(name)
|
|
24
|
+
except (KeyError, AttributeError):
|
|
25
|
+
if EMPTY != default or initial is None: # noqa: SIM300
|
|
26
|
+
return default
|
|
27
|
+
|
|
28
|
+
config: Config = request.scope["faststream_config__"]
|
|
29
|
+
# FastAPI runs sync dependencies in worker threads. Recheck under the lock
|
|
30
|
+
# so concurrent subscribers reuse the first value initialized by the application.
|
|
31
|
+
with config.context_init_lock:
|
|
32
|
+
return resolve_context_by_name(
|
|
33
|
+
name=name,
|
|
34
|
+
default=default,
|
|
35
|
+
initial=initial,
|
|
36
|
+
context=config.context,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
return params.Depends(solve_context, use_cache=True)
|
{faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/faststream_api.py
RENAMED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import traceback
|
|
2
|
-
from collections.abc import
|
|
3
|
-
from contextlib import asynccontextmanager
|
|
4
|
-
from
|
|
2
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable
|
|
3
|
+
from contextlib import AsyncExitStack, asynccontextmanager
|
|
4
|
+
from logging import getLogger
|
|
5
|
+
from typing import Any, Self
|
|
6
|
+
from weakref import WeakSet
|
|
5
7
|
|
|
6
8
|
from fastapi import FastAPI
|
|
7
9
|
from fastapi.params import Depends
|
|
10
|
+
from faststream._internal.endpoint.subscriber.usecase import SubscriberUsecase
|
|
8
11
|
from faststream.message import StreamMessage
|
|
9
12
|
from faststream.specification.base import SpecificationFactory
|
|
10
13
|
from starlette.types import Receive, Scope, Send
|
|
@@ -22,6 +25,8 @@ from faststream_fastapi._internal.wrap_callable_to_fastapi_compatible import (
|
|
|
22
25
|
)
|
|
23
26
|
from faststream_fastapi.asyncapi_config import AsyncAPIConfig
|
|
24
27
|
|
|
28
|
+
_logger = getLogger(__name__)
|
|
29
|
+
|
|
25
30
|
|
|
26
31
|
def _subscriber_compatibility_wrapper(
|
|
27
32
|
config: Config,
|
|
@@ -41,19 +46,34 @@ def _subscriber_compatibility_wrapper(
|
|
|
41
46
|
return subscriber_compatibility_wrapper
|
|
42
47
|
|
|
43
48
|
|
|
49
|
+
async def _default_connection_hook(broker: BrokerUsecase[Any, Any]) -> None:
|
|
50
|
+
await broker.start()
|
|
51
|
+
|
|
52
|
+
|
|
44
53
|
class FastStreamAPI:
|
|
45
54
|
def __init__(
|
|
46
55
|
self,
|
|
47
56
|
*brokers: BrokerUsecase[Any, Any],
|
|
48
57
|
application: FastAPI,
|
|
49
58
|
context: ContextRepo | None = None,
|
|
59
|
+
max_streaming_reply_size: int = 1024 * 1024,
|
|
50
60
|
# AsyncAPI
|
|
51
61
|
specification: SpecificationFactory | None = None,
|
|
52
62
|
asyncapi_path: str | AsyncAPIConfig | None = None,
|
|
63
|
+
# Low API
|
|
64
|
+
safe_connection: bool = False,
|
|
65
|
+
connection_hook: Callable[[Any], Awaitable[None]] | None = None,
|
|
53
66
|
) -> None:
|
|
67
|
+
if max_streaming_reply_size <= 0:
|
|
68
|
+
msg = "max_streaming_reply_size must be positive."
|
|
69
|
+
raise ValueError(msg)
|
|
70
|
+
|
|
54
71
|
self._application = application
|
|
55
72
|
|
|
56
73
|
self._brokers = brokers
|
|
74
|
+
self._patched_subscribers: WeakSet[SubscriberUsecase[Any]] = WeakSet()
|
|
75
|
+
self._patched_brokers: list[BrokerUsecase[Any, Any]] = []
|
|
76
|
+
self._asyncapi_router_added = False
|
|
57
77
|
|
|
58
78
|
self._startable_application = StartAbleApplication(
|
|
59
79
|
*brokers,
|
|
@@ -63,10 +83,13 @@ class FastStreamAPI:
|
|
|
63
83
|
context=context or ContextRepo(),
|
|
64
84
|
),
|
|
65
85
|
)
|
|
86
|
+
self._startable_application.config.context.set_global("app", self)
|
|
66
87
|
|
|
67
88
|
self._config = Config(
|
|
68
89
|
application=application,
|
|
69
90
|
dependency_overrides_provider=self._application,
|
|
91
|
+
context=self._startable_application.context,
|
|
92
|
+
max_streaming_reply_size=max_streaming_reply_size,
|
|
70
93
|
)
|
|
71
94
|
|
|
72
95
|
if asyncapi_path is not None:
|
|
@@ -79,29 +102,31 @@ class FastStreamAPI:
|
|
|
79
102
|
asyncapi_config = None
|
|
80
103
|
|
|
81
104
|
self._asyncapi_config = asyncapi_config
|
|
105
|
+
self._safe_connection = safe_connection
|
|
82
106
|
|
|
83
|
-
|
|
84
|
-
|
|
107
|
+
if connection_hook is None:
|
|
108
|
+
connection_hook = _default_connection_hook
|
|
85
109
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
)
|
|
91
|
-
subscriber._call_decorators = (
|
|
92
|
-
_subscriber_compatibility_wrapper(
|
|
93
|
-
config=self._config,
|
|
94
|
-
context=self._startable_application.context,
|
|
95
|
-
dependencies=dependencies, # type: ignore[arg-type]
|
|
96
|
-
),
|
|
97
|
-
*subscriber._call_decorators,
|
|
98
|
-
)
|
|
110
|
+
self._connection_hook = connection_hook
|
|
111
|
+
|
|
112
|
+
for broker in self._brokers:
|
|
113
|
+
self._patch_broker(broker)
|
|
99
114
|
|
|
100
115
|
# For FastStream docs gen
|
|
101
116
|
@property
|
|
102
117
|
def schema(self) -> SpecificationFactory:
|
|
118
|
+
for broker in self._brokers:
|
|
119
|
+
self._patch_broker(broker)
|
|
103
120
|
return self._startable_application.schema
|
|
104
121
|
|
|
122
|
+
@property
|
|
123
|
+
def broker(self) -> BrokerUsecase[Any, Any] | None:
|
|
124
|
+
return self._startable_application.broker
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def brokers(self) -> list[BrokerUsecase[Any, Any]]:
|
|
128
|
+
return self._startable_application.brokers
|
|
129
|
+
|
|
105
130
|
@property
|
|
106
131
|
def context(self) -> ContextRepo:
|
|
107
132
|
return self._startable_application.context
|
|
@@ -120,10 +145,7 @@ class FastStreamAPI:
|
|
|
120
145
|
app: Any = scope.get("app")
|
|
121
146
|
await receive()
|
|
122
147
|
try:
|
|
123
|
-
async with (
|
|
124
|
-
self._application.router.lifespan_context(app) as maybe_state,
|
|
125
|
-
self._lifespan_context(app),
|
|
126
|
-
):
|
|
148
|
+
async with self._application.router.lifespan_context(app) as maybe_state:
|
|
127
149
|
if maybe_state is not None:
|
|
128
150
|
if "state" not in scope:
|
|
129
151
|
msg = 'The server does not support "state" in the lifespan scope.'
|
|
@@ -131,9 +153,11 @@ class FastStreamAPI:
|
|
|
131
153
|
|
|
132
154
|
scope["state"].update(maybe_state)
|
|
133
155
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
156
|
+
self._config.asgi_state = scope.get("state", {})
|
|
157
|
+
async with self._lifespan_context(app):
|
|
158
|
+
await send({"type": "lifespan.startup.complete"})
|
|
159
|
+
started = True
|
|
160
|
+
await receive()
|
|
137
161
|
except BaseException:
|
|
138
162
|
exc_text = traceback.format_exc()
|
|
139
163
|
if started:
|
|
@@ -145,23 +169,51 @@ class FastStreamAPI:
|
|
|
145
169
|
await send({"type": "lifespan.shutdown.complete"})
|
|
146
170
|
|
|
147
171
|
@asynccontextmanager
|
|
148
|
-
async def _lifespan_context(self, application:
|
|
149
|
-
if self._asyncapi_config is not None:
|
|
172
|
+
async def _lifespan_context(self, application: Self) -> AsyncGenerator[None, None]:
|
|
173
|
+
if self._asyncapi_config is not None and not self._asyncapi_router_added:
|
|
150
174
|
asyncapi_router = AsyncAPIRouter(
|
|
151
175
|
brokers=self._brokers,
|
|
152
176
|
config=self._asyncapi_config,
|
|
153
|
-
schema=self.
|
|
177
|
+
schema=self.schema,
|
|
154
178
|
)
|
|
155
179
|
self._application.include_router(asyncapi_router)
|
|
180
|
+
self._asyncapi_router_added = True
|
|
156
181
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
try:
|
|
182
|
+
async with AsyncExitStack() as stack:
|
|
160
183
|
for broker in self._brokers:
|
|
161
|
-
|
|
162
|
-
|
|
184
|
+
self._patch_broker(broker)
|
|
185
|
+
stack.push_async_callback(broker.stop)
|
|
186
|
+
await self._connect_broker(broker)
|
|
163
187
|
|
|
164
188
|
yield None
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
189
|
+
|
|
190
|
+
def _patch_broker(self, broker: BrokerUsecase[Any, Any]) -> None:
|
|
191
|
+
if broker not in self._patched_brokers:
|
|
192
|
+
broker.config.add_middleware(_BackgroundMiddleware)
|
|
193
|
+
self._patched_brokers.append(broker)
|
|
194
|
+
|
|
195
|
+
for subscriber in broker.subscribers:
|
|
196
|
+
if subscriber in self._patched_subscribers:
|
|
197
|
+
continue
|
|
198
|
+
|
|
199
|
+
dependencies = (
|
|
200
|
+
*broker.config.broker_dependencies,
|
|
201
|
+
*subscriber._call_options.dependencies,
|
|
202
|
+
)
|
|
203
|
+
subscriber._call_decorators = (
|
|
204
|
+
_subscriber_compatibility_wrapper(
|
|
205
|
+
config=self._config,
|
|
206
|
+
context=broker.context,
|
|
207
|
+
dependencies=dependencies, # type: ignore[arg-type]
|
|
208
|
+
),
|
|
209
|
+
*subscriber._call_decorators,
|
|
210
|
+
)
|
|
211
|
+
self._patched_subscribers.add(subscriber)
|
|
212
|
+
|
|
213
|
+
async def _connect_broker(self, broker: BrokerUsecase[Any, Any]) -> None:
|
|
214
|
+
try:
|
|
215
|
+
await self._connection_hook(broker)
|
|
216
|
+
except Exception as error:
|
|
217
|
+
if self._safe_connection:
|
|
218
|
+
raise
|
|
219
|
+
_logger.warning("The start to broker %r was unsuccessful.", broker, exc_info=error)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from fastapi import Request
|
|
4
|
+
from fastapi.encoders import jsonable_encoder
|
|
5
|
+
from starlette.datastructures import Headers
|
|
6
|
+
from starlette.types import Message, Scope
|
|
7
|
+
from typing_extensions import override
|
|
8
|
+
|
|
9
|
+
from faststream_fastapi._internal.fs_re_exports._compat import json_dumps
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _MessageHeaders(Headers):
|
|
13
|
+
"""Expose broker header text (including Unicode) through the Starlette header interface."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, headers: dict[str, Any]) -> None:
|
|
16
|
+
raw: list[tuple[bytes, bytes]] = []
|
|
17
|
+
for name, value in headers.items():
|
|
18
|
+
values = value if isinstance(value, (list, tuple)) else (value,)
|
|
19
|
+
raw.extend(
|
|
20
|
+
(name.lower().encode(), item if isinstance(item, bytes) else str(item).encode())
|
|
21
|
+
for item in values
|
|
22
|
+
)
|
|
23
|
+
super().__init__(raw=raw)
|
|
24
|
+
|
|
25
|
+
@override
|
|
26
|
+
def __getitem__(self, key: str) -> str:
|
|
27
|
+
key_bytes = key.lower().encode()
|
|
28
|
+
for name, value in self._list:
|
|
29
|
+
if name == key_bytes:
|
|
30
|
+
return value.decode("utf-8", "surrogateescape")
|
|
31
|
+
raise KeyError(key)
|
|
32
|
+
|
|
33
|
+
@override
|
|
34
|
+
def __contains__(self, key: Any) -> bool:
|
|
35
|
+
return bool(self.getlist(key))
|
|
36
|
+
|
|
37
|
+
@override
|
|
38
|
+
def keys(self) -> list[str]: # type: ignore[override]
|
|
39
|
+
return [name.decode() for name, _ in self._list]
|
|
40
|
+
|
|
41
|
+
@override
|
|
42
|
+
def getlist(self, key: str) -> list[str]:
|
|
43
|
+
key_bytes = key.lower().encode()
|
|
44
|
+
return [v.decode("utf-8", "surrogateescape") for k, v in self._list if k == key_bytes]
|
|
45
|
+
|
|
46
|
+
@override
|
|
47
|
+
def items(self) -> list[tuple[str, str]]: # type: ignore[override]
|
|
48
|
+
return [
|
|
49
|
+
(key.decode(), value.decode("utf-8", "surrogateescape")) for key, value in self._list
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
@override
|
|
53
|
+
def values(self) -> list[str]: # type: ignore[override]
|
|
54
|
+
return [value.decode("utf-8", "surrogateescape") for _, value in self._list]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class StreamMessage(Request):
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
*,
|
|
61
|
+
body: Any,
|
|
62
|
+
headers: dict[str, Any],
|
|
63
|
+
path: dict[str, Any],
|
|
64
|
+
raw_body: bytes | None = None,
|
|
65
|
+
) -> None:
|
|
66
|
+
message_headers = _MessageHeaders(headers)
|
|
67
|
+
scope: Scope = {
|
|
68
|
+
"type": "http",
|
|
69
|
+
"method": "POST",
|
|
70
|
+
"path": "/",
|
|
71
|
+
"root_path": "",
|
|
72
|
+
"scheme": "http",
|
|
73
|
+
"query_string": b"",
|
|
74
|
+
"headers": message_headers.raw,
|
|
75
|
+
"path_params": path,
|
|
76
|
+
}
|
|
77
|
+
consumed = False
|
|
78
|
+
|
|
79
|
+
async def receive() -> Message:
|
|
80
|
+
nonlocal consumed
|
|
81
|
+
if consumed:
|
|
82
|
+
return {"type": "http.disconnect"}
|
|
83
|
+
consumed = True
|
|
84
|
+
data = raw_body if raw_body is not None else json_dumps(jsonable_encoder(body))
|
|
85
|
+
return {"type": "http.request", "body": data}
|
|
86
|
+
|
|
87
|
+
super().__init__(scope, receive)
|
|
88
|
+
self._headers = message_headers
|
|
89
|
+
self.decoded_body = body
|
|
90
|
+
self._query_params = path # type: ignore[assignment]
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
from dataclasses import dataclass
|
|
2
|
-
from typing import Any
|
|
3
|
-
|
|
4
|
-
from fastapi import FastAPI
|
|
5
|
-
from fastapi.datastructures import State
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class ConfigAsgiStateError(ValueError):
|
|
9
|
-
def __str__(self) -> str:
|
|
10
|
-
return "ASGI state already is set"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
@dataclass
|
|
14
|
-
class Config:
|
|
15
|
-
application: FastAPI
|
|
16
|
-
dependency_overrides_provider: Any | None
|
|
17
|
-
asgi_state: State | None = None
|
|
18
|
-
|
|
19
|
-
def set_asgi_state(self, asgi_state: State) -> None:
|
|
20
|
-
if self.asgi_state is not None:
|
|
21
|
-
raise ConfigAsgiStateError # pragma: no cover
|
|
22
|
-
|
|
23
|
-
self.asgi_state = asgi_state
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
from collections.abc import Callable
|
|
2
|
-
from typing import Annotated, Any
|
|
3
|
-
|
|
4
|
-
from fastapi import params
|
|
5
|
-
|
|
6
|
-
from faststream_fastapi._internal.fs_re_exports.constants import EMPTY
|
|
7
|
-
from faststream_fastapi._internal.fs_re_exports.context import (
|
|
8
|
-
resolve_context_by_name,
|
|
9
|
-
)
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def Context( # noqa: N802
|
|
13
|
-
name: str = "",
|
|
14
|
-
*,
|
|
15
|
-
default: Any = EMPTY,
|
|
16
|
-
initial: Callable[..., Any] | None = None,
|
|
17
|
-
) -> Any:
|
|
18
|
-
def solve_context(
|
|
19
|
-
context: Annotated[
|
|
20
|
-
Any,
|
|
21
|
-
params.Header(alias="context__", include_in_schema=False),
|
|
22
|
-
],
|
|
23
|
-
) -> Any:
|
|
24
|
-
return resolve_context_by_name(
|
|
25
|
-
name=name,
|
|
26
|
-
default=default,
|
|
27
|
-
initial=initial,
|
|
28
|
-
context=context,
|
|
29
|
-
)
|
|
30
|
-
|
|
31
|
-
return params.Depends(solve_context, use_cache=True)
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
from typing import Any
|
|
2
|
-
|
|
3
|
-
from fastapi import Request
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class StreamMessage(Request):
|
|
7
|
-
scope: dict[str, Any]
|
|
8
|
-
_cookies: dict[str, Any]
|
|
9
|
-
_headers: dict[str, Any] # type: ignore[assignment]
|
|
10
|
-
_body: dict[str, Any] | list[Any] # type: ignore[assignment]
|
|
11
|
-
_query_params: dict[str, Any] # type: ignore[assignment]
|
|
12
|
-
|
|
13
|
-
def __init__(
|
|
14
|
-
self,
|
|
15
|
-
*,
|
|
16
|
-
body: dict[str, Any] | list[Any],
|
|
17
|
-
headers: dict[str, Any],
|
|
18
|
-
path: dict[str, Any],
|
|
19
|
-
) -> None:
|
|
20
|
-
self._headers = headers
|
|
21
|
-
self._body = body
|
|
22
|
-
self._query_params = path
|
|
23
|
-
|
|
24
|
-
self.scope = {"path_params": self._query_params}
|
|
25
|
-
self._cookies = {}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/_internal/logger.py
RENAMED
|
File without changes
|
{faststream_fastapi-1.3.1 → faststream_fastapi-1.5.0}/src/faststream_fastapi/asyncapi_config.py
RENAMED
|
File without changes
|
|
File without changes
|