lite-bootstrap 1.15.3__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.15.3 → lite_bootstrap-2.0.0}/PKG-INFO +19 -19
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/README.md +4 -0
- lite_bootstrap-2.0.0/lite_bootstrap/__init__.py +70 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/base.py +48 -7
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/fastapi_bootstrapper.py +151 -53
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/fastmcp_bootstrapper.py +186 -60
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/faststream_bootstrapper.py +82 -35
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/free_bootstrapper.py +1 -8
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/litestar_bootstrapper.py +216 -51
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/exceptions.py +5 -8
- {lite_bootstrap-1.15.3 → 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.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/import_checker.py +3 -5
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/base.py +16 -23
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/cors_instrument.py +1 -1
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/healthchecks_instrument.py +17 -5
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/logging_factory.py +3 -71
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/logging_instrument.py +57 -62
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/opentelemetry_instrument.py +150 -72
- lite_bootstrap-2.0.0/lite_bootstrap/instruments/prometheus_instrument.py +55 -0
- {lite_bootstrap-1.15.3 → 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.15.3 → lite_bootstrap-2.0.0}/pyproject.toml +21 -27
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/pyproject.toml.orig +32 -48
- lite_bootstrap-1.15.3/lite_bootstrap/__init__.py +0 -37
- lite_bootstrap-1.15.3/lite_bootstrap/instruments/prometheus_instrument.py +0 -27
- lite_bootstrap-1.15.3/lite_bootstrap/instruments/sentry_instrument.py +0 -160
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/bootstrappers/__init__.py +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/__init__.py +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/path.py +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/helpers/warn.py +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/__init__.py +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/instruments/swagger_instrument.py +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/py.typed +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/fastapi_docs/redoc.standalone.js +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/fastapi_docs/swagger-ui-bundle.js +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/fastapi_docs/swagger-ui.css +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/asyncapi-web-component.js +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/default.min.css +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/swagger-ui-bundle.js +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/swagger-ui-standalone-preset.js +0 -0
- {lite_bootstrap-1.15.3 → lite_bootstrap-2.0.0}/lite_bootstrap/static/litestar_docs/swagger-ui.css +0 -0
- {lite_bootstrap-1.15.3 → 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,8 +35,9 @@ 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
|
|
40
|
+
self._torn_down = False
|
|
37
41
|
# Set when another bootstrapper already owns this application; bootstrap() then refuses.
|
|
38
42
|
self._attach_skipped = False
|
|
39
43
|
if not self.is_ready():
|
|
@@ -131,18 +135,55 @@ class BaseBootstrapper(abc.ABC, typing.Generic[ApplicationT]):
|
|
|
131
135
|
f"{type(self).__name__} per application."
|
|
132
136
|
)
|
|
133
137
|
raise ConfigurationError(msg)
|
|
138
|
+
if self._torn_down:
|
|
139
|
+
msg = (
|
|
140
|
+
f"{type(self).__name__} was torn down and cannot bootstrap again: its instruments "
|
|
141
|
+
f"already changed the application. To bootstrap again, construct a new "
|
|
142
|
+
f"{type(self).__name__}, with a new application if it takes one."
|
|
143
|
+
)
|
|
144
|
+
raise ConfigurationError(msg)
|
|
134
145
|
if self.is_bootstrapped:
|
|
135
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
|
|
136
163
|
self.is_bootstrapped = True
|
|
137
|
-
for one_instrument in self.instruments:
|
|
138
|
-
one_instrument.bootstrap()
|
|
139
|
-
self._application = self._prepare_application()
|
|
140
164
|
return self._application
|
|
141
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
|
+
|
|
142
182
|
def teardown(self) -> None:
|
|
143
183
|
if not self.is_bootstrapped:
|
|
144
184
|
return
|
|
145
185
|
self.is_bootstrapped = False
|
|
186
|
+
self._torn_down = True
|
|
146
187
|
with collect_teardown_errors(logger) as teardown_errors:
|
|
147
188
|
for one_instrument in reversed(self.instruments):
|
|
148
189
|
with teardown_errors.capture(type(one_instrument).__name__):
|
{lite_bootstrap-1.15.3 → 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
|
-
|
|
5
|
+
import weakref
|
|
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,20 +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
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
78
|
+
prometheus_instrumentator_additional_params: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
79
|
+
prometheus_instrument_additional_params: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
80
|
+
prometheus_expose_additional_params: dict[str, typing.Any] = dataclasses.field(default_factory=dict)
|
|
81
|
+
logging_access_log_enabled: bool = False
|
|
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",
|
|
86
|
+
}
|
|
70
87
|
|
|
71
88
|
def __post_init__(self) -> None:
|
|
72
89
|
# @dataclass(slots=True) replaces the class object, breaking bare super().
|
|
@@ -76,13 +93,16 @@ class FastAPIConfig(
|
|
|
76
93
|
raise ConfigurationError(msg)
|
|
77
94
|
|
|
78
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)
|
|
79
99
|
application = fastapi.FastAPI(docs_url=self.swagger_path, **self.application_kwargs)
|
|
80
100
|
# FastAPIConfig stays frozen for user-facing immutability; __post_init__ needs
|
|
81
101
|
# to set application after construction, so we bypass the freeze here.
|
|
82
102
|
object.__setattr__(self, "application", application)
|
|
83
|
-
application.title = self.
|
|
103
|
+
application.title = self.service_name_or_default
|
|
84
104
|
application.debug = self.service_debug
|
|
85
|
-
application.version = self.
|
|
105
|
+
application.version = self.service_version_or_default
|
|
86
106
|
elif self.application_kwargs:
|
|
87
107
|
warn_at_caller("application_kwargs must be used without application")
|
|
88
108
|
|
|
@@ -158,7 +178,7 @@ class _AccessLogMiddleware:
|
|
|
158
178
|
class FastAPILoggingInstrument(LoggingInstrument[FastAPIConfig]):
|
|
159
179
|
def bootstrap(self) -> None:
|
|
160
180
|
super().bootstrap()
|
|
161
|
-
if not self.bootstrap_config.
|
|
181
|
+
if not self.bootstrap_config.logging_access_log_enabled:
|
|
162
182
|
return
|
|
163
183
|
self.bootstrap_config.app.add_middleware(_AccessLogMiddleware, excluded_paths=self._build_excluded_paths())
|
|
164
184
|
|
|
@@ -181,7 +201,7 @@ class FastAPIHealthChecksInstrument(HealthChecksInstrument[FastAPIConfig]):
|
|
|
181
201
|
async def health_check_handler(response: fastapi.Response) -> HealthCheckTypedDict:
|
|
182
202
|
health_status = await self.define_health_status()
|
|
183
203
|
if not health_status:
|
|
184
|
-
response.status_code = fastapi.status.
|
|
204
|
+
response.status_code = fastapi.status.HTTP_503_SERVICE_UNAVAILABLE
|
|
185
205
|
return self.render_health_check_data(health_status=health_status)
|
|
186
206
|
|
|
187
207
|
return fastapi_router
|
|
@@ -192,19 +212,70 @@ class FastAPIHealthChecksInstrument(HealthChecksInstrument[FastAPIConfig]):
|
|
|
192
212
|
|
|
193
213
|
@dataclasses.dataclass(kw_only=True)
|
|
194
214
|
class FastAPIOpenTelemetryInstrument(OpenTelemetryInstrument[FastAPIConfig]):
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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
|
+
)
|
|
219
|
+
|
|
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()
|
|
208
279
|
|
|
209
280
|
|
|
210
281
|
@dataclasses.dataclass(kw_only=True)
|
|
@@ -213,55 +284,79 @@ class FastAPIPrometheusInstrument(PrometheusInstrument[FastAPIConfig]):
|
|
|
213
284
|
|
|
214
285
|
@staticmethod
|
|
215
286
|
def dependencies_installed() -> bool:
|
|
216
|
-
return
|
|
287
|
+
return (
|
|
288
|
+
import_checker.is_prometheus_client_installed
|
|
289
|
+
and import_checker.is_prometheus_fastapi_instrumentator_installed
|
|
290
|
+
)
|
|
217
291
|
|
|
218
292
|
def bootstrap(self) -> None:
|
|
219
293
|
config = self.bootstrap_config
|
|
220
294
|
application = config.app
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
)
|
|
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(
|
|
225
309
|
application,
|
|
226
310
|
endpoint=config.prometheus_metrics_path,
|
|
227
311
|
include_in_schema=config.prometheus_metrics_include_in_schema,
|
|
228
|
-
**config.
|
|
312
|
+
**config.prometheus_expose_additional_params,
|
|
229
313
|
)
|
|
230
314
|
|
|
231
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
|
+
|
|
232
332
|
@dataclasses.dataclass(kw_only=True)
|
|
233
333
|
class FastAPISwaggerInstrument(SwaggerInstrument[FastAPIConfig]):
|
|
234
334
|
def bootstrap(self) -> None:
|
|
235
335
|
config = self.bootstrap_config
|
|
236
336
|
application = config.app
|
|
237
|
-
if config.swagger_path != application.docs_url:
|
|
337
|
+
if application.docs_url is not None and config.swagger_path != application.docs_url:
|
|
238
338
|
warn_at_caller(f"swagger_path differs from docs_url, {application.docs_url} will be used for docs path")
|
|
239
339
|
if config.swagger_offline_docs:
|
|
240
340
|
enable_offline_docs(application, static_path=config.swagger_static_path)
|
|
241
341
|
|
|
242
342
|
|
|
243
|
-
class FastAPIBootstrapper(BaseBootstrapper["fastapi.FastAPI"]):
|
|
244
|
-
__slots__ = "bootstrap_config", "instruments"
|
|
245
|
-
|
|
343
|
+
class FastAPIBootstrapper(BaseBootstrapper["fastapi.FastAPI", FastAPIConfig]):
|
|
246
344
|
instruments_types: typing.ClassVar = [
|
|
247
345
|
FastAPICorsInstrument,
|
|
248
346
|
FastAPIOpenTelemetryInstrument,
|
|
249
347
|
PyroscopeInstrument,
|
|
250
|
-
|
|
348
|
+
FastAPISentryInstrument,
|
|
251
349
|
FastAPIHealthChecksInstrument,
|
|
252
350
|
FastAPILoggingInstrument,
|
|
253
351
|
FastAPIPrometheusInstrument,
|
|
254
352
|
FastAPISwaggerInstrument,
|
|
255
353
|
]
|
|
256
|
-
bootstrap_config: FastAPIConfig # ty: ignore[invalid-mutable-override]
|
|
257
354
|
not_ready_message = "fastapi is not installed"
|
|
258
355
|
|
|
259
356
|
@contextlib.asynccontextmanager
|
|
260
357
|
async def lifespan_manager(self, _: "fastapi.FastAPI") -> AsyncGenerator[dict[str, typing.Any]]:
|
|
261
|
-
|
|
358
|
+
with self._teardown_after_lifecycle():
|
|
262
359
|
yield {}
|
|
263
|
-
finally:
|
|
264
|
-
self.teardown()
|
|
265
360
|
|
|
266
361
|
def __init__(self, bootstrap_config: FastAPIConfig) -> None:
|
|
267
362
|
super().__init__(bootstrap_config)
|
|
@@ -269,11 +364,14 @@ class FastAPIBootstrapper(BaseBootstrapper["fastapi.FastAPI"]):
|
|
|
269
364
|
self._attach_teardown_once(application, lambda: self._wrap_lifespan(application))
|
|
270
365
|
|
|
271
366
|
def _wrap_lifespan(self, application: "fastapi.FastAPI") -> None:
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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
|
|
277
375
|
|
|
278
376
|
def is_ready(self) -> bool:
|
|
279
377
|
return import_checker.is_fastapi_installed
|