lite-bootstrap 1.16.0__tar.gz → 2.0.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.
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/PKG-INFO +19 -19
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/README.md +4 -0
- lite_bootstrap-2.0.0/lite_bootstrap/__init__.py +70 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/base.py +39 -7
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/fastapi_bootstrapper.py +142 -61
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/fastmcp_bootstrapper.py +180 -68
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/faststream_bootstrapper.py +71 -35
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/free_bootstrapper.py +1 -11
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/litestar_bootstrapper.py +199 -56
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/exceptions.py +5 -8
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/fastapi_helpers.py +32 -26
- lite_bootstrap-2.0.0/lite_bootstrap/helpers/opentelemetry_asgi.py +35 -0
- lite_bootstrap-2.0.0/lite_bootstrap/helpers/starlette_sentry.py +204 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/warn.py +0 -24
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/import_checker.py +3 -5
- lite_bootstrap-2.0.0/lite_bootstrap/instruments/base.py +63 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/cors_instrument.py +1 -1
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/healthchecks_instrument.py +13 -4
- lite_bootstrap-2.0.0/lite_bootstrap/instruments/logging_factory.py +75 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/logging_instrument.py +57 -69
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/opentelemetry_instrument.py +149 -77
- lite_bootstrap-2.0.0/lite_bootstrap/instruments/prometheus_instrument.py +55 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/pyroscope_instrument.py +7 -6
- lite_bootstrap-2.0.0/lite_bootstrap/instruments/sentry_instrument.py +374 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/pyproject.toml +16 -24
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/pyproject.toml.orig +31 -44
- lite_bootstrap-1.16.0/lite_bootstrap/__init__.py +0 -46
- lite_bootstrap-1.16.0/lite_bootstrap/instruments/base.py +0 -103
- lite_bootstrap-1.16.0/lite_bootstrap/instruments/logging_factory.py +0 -168
- lite_bootstrap-1.16.0/lite_bootstrap/instruments/prometheus_instrument.py +0 -27
- lite_bootstrap-1.16.0/lite_bootstrap/instruments/sentry_instrument.py +0 -164
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/__init__.py +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/__init__.py +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/path.py +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/__init__.py +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/swagger_instrument.py +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/py.typed +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/fastapi_docs/redoc.standalone.js +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/fastapi_docs/swagger-ui-bundle.js +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/fastapi_docs/swagger-ui.css +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/asyncapi-web-component.js +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/default.min.css +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/swagger-ui-bundle.js +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/swagger-ui-standalone-preset.js +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/swagger-ui.css +0 -0
- {lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/types.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lite-bootstrap
|
|
3
|
-
Version:
|
|
3
|
+
Version: 2.0.0
|
|
4
4
|
Summary: Lightweight bootstrap for production-ready Python microservices
|
|
5
5
|
Keywords: microservices,bootstrap,opentelemetry,sentry,prometheus,healthcheck,fastapi,litestar,faststream,structlog,fastmcp,python
|
|
6
6
|
Author: Artur Shiriev
|
|
@@ -26,27 +26,26 @@ Requires-Dist: prometheus-fastapi-instrumentator>=8.0.1 ; extra == 'fastapi-metr
|
|
|
26
26
|
Requires-Dist: fastapi>=0.133 ; extra == 'fastapi-metrics'
|
|
27
27
|
Requires-Dist: typing-extensions>=4.12 ; extra == 'fastapi-metrics'
|
|
28
28
|
Requires-Dist: lite-bootstrap[fastapi,otl] ; extra == 'fastapi-otl'
|
|
29
|
-
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.
|
|
29
|
+
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.63b0 ; extra == 'fastapi-otl'
|
|
30
30
|
Requires-Dist: lite-bootstrap[fastapi,sentry] ; extra == 'fastapi-sentry'
|
|
31
|
-
Requires-Dist: fastmcp>=
|
|
31
|
+
Requires-Dist: fastmcp>=4.0,<5 ; extra == 'fastmcp'
|
|
32
32
|
Requires-Dist: typing-extensions>=4.15 ; extra == 'fastmcp'
|
|
33
33
|
Requires-Dist: lite-bootstrap[fastmcp,fastmcp-otl,fastmcp-metrics,sentry,logging,pyroscope] ; extra == 'fastmcp-all'
|
|
34
34
|
Requires-Dist: lite-bootstrap[fastmcp] ; extra == 'fastmcp-metrics'
|
|
35
35
|
Requires-Dist: prometheus-client>=0.20 ; extra == 'fastmcp-metrics'
|
|
36
36
|
Requires-Dist: prometheus-fastapi-instrumentator>=8.0.1 ; extra == 'fastmcp-metrics'
|
|
37
37
|
Requires-Dist: lite-bootstrap[fastmcp,otl] ; extra == 'fastmcp-otl'
|
|
38
|
-
Requires-Dist: opentelemetry-instrumentation-asgi>=0.
|
|
38
|
+
Requires-Dist: opentelemetry-instrumentation-asgi>=0.63b0 ; extra == 'fastmcp-otl'
|
|
39
39
|
Requires-Dist: faststream>=0.6 ; extra == 'faststream'
|
|
40
40
|
Requires-Dist: typing-extensions>=4.12.2 ; extra == 'faststream'
|
|
41
41
|
Requires-Dist: lite-bootstrap[faststream-sentry,faststream-otl,faststream-logging,faststream-metrics,pyroscope] ; extra == 'faststream-all'
|
|
42
|
-
Requires-Dist: lite-bootstrap[sentry,otl,logging,faststream,faststream-metrics,pyroscope] ; extra == 'faststream-all'
|
|
43
42
|
Requires-Dist: lite-bootstrap[faststream,logging] ; extra == 'faststream-logging'
|
|
44
43
|
Requires-Dist: lite-bootstrap[faststream] ; extra == 'faststream-metrics'
|
|
45
44
|
Requires-Dist: prometheus-client>=0.20 ; extra == 'faststream-metrics'
|
|
46
45
|
Requires-Dist: lite-bootstrap[faststream,otl] ; extra == 'faststream-otl'
|
|
47
46
|
Requires-Dist: lite-bootstrap[faststream,sentry] ; extra == 'faststream-sentry'
|
|
48
47
|
Requires-Dist: lite-bootstrap[sentry,otl,logging,pyroscope] ; extra == 'free-all'
|
|
49
|
-
Requires-Dist: litestar>=2.
|
|
48
|
+
Requires-Dist: litestar>=2.22 ; extra == 'litestar'
|
|
50
49
|
Requires-Dist: typing-extensions>=4.12 ; extra == 'litestar'
|
|
51
50
|
Requires-Dist: lite-bootstrap[litestar-sentry,litestar-otl,litestar-logging,litestar-metrics,pyroscope] ; extra == 'litestar-all'
|
|
52
51
|
Requires-Dist: lite-bootstrap[litestar,logging] ; extra == 'litestar-logging'
|
|
@@ -54,23 +53,20 @@ Requires-Dist: structlog>=23.2 ; extra == 'litestar-logging'
|
|
|
54
53
|
Requires-Dist: lite-bootstrap[litestar] ; extra == 'litestar-metrics'
|
|
55
54
|
Requires-Dist: prometheus-client>=0.20 ; extra == 'litestar-metrics'
|
|
56
55
|
Requires-Dist: lite-bootstrap[litestar,otl] ; extra == 'litestar-otl'
|
|
57
|
-
Requires-Dist:
|
|
58
|
-
Requires-Dist: opentelemetry-instrumentation-asgi>=0.49b0 ; extra == 'litestar-otl'
|
|
56
|
+
Requires-Dist: opentelemetry-instrumentation-asgi>=0.63b0 ; extra == 'litestar-otl'
|
|
59
57
|
Requires-Dist: lite-bootstrap[litestar,sentry] ; extra == 'litestar-sentry'
|
|
60
58
|
Requires-Dist: structlog>=21.3 ; extra == 'logging'
|
|
61
59
|
Requires-Dist: orjson>=3.8.0 ; extra == 'orjson'
|
|
62
|
-
Requires-Dist: opentelemetry-api>=1.
|
|
63
|
-
Requires-Dist: opentelemetry-sdk>=1.
|
|
64
|
-
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.
|
|
65
|
-
Requires-Dist: opentelemetry-instrumentation>=0.
|
|
66
|
-
Requires-Dist: opentelemetry-api>=1.
|
|
67
|
-
Requires-Dist: opentelemetry-sdk>=1.
|
|
68
|
-
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.
|
|
69
|
-
Requires-Dist: opentelemetry-instrumentation>=0.
|
|
60
|
+
Requires-Dist: opentelemetry-api>=1.42 ; extra == 'otl'
|
|
61
|
+
Requires-Dist: opentelemetry-sdk>=1.42 ; extra == 'otl'
|
|
62
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.42 ; extra == 'otl'
|
|
63
|
+
Requires-Dist: opentelemetry-instrumentation>=0.63b0 ; extra == 'otl'
|
|
64
|
+
Requires-Dist: opentelemetry-api>=1.42 ; extra == 'otl-http'
|
|
65
|
+
Requires-Dist: opentelemetry-sdk>=1.42 ; extra == 'otl-http'
|
|
66
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.42 ; extra == 'otl-http'
|
|
67
|
+
Requires-Dist: opentelemetry-instrumentation>=0.63b0 ; extra == 'otl-http'
|
|
70
68
|
Requires-Dist: pyroscope-io>=1.0.1 ; extra == 'pyroscope'
|
|
71
|
-
Requires-Dist: sentry-sdk>=2.
|
|
72
|
-
Requires-Dist: sentry-sdk>=2.11,!=2.69.0,<3 ; python_full_version == '3.13.*' and extra == 'sentry'
|
|
73
|
-
Requires-Dist: sentry-sdk>=2.59,!=2.69.0,<3 ; python_full_version >= '3.14' and extra == 'sentry'
|
|
69
|
+
Requires-Dist: sentry-sdk>=2.70,<4 ; extra == 'sentry'
|
|
74
70
|
Requires-Python: >=3.11, <4
|
|
75
71
|
Project-URL: Homepage, https://lite-bootstrap.modern-python.org
|
|
76
72
|
Project-URL: Documentation, https://lite-bootstrap.modern-python.org
|
|
@@ -156,6 +152,7 @@ A few constraints that aren't obvious from the API:
|
|
|
156
152
|
- **One bootstrapper per application instance.** Constructing two `FastAPIBootstrapper`s around the same `fastapi.FastAPI` (or two `FastMcpBootstrapper`s around the same `FastMCP`) is not supported. The second bootstrapper warns at construction, and its `bootstrap()` raises `ConfigurationError`.
|
|
157
153
|
- **One `OpenTelemetryInstrument` per process.** `bootstrap()` calls `opentelemetry.trace.set_tracer_provider(...)`, which the OTel SDK enforces as set-once: later calls log a warning and have no effect. `teardown()` flushes spans and closes exporters but can't reset the process-global pointer.
|
|
158
154
|
- **`teardown()` is idempotent.** `BaseBootstrapper.teardown()` short-circuits if not bootstrapped; per-instrument teardown methods are safe to call multiple times.
|
|
155
|
+
- **Failed bootstrap is terminal.** If an instrument or application preparation raises, successfully started instruments are torn down in reverse order. Cleanup failures are attached as notes to the original exception. The bootstrapper cannot be reused, and a later `teardown()` does nothing. Rollback does not undo arbitrary changes made by the instrument that raised.
|
|
159
156
|
- **Partial teardown failures are aggregated.** If an instrument's teardown raises, the bootstrapper continues with the rest of the instruments and raises `TeardownError` at the end with all collected failures.
|
|
160
157
|
|
|
161
158
|
---
|
|
@@ -185,9 +182,12 @@ The following intentionally differ:
|
|
|
185
182
|
## Links
|
|
186
183
|
|
|
187
184
|
- [Documentation](https://lite-bootstrap.modern-python.org)
|
|
185
|
+
- [Upgrading to 2.x](https://lite-bootstrap.modern-python.org/migration/to-2.x/)
|
|
188
186
|
- [PyPI](https://pypi.org/project/lite-bootstrap)
|
|
189
187
|
- [License](https://github.com/modern-python/lite-bootstrap/blob/main/LICENSE)
|
|
190
188
|
|
|
189
|
+
If this project saves you time, consider giving it a star on GitHub.
|
|
190
|
+
|
|
191
191
|
## Part of `modern-python`
|
|
192
192
|
|
|
193
193
|
Browse the full list of templates and libraries in
|
|
@@ -46,6 +46,7 @@ A few constraints that aren't obvious from the API:
|
|
|
46
46
|
- **One bootstrapper per application instance.** Constructing two `FastAPIBootstrapper`s around the same `fastapi.FastAPI` (or two `FastMcpBootstrapper`s around the same `FastMCP`) is not supported. The second bootstrapper warns at construction, and its `bootstrap()` raises `ConfigurationError`.
|
|
47
47
|
- **One `OpenTelemetryInstrument` per process.** `bootstrap()` calls `opentelemetry.trace.set_tracer_provider(...)`, which the OTel SDK enforces as set-once: later calls log a warning and have no effect. `teardown()` flushes spans and closes exporters but can't reset the process-global pointer.
|
|
48
48
|
- **`teardown()` is idempotent.** `BaseBootstrapper.teardown()` short-circuits if not bootstrapped; per-instrument teardown methods are safe to call multiple times.
|
|
49
|
+
- **Failed bootstrap is terminal.** If an instrument or application preparation raises, successfully started instruments are torn down in reverse order. Cleanup failures are attached as notes to the original exception. The bootstrapper cannot be reused, and a later `teardown()` does nothing. Rollback does not undo arbitrary changes made by the instrument that raised.
|
|
49
50
|
- **Partial teardown failures are aggregated.** If an instrument's teardown raises, the bootstrapper continues with the rest of the instruments and raises `TeardownError` at the end with all collected failures.
|
|
50
51
|
|
|
51
52
|
---
|
|
@@ -75,9 +76,12 @@ The following intentionally differ:
|
|
|
75
76
|
## Links
|
|
76
77
|
|
|
77
78
|
- [Documentation](https://lite-bootstrap.modern-python.org)
|
|
79
|
+
- [Upgrading to 2.x](https://lite-bootstrap.modern-python.org/migration/to-2.x/)
|
|
78
80
|
- [PyPI](https://pypi.org/project/lite-bootstrap)
|
|
79
81
|
- [License](https://github.com/modern-python/lite-bootstrap/blob/main/LICENSE)
|
|
80
82
|
|
|
83
|
+
If this project saves you time, consider giving it a star on GitHub.
|
|
84
|
+
|
|
81
85
|
## Part of `modern-python`
|
|
82
86
|
|
|
83
87
|
Browse the full list of templates and libraries in
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
|
|
4
|
+
from lite_bootstrap.exceptions import (
|
|
5
|
+
BootstrapperNotReadyError,
|
|
6
|
+
ConfigurationError,
|
|
7
|
+
InstrumentDependencyMissingWarning,
|
|
8
|
+
LiteBootstrapError,
|
|
9
|
+
TeardownError,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
if typing.TYPE_CHECKING:
|
|
14
|
+
from lite_bootstrap.bootstrappers.fastapi_bootstrapper import FastAPIBootstrapper, FastAPIConfig
|
|
15
|
+
from lite_bootstrap.bootstrappers.fastmcp_bootstrapper import FastMcpBootstrapper, FastMcpConfig
|
|
16
|
+
from lite_bootstrap.bootstrappers.faststream_bootstrapper import FastStreamBootstrapper, FastStreamConfig
|
|
17
|
+
from lite_bootstrap.bootstrappers.free_bootstrapper import FreeBootstrapper, FreeConfig
|
|
18
|
+
from lite_bootstrap.bootstrappers.litestar_bootstrapper import LitestarBootstrapper, LitestarConfig
|
|
19
|
+
from lite_bootstrap.instruments.pyroscope_instrument import PyroscopeConfig, PyroscopeInstrument
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"BootstrapperNotReadyError",
|
|
24
|
+
"ConfigurationError",
|
|
25
|
+
"FastAPIBootstrapper",
|
|
26
|
+
"FastAPIConfig",
|
|
27
|
+
"FastMcpBootstrapper",
|
|
28
|
+
"FastMcpConfig",
|
|
29
|
+
"FastStreamBootstrapper",
|
|
30
|
+
"FastStreamConfig",
|
|
31
|
+
"FreeBootstrapper",
|
|
32
|
+
"FreeConfig",
|
|
33
|
+
"InstrumentDependencyMissingWarning",
|
|
34
|
+
"LiteBootstrapError",
|
|
35
|
+
"LitestarBootstrapper",
|
|
36
|
+
"LitestarConfig",
|
|
37
|
+
"PyroscopeConfig",
|
|
38
|
+
"PyroscopeInstrument",
|
|
39
|
+
"TeardownError",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_LAZY_EXPORTS = {
|
|
44
|
+
"FastAPIBootstrapper": "bootstrappers.fastapi_bootstrapper",
|
|
45
|
+
"FastAPIConfig": "bootstrappers.fastapi_bootstrapper",
|
|
46
|
+
"FastMcpBootstrapper": "bootstrappers.fastmcp_bootstrapper",
|
|
47
|
+
"FastMcpConfig": "bootstrappers.fastmcp_bootstrapper",
|
|
48
|
+
"FastStreamBootstrapper": "bootstrappers.faststream_bootstrapper",
|
|
49
|
+
"FastStreamConfig": "bootstrappers.faststream_bootstrapper",
|
|
50
|
+
"FreeBootstrapper": "bootstrappers.free_bootstrapper",
|
|
51
|
+
"FreeConfig": "bootstrappers.free_bootstrapper",
|
|
52
|
+
"LitestarBootstrapper": "bootstrappers.litestar_bootstrapper",
|
|
53
|
+
"LitestarConfig": "bootstrappers.litestar_bootstrapper",
|
|
54
|
+
"PyroscopeConfig": "instruments.pyroscope_instrument",
|
|
55
|
+
"PyroscopeInstrument": "instruments.pyroscope_instrument",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def __getattr__(name: str) -> typing.Any: # noqa: ANN401
|
|
60
|
+
module_name = _LAZY_EXPORTS.get(name)
|
|
61
|
+
if module_name is None:
|
|
62
|
+
msg = f"module {__name__!r} has no attribute {name!r}"
|
|
63
|
+
raise AttributeError(msg)
|
|
64
|
+
exported = getattr(import_module(f".{module_name}", __name__), name)
|
|
65
|
+
globals()[name] = exported
|
|
66
|
+
return exported
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def __dir__() -> list[str]:
|
|
70
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import abc
|
|
2
|
+
import contextlib
|
|
2
3
|
import logging
|
|
3
4
|
import typing
|
|
4
5
|
import warnings
|
|
6
|
+
from collections.abc import Generator
|
|
5
7
|
|
|
6
8
|
from lite_bootstrap.exceptions import (
|
|
7
9
|
BootstrapperNotReadyError,
|
|
8
10
|
ConfigurationError,
|
|
9
11
|
InstrumentDependencyMissingWarning,
|
|
12
|
+
TeardownErrorCollector,
|
|
10
13
|
collect_teardown_errors,
|
|
11
14
|
)
|
|
12
|
-
from lite_bootstrap.instruments.base import
|
|
15
|
+
from lite_bootstrap.instruments.base import BaseInstrument, ConfigT
|
|
13
16
|
from lite_bootstrap.types import ApplicationT
|
|
14
17
|
|
|
15
18
|
|
|
@@ -19,12 +22,12 @@ logger = logging.getLogger(__name__)
|
|
|
19
22
|
InstrumentT = typing.TypeVar("InstrumentT", bound=BaseInstrument)
|
|
20
23
|
|
|
21
24
|
|
|
22
|
-
class BaseBootstrapper(abc.ABC, typing.Generic[ApplicationT]):
|
|
25
|
+
class BaseBootstrapper(abc.ABC, typing.Generic[ApplicationT, ConfigT]):
|
|
23
26
|
instruments_types: typing.ClassVar[list[type[BaseInstrument]]]
|
|
24
27
|
not_ready_message: typing.ClassVar[str]
|
|
25
28
|
instruments: list[BaseInstrument]
|
|
26
29
|
skipped_instruments: list[tuple[type[BaseInstrument], str]]
|
|
27
|
-
bootstrap_config:
|
|
30
|
+
bootstrap_config: ConfigT
|
|
28
31
|
_application: ApplicationT
|
|
29
32
|
|
|
30
33
|
# Marker tagged on a user-supplied app (or its config) once this bootstrapper has
|
|
@@ -32,7 +35,7 @@ class BaseBootstrapper(abc.ABC, typing.Generic[ApplicationT]):
|
|
|
32
35
|
# bootstrapper on the same app from re-attaching. Its accepted limits: ADR-0003.
|
|
33
36
|
_TEARDOWN_MARKER: typing.ClassVar[str] = "_lite_bootstrap_teardown_attached"
|
|
34
37
|
|
|
35
|
-
def __init__(self, bootstrap_config:
|
|
38
|
+
def __init__(self, bootstrap_config: ConfigT) -> None:
|
|
36
39
|
self.is_bootstrapped = False
|
|
37
40
|
self._torn_down = False
|
|
38
41
|
# Set when another bootstrapper already owns this application; bootstrap() then refuses.
|
|
@@ -141,12 +144,41 @@ class BaseBootstrapper(abc.ABC, typing.Generic[ApplicationT]):
|
|
|
141
144
|
raise ConfigurationError(msg)
|
|
142
145
|
if self.is_bootstrapped:
|
|
143
146
|
return self._application
|
|
147
|
+
started_instruments: list[BaseInstrument] = []
|
|
148
|
+
try:
|
|
149
|
+
for one_instrument in self.instruments:
|
|
150
|
+
one_instrument.bootstrap()
|
|
151
|
+
started_instruments.append(one_instrument)
|
|
152
|
+
application = self._prepare_application()
|
|
153
|
+
except BaseException as error:
|
|
154
|
+
self._torn_down = True
|
|
155
|
+
teardown_errors = TeardownErrorCollector(logger)
|
|
156
|
+
for one_instrument in reversed(started_instruments):
|
|
157
|
+
with teardown_errors.capture(type(one_instrument).__name__):
|
|
158
|
+
one_instrument.teardown()
|
|
159
|
+
for name, teardown_error in teardown_errors.errors:
|
|
160
|
+
error.add_note(f"Error rolling back {name}: {teardown_error}")
|
|
161
|
+
raise
|
|
162
|
+
self._application = application
|
|
144
163
|
self.is_bootstrapped = True
|
|
145
|
-
for one_instrument in self.instruments:
|
|
146
|
-
one_instrument.bootstrap()
|
|
147
|
-
self._application = self._prepare_application()
|
|
148
164
|
return self._application
|
|
149
165
|
|
|
166
|
+
@contextlib.contextmanager
|
|
167
|
+
def _teardown_after_lifecycle(self) -> Generator[None]:
|
|
168
|
+
lifecycle_error: BaseException | None = None
|
|
169
|
+
try:
|
|
170
|
+
yield
|
|
171
|
+
except BaseException as error:
|
|
172
|
+
lifecycle_error = error
|
|
173
|
+
raise
|
|
174
|
+
finally:
|
|
175
|
+
try:
|
|
176
|
+
self.teardown()
|
|
177
|
+
except Exception as teardown_error:
|
|
178
|
+
if lifecycle_error is None:
|
|
179
|
+
raise
|
|
180
|
+
lifecycle_error.add_note(f"Error tearing down observability: {teardown_error}")
|
|
181
|
+
|
|
150
182
|
def teardown(self) -> None:
|
|
151
183
|
if not self.is_bootstrapped:
|
|
152
184
|
return
|
{lite_bootstrap-1.16.0 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/fastapi_bootstrapper.py
RENAMED
|
@@ -2,11 +2,12 @@ import contextlib
|
|
|
2
2
|
import dataclasses
|
|
3
3
|
import time
|
|
4
4
|
import typing
|
|
5
|
+
import weakref
|
|
5
6
|
from collections.abc import AsyncGenerator, Mapping
|
|
6
7
|
|
|
7
8
|
from lite_bootstrap import import_checker
|
|
8
9
|
from lite_bootstrap.bootstrappers.base import BaseBootstrapper
|
|
9
|
-
from lite_bootstrap.exceptions import ConfigurationError
|
|
10
|
+
from lite_bootstrap.exceptions import ConfigurationError, collect_teardown_errors
|
|
10
11
|
from lite_bootstrap.helpers.fastapi_helpers import enable_offline_docs
|
|
11
12
|
from lite_bootstrap.helpers.warn import warn_at_caller
|
|
12
13
|
from lite_bootstrap.instruments.cors_instrument import CorsConfig, CorsInstrument
|
|
@@ -16,10 +17,15 @@ from lite_bootstrap.instruments.healthchecks_instrument import (
|
|
|
16
17
|
HealthCheckTypedDict,
|
|
17
18
|
)
|
|
18
19
|
from lite_bootstrap.instruments.logging_instrument import LoggingConfig, LoggingInstrument
|
|
19
|
-
from lite_bootstrap.instruments.opentelemetry_instrument import
|
|
20
|
-
from lite_bootstrap.instruments.prometheus_instrument import
|
|
20
|
+
from lite_bootstrap.instruments.opentelemetry_instrument import OpenTelemetryAsgiConfig, OpenTelemetryInstrument
|
|
21
|
+
from lite_bootstrap.instruments.prometheus_instrument import PrometheusHttpConfig, PrometheusInstrument
|
|
21
22
|
from lite_bootstrap.instruments.pyroscope_instrument import PyroscopeConfig, PyroscopeInstrument
|
|
22
|
-
from lite_bootstrap.instruments.sentry_instrument import
|
|
23
|
+
from lite_bootstrap.instruments.sentry_instrument import (
|
|
24
|
+
SentryInstrument,
|
|
25
|
+
SentryLeanCaptureConfig,
|
|
26
|
+
disable_sentry_integrations,
|
|
27
|
+
warn_about_sentry_integrations_installed_earlier,
|
|
28
|
+
)
|
|
23
29
|
from lite_bootstrap.instruments.swagger_instrument import SwaggerConfig, SwaggerInstrument
|
|
24
30
|
from lite_bootstrap.types import UNSET, UnsetType
|
|
25
31
|
|
|
@@ -30,7 +36,12 @@ if typing.TYPE_CHECKING:
|
|
|
30
36
|
if import_checker.is_fastapi_installed:
|
|
31
37
|
import fastapi
|
|
32
38
|
from fastapi.middleware.cors import CORSMiddleware
|
|
33
|
-
|
|
39
|
+
|
|
40
|
+
if import_checker.is_fastapi_installed and import_checker.is_sentry_installed:
|
|
41
|
+
from sentry_sdk.integrations.fastapi import FastApiIntegration
|
|
42
|
+
from sentry_sdk.integrations.starlette import StarletteIntegration
|
|
43
|
+
|
|
44
|
+
from lite_bootstrap.helpers.starlette_sentry import StarletteSentryCaptureMiddleware
|
|
34
45
|
|
|
35
46
|
if import_checker.is_structlog_installed:
|
|
36
47
|
import structlog
|
|
@@ -39,10 +50,13 @@ if import_checker.is_structlog_installed:
|
|
|
39
50
|
|
|
40
51
|
if import_checker.is_opentelemetry_installed:
|
|
41
52
|
from opentelemetry.metrics import get_meter_provider
|
|
42
|
-
from opentelemetry.trace import get_tracer_provider
|
|
43
53
|
|
|
44
54
|
if import_checker.is_fastapi_opentelemetry_installed:
|
|
55
|
+
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
|
|
45
56
|
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
|
57
|
+
from starlette.middleware.errors import ServerErrorMiddleware
|
|
58
|
+
|
|
59
|
+
from lite_bootstrap.helpers.opentelemetry_asgi import ExcludeInfrastructureTelemetry
|
|
46
60
|
|
|
47
61
|
if import_checker.is_prometheus_fastapi_instrumentator_installed:
|
|
48
62
|
from prometheus_fastapi_instrumentator import Instrumentator
|
|
@@ -53,37 +67,23 @@ class FastAPIConfig(
|
|
|
53
67
|
CorsConfig,
|
|
54
68
|
HealthChecksConfig,
|
|
55
69
|
LoggingConfig,
|
|
56
|
-
|
|
57
|
-
|
|
70
|
+
OpenTelemetryAsgiConfig,
|
|
71
|
+
PrometheusHttpConfig,
|
|
58
72
|
PyroscopeConfig,
|
|
59
|
-
|
|
73
|
+
SentryLeanCaptureConfig,
|
|
60
74
|
SwaggerConfig,
|
|
61
75
|
):
|
|
62
76
|
application: "fastapi.FastAPI | UnsetType" = UNSET
|
|
63
77
|
application_kwargs: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
64
|
-
# Not on OpenTelemetryConfig: only the FastAPI and Litestar instrumentors take `exclude_spans`.
|
|
65
|
-
opentelemetry_exclude_spans: list[typing.Literal["receive", "send"]] = dataclasses.field(default_factory=list)
|
|
66
78
|
prometheus_instrumentator_additional_params: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
67
79
|
prometheus_instrument_additional_params: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
68
80
|
prometheus_expose_additional_params: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
69
81
|
logging_access_log_enabled: bool = False
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"prometheus_expose_params": "prometheus_expose_additional_params",
|
|
75
|
-
"fastapi_logging_middleware_enabled": "logging_access_log_enabled",
|
|
82
|
+
_opentelemetry_exclusions_use_comma_separator: typing.ClassVar[bool] = True
|
|
83
|
+
_sentry_lean_replaced_integrations: typing.ClassVar[Mapping[str, str]] = {
|
|
84
|
+
"starlette": "StarletteIntegration",
|
|
85
|
+
"fastapi": "FastApiIntegration",
|
|
76
86
|
}
|
|
77
|
-
prometheus_instrumentator_params: dict[str, typing.Any] | UnsetType = dataclasses.field(
|
|
78
|
-
default=UNSET, repr=False, compare=False
|
|
79
|
-
)
|
|
80
|
-
prometheus_instrument_params: dict[str, typing.Any] | UnsetType = dataclasses.field(
|
|
81
|
-
default=UNSET, repr=False, compare=False
|
|
82
|
-
)
|
|
83
|
-
prometheus_expose_params: dict[str, typing.Any] | UnsetType = dataclasses.field(
|
|
84
|
-
default=UNSET, repr=False, compare=False
|
|
85
|
-
)
|
|
86
|
-
fastapi_logging_middleware_enabled: bool | UnsetType = dataclasses.field(default=UNSET, repr=False, compare=False)
|
|
87
87
|
|
|
88
88
|
def __post_init__(self) -> None:
|
|
89
89
|
# @dataclass(slots=True) replaces the class object, breaking bare super().
|
|
@@ -93,13 +93,16 @@ class FastAPIConfig(
|
|
|
93
93
|
raise ConfigurationError(msg)
|
|
94
94
|
|
|
95
95
|
if isinstance(self.application, UnsetType):
|
|
96
|
+
if "docs_url" in self.application_kwargs:
|
|
97
|
+
msg = "Use swagger_path to configure docs_url when lite-bootstrap creates the FastAPI application"
|
|
98
|
+
raise ConfigurationError(msg)
|
|
96
99
|
application = fastapi.FastAPI(docs_url=self.swagger_path, **self.application_kwargs)
|
|
97
100
|
# FastAPIConfig stays frozen for user-facing immutability; __post_init__ needs
|
|
98
101
|
# to set application after construction, so we bypass the freeze here.
|
|
99
102
|
object.__setattr__(self, "application", application)
|
|
100
|
-
application.title = self.
|
|
103
|
+
application.title = self.service_name_or_default
|
|
101
104
|
application.debug = self.service_debug
|
|
102
|
-
application.version = self.
|
|
105
|
+
application.version = self.service_version_or_default
|
|
103
106
|
elif self.application_kwargs:
|
|
104
107
|
warn_at_caller("application_kwargs must be used without application")
|
|
105
108
|
|
|
@@ -198,7 +201,7 @@ class FastAPIHealthChecksInstrument(HealthChecksInstrument[FastAPIConfig]):
|
|
|
198
201
|
async def health_check_handler(response: fastapi.Response) -> HealthCheckTypedDict:
|
|
199
202
|
health_status = await self.define_health_status()
|
|
200
203
|
if not health_status:
|
|
201
|
-
response.status_code = fastapi.status.
|
|
204
|
+
response.status_code = fastapi.status.HTTP_503_SERVICE_UNAVAILABLE
|
|
202
205
|
return self.render_health_check_data(health_status=health_status)
|
|
203
206
|
|
|
204
207
|
return fastapi_router
|
|
@@ -209,19 +212,70 @@ class FastAPIHealthChecksInstrument(HealthChecksInstrument[FastAPIConfig]):
|
|
|
209
212
|
|
|
210
213
|
@dataclasses.dataclass(kw_only=True)
|
|
211
214
|
class FastAPIOpenTelemetryInstrument(OpenTelemetryInstrument[FastAPIConfig]):
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
tracer_provider=get_tracer_provider(),
|
|
217
|
-
meter_provider=get_meter_provider(),
|
|
218
|
-
excluded_urls=",".join(self._build_excluded_url_patterns("FASTAPI")),
|
|
219
|
-
exclude_spans=self.bootstrap_config.opentelemetry_exclude_spans,
|
|
220
|
-
)
|
|
215
|
+
_owns_app_instrumentation: bool = dataclasses.field(default=False, init=False, repr=False, compare=False)
|
|
216
|
+
_restore_infrastructure_exclusions: typing.Callable[[], None] | None = dataclasses.field(
|
|
217
|
+
default=None, init=False, repr=False, compare=False
|
|
218
|
+
)
|
|
221
219
|
|
|
222
|
-
def
|
|
223
|
-
|
|
224
|
-
|
|
220
|
+
def _bootstrap_telemetry(self) -> None:
|
|
221
|
+
super()._bootstrap_telemetry()
|
|
222
|
+
app = self.bootstrap_config.app
|
|
223
|
+
if not getattr(app, "_is_instrumented_by_opentelemetry", False):
|
|
224
|
+
FastAPIInstrumentor.instrument_app(
|
|
225
|
+
app=app,
|
|
226
|
+
tracer_provider=self.tracer_provider,
|
|
227
|
+
meter_provider=get_meter_provider(),
|
|
228
|
+
excluded_urls=",".join(self._build_excluded_url_patterns("FASTAPI")),
|
|
229
|
+
exclude_spans=self.bootstrap_config.opentelemetry_exclude_spans,
|
|
230
|
+
)
|
|
231
|
+
self._owns_app_instrumentation = True
|
|
232
|
+
self._restore_infrastructure_exclusions = self._install_infrastructure_exclusions()
|
|
233
|
+
|
|
234
|
+
def _install_infrastructure_exclusions(self) -> typing.Callable[[], None]:
|
|
235
|
+
app = self.bootstrap_config.app
|
|
236
|
+
build_stack = app.build_middleware_stack
|
|
237
|
+
excluded_paths = self._build_infrastructure_excluded_paths()
|
|
238
|
+
owned_wrappers = weakref.WeakSet[ExcludeInfrastructureTelemetry]()
|
|
239
|
+
|
|
240
|
+
def wrap(stack: "ASGIApp | None") -> None:
|
|
241
|
+
# FastAPIInstrumentor places its OTel middleware inside an outer error handler.
|
|
242
|
+
if isinstance(stack, ServerErrorMiddleware) and isinstance(stack.app, OpenTelemetryMiddleware):
|
|
243
|
+
wrapper = ExcludeInfrastructureTelemetry(stack.app, excluded_paths)
|
|
244
|
+
owned_wrappers.add(wrapper)
|
|
245
|
+
stack.app = wrapper
|
|
246
|
+
|
|
247
|
+
def build_middleware_stack() -> "ASGIApp":
|
|
248
|
+
stack = build_stack()
|
|
249
|
+
wrap(stack)
|
|
250
|
+
return stack
|
|
251
|
+
|
|
252
|
+
def restore() -> None:
|
|
253
|
+
if app.build_middleware_stack is build_middleware_stack:
|
|
254
|
+
vars(app)["build_middleware_stack"] = build_stack
|
|
255
|
+
stack = app.middleware_stack
|
|
256
|
+
if (
|
|
257
|
+
isinstance(stack, ServerErrorMiddleware)
|
|
258
|
+
and isinstance(stack.app, ExcludeInfrastructureTelemetry)
|
|
259
|
+
and stack.app in owned_wrappers
|
|
260
|
+
):
|
|
261
|
+
stack.app = stack.app.app
|
|
262
|
+
|
|
263
|
+
vars(app)["build_middleware_stack"] = build_middleware_stack
|
|
264
|
+
wrap(app.middleware_stack)
|
|
265
|
+
return restore
|
|
266
|
+
|
|
267
|
+
def _teardown_owned_resources(self) -> None:
|
|
268
|
+
with collect_teardown_errors() as teardown_errors:
|
|
269
|
+
if self._restore_infrastructure_exclusions is not None:
|
|
270
|
+
with teardown_errors.capture("FastAPI infrastructure exclusions"):
|
|
271
|
+
self._restore_infrastructure_exclusions()
|
|
272
|
+
self._restore_infrastructure_exclusions = None
|
|
273
|
+
if self._owns_app_instrumentation:
|
|
274
|
+
self._owns_app_instrumentation = False
|
|
275
|
+
with teardown_errors.capture("FastAPIInstrumentor"):
|
|
276
|
+
FastAPIInstrumentor.uninstrument_app(self.bootstrap_config.app)
|
|
277
|
+
with teardown_errors.capture("OpenTelemetry"):
|
|
278
|
+
super()._teardown_owned_resources()
|
|
225
279
|
|
|
226
280
|
|
|
227
281
|
@dataclasses.dataclass(kw_only=True)
|
|
@@ -230,15 +284,28 @@ class FastAPIPrometheusInstrument(PrometheusInstrument[FastAPIConfig]):
|
|
|
230
284
|
|
|
231
285
|
@staticmethod
|
|
232
286
|
def dependencies_installed() -> bool:
|
|
233
|
-
return
|
|
287
|
+
return (
|
|
288
|
+
import_checker.is_prometheus_client_installed
|
|
289
|
+
and import_checker.is_prometheus_fastapi_instrumentator_installed
|
|
290
|
+
)
|
|
234
291
|
|
|
235
292
|
def bootstrap(self) -> None:
|
|
236
293
|
config = self.bootstrap_config
|
|
237
294
|
application = config.app
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
)
|
|
295
|
+
if "endpoint" in config.prometheus_expose_additional_params:
|
|
296
|
+
msg = "Use prometheus_metrics_path to configure the Prometheus endpoint"
|
|
297
|
+
raise ConfigurationError(msg)
|
|
298
|
+
instrumentator_params = dict(config.prometheus_instrumentator_additional_params)
|
|
299
|
+
instrumentator_params["excluded_handlers"] = [
|
|
300
|
+
*instrumentator_params.get("excluded_handlers", []),
|
|
301
|
+
*self.infrastructure_excluded_patterns(),
|
|
302
|
+
]
|
|
303
|
+
instrumentator = Instrumentator(**instrumentator_params)
|
|
304
|
+
if config.is_prometheus_http_metrics_on(
|
|
305
|
+
opentelemetry_records_http_metrics=FastAPIOpenTelemetryInstrument.is_recording_metrics(config)
|
|
306
|
+
):
|
|
307
|
+
instrumentator.instrument(application, **config.prometheus_instrument_additional_params)
|
|
308
|
+
instrumentator.expose(
|
|
242
309
|
application,
|
|
243
310
|
endpoint=config.prometheus_metrics_path,
|
|
244
311
|
include_in_schema=config.prometheus_metrics_include_in_schema,
|
|
@@ -246,39 +313,50 @@ class FastAPIPrometheusInstrument(PrometheusInstrument[FastAPIConfig]):
|
|
|
246
313
|
)
|
|
247
314
|
|
|
248
315
|
|
|
316
|
+
@dataclasses.dataclass(kw_only=True, slots=True)
|
|
317
|
+
class FastAPISentryInstrument(SentryInstrument[FastAPIConfig]):
|
|
318
|
+
def _build_init_params(self) -> dict[str, typing.Any]:
|
|
319
|
+
init_params: typing.Final = super(FastAPISentryInstrument, self)._build_init_params()
|
|
320
|
+
if self.bootstrap_config.is_sentry_lean_error_capture_on():
|
|
321
|
+
disable_sentry_integrations(init_params, [StarletteIntegration, FastApiIntegration])
|
|
322
|
+
return init_params
|
|
323
|
+
|
|
324
|
+
def bootstrap(self) -> None:
|
|
325
|
+
super(FastAPISentryInstrument, self).bootstrap()
|
|
326
|
+
if not self.bootstrap_config.is_sentry_lean_error_capture_on():
|
|
327
|
+
return
|
|
328
|
+
warn_about_sentry_integrations_installed_earlier([StarletteIntegration, FastApiIntegration])
|
|
329
|
+
self.bootstrap_config.app.add_middleware(StarletteSentryCaptureMiddleware)
|
|
330
|
+
|
|
331
|
+
|
|
249
332
|
@dataclasses.dataclass(kw_only=True)
|
|
250
333
|
class FastAPISwaggerInstrument(SwaggerInstrument[FastAPIConfig]):
|
|
251
334
|
def bootstrap(self) -> None:
|
|
252
335
|
config = self.bootstrap_config
|
|
253
336
|
application = config.app
|
|
254
|
-
if config.swagger_path != application.docs_url:
|
|
337
|
+
if application.docs_url is not None and config.swagger_path != application.docs_url:
|
|
255
338
|
warn_at_caller(f"swagger_path differs from docs_url, {application.docs_url} will be used for docs path")
|
|
256
339
|
if config.swagger_offline_docs:
|
|
257
340
|
enable_offline_docs(application, static_path=config.swagger_static_path)
|
|
258
341
|
|
|
259
342
|
|
|
260
|
-
class FastAPIBootstrapper(BaseBootstrapper["fastapi.FastAPI"]):
|
|
261
|
-
__slots__ = "bootstrap_config", "instruments"
|
|
262
|
-
|
|
343
|
+
class FastAPIBootstrapper(BaseBootstrapper["fastapi.FastAPI", FastAPIConfig]):
|
|
263
344
|
instruments_types: typing.ClassVar = [
|
|
264
345
|
FastAPICorsInstrument,
|
|
265
346
|
FastAPIOpenTelemetryInstrument,
|
|
266
347
|
PyroscopeInstrument,
|
|
267
|
-
|
|
348
|
+
FastAPISentryInstrument,
|
|
268
349
|
FastAPIHealthChecksInstrument,
|
|
269
350
|
FastAPILoggingInstrument,
|
|
270
351
|
FastAPIPrometheusInstrument,
|
|
271
352
|
FastAPISwaggerInstrument,
|
|
272
353
|
]
|
|
273
|
-
bootstrap_config: FastAPIConfig # ty: ignore[invalid-mutable-override]
|
|
274
354
|
not_ready_message = "fastapi is not installed"
|
|
275
355
|
|
|
276
356
|
@contextlib.asynccontextmanager
|
|
277
357
|
async def lifespan_manager(self, _: "fastapi.FastAPI") -> AsyncGenerator[dict[str, typing.Any]]:
|
|
278
|
-
|
|
358
|
+
with self._teardown_after_lifecycle():
|
|
279
359
|
yield {}
|
|
280
|
-
finally:
|
|
281
|
-
self.teardown()
|
|
282
360
|
|
|
283
361
|
def __init__(self, bootstrap_config: FastAPIConfig) -> None:
|
|
284
362
|
super().__init__(bootstrap_config)
|
|
@@ -286,11 +364,14 @@ class FastAPIBootstrapper(BaseBootstrapper["fastapi.FastAPI"]):
|
|
|
286
364
|
self._attach_teardown_once(application, lambda: self._wrap_lifespan(application))
|
|
287
365
|
|
|
288
366
|
def _wrap_lifespan(self, application: "fastapi.FastAPI") -> None:
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
367
|
+
user_lifespan = application.router.lifespan_context
|
|
368
|
+
|
|
369
|
+
@contextlib.asynccontextmanager
|
|
370
|
+
async def merged_lifespan(app: "fastapi.FastAPI") -> AsyncGenerator[Mapping[str, typing.Any]]:
|
|
371
|
+
async with self.lifespan_manager(app) as bootstrap_state, user_lifespan(app) as user_state:
|
|
372
|
+
yield {**bootstrap_state, **(user_state or {})}
|
|
373
|
+
|
|
374
|
+
application.router.lifespan_context = merged_lifespan
|
|
294
375
|
|
|
295
376
|
def is_ready(self) -> bool:
|
|
296
377
|
return import_checker.is_fastapi_installed
|