csrd-lifespan 0.1.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.
@@ -0,0 +1,217 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ /env/
142
+ /venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ *.db
210
+
211
+
212
+ # Import linter cache
213
+ .import_linter_cache/
214
+
215
+ # IDE
216
+ .idea/
217
+ .idea/*
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: csrd-lifespan
3
+ Version: 0.1.0
4
+ Summary: Lifespan stack utilities for FastAPI
5
+ Project-URL: Repository, https://github.com/csrd-api/fastapi-common
6
+ Project-URL: Documentation, https://github.com/csrd-api/fastapi-common/tree/main/packages/lifespan
7
+ Project-URL: Changelog, https://github.com/csrd-api/fastapi-common/blob/main/CHANGELOG.md
8
+ License: MIT
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: fastapi<1,>=0.115
@@ -0,0 +1,21 @@
1
+ # csrd-lifespan
2
+
3
+ Composable lifespan stack for FastAPI applications.
4
+
5
+ **Package**: `csrd.lifespan` · **Import**: `from csrd.lifespan import lifespan_stack`
6
+
7
+ ## What's included
8
+
9
+ - `lifespan_stack` — register multiple async context managers as a single FastAPI lifespan
10
+ - Merges yielded state dicts from all lifespan functions
11
+ - Supports nested lists of lifespan functions
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ uv pip install "csrd-lifespan @ git+ssh://git@github.com/csrd-api/fastapi-common.git#subdirectory=packages/lifespan"
17
+ ```
18
+
19
+ ## Dependencies
20
+
21
+ None (Tier 1 — standalone)
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "csrd-lifespan"
3
+ version = "0.1.0"
4
+ description = "Lifespan stack utilities for FastAPI"
5
+ license = { text = "MIT" }
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "fastapi>=0.115,<1",
9
+ ]
10
+
11
+ [project.urls]
12
+ Repository = "https://github.com/csrd-api/fastapi-common"
13
+ Documentation = "https://github.com/csrd-api/fastapi-common/tree/main/packages/lifespan"
14
+ Changelog = "https://github.com/csrd-api/fastapi-common/blob/main/CHANGELOG.md"
15
+
16
+ [build-system]
17
+ requires = ["hatchling"]
18
+ build-backend = "hatchling.build"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["src/csrd"]
@@ -0,0 +1,3 @@
1
+ from .lifespan_stack import lifespan_stack
2
+
3
+ __all__ = ("lifespan_stack",)
@@ -0,0 +1,57 @@
1
+ import warnings
2
+ from collections.abc import AsyncIterator, Callable, Mapping
3
+ from contextlib import AbstractAsyncContextManager, AsyncExitStack, asynccontextmanager
4
+ from typing import Any
5
+
6
+ from fastapi import FastAPI
7
+
8
+ LifespanFunction = Callable[[FastAPI], AbstractAsyncContextManager[Mapping[str, Any] | None]]
9
+
10
+
11
+ def _callable_name(callable_: Callable[..., Any]) -> str:
12
+ try:
13
+ return callable_.__name__
14
+ except AttributeError:
15
+ return getattr(type(callable_), "__name__", repr(callable_))
16
+
17
+
18
+ def _normalize(
19
+ functions: tuple[LifespanFunction | list[LifespanFunction], ...],
20
+ ) -> list[LifespanFunction]:
21
+ collector: list[LifespanFunction] = []
22
+ for function in functions:
23
+ if isinstance(function, list):
24
+ collector.extend(function)
25
+ else:
26
+ collector.append(function)
27
+
28
+ return collector
29
+
30
+
31
+ class lifespan_stack:
32
+ def __init__(self, *lifespan_functions: LifespanFunction | list[LifespanFunction]) -> None:
33
+ self._lifespan_functions = _normalize(lifespan_functions)
34
+
35
+ @asynccontextmanager
36
+ async def __call__(self, app: FastAPI) -> AsyncIterator[dict[str, Any]]:
37
+ state: dict[str, Any] = {}
38
+ async with AsyncExitStack() as exit_stack:
39
+ for lifespan_function in self._lifespan_functions:
40
+ result = await exit_stack.enter_async_context(lifespan_function(app))
41
+
42
+ # If the lifespan function yielded None then it doesnt need to store anything in state
43
+ if result is None:
44
+ continue
45
+
46
+ if isinstance(result, Mapping):
47
+ state |= result
48
+ else:
49
+ warnings.warn(
50
+ f"Unexpected value from lifespan {_callable_name(lifespan_function)!r}: {result!r}",
51
+ stacklevel=2,
52
+ )
53
+
54
+ yield state
55
+
56
+
57
+ __all__ = ("lifespan_stack",)
File without changes
@@ -0,0 +1,87 @@
1
+ """Tests for lifespan_stack."""
2
+
3
+ import warnings
4
+ from contextlib import asynccontextmanager
5
+
6
+ import pytest
7
+ from fastapi import FastAPI
8
+
9
+ from csrd.lifespan.lifespan_stack import lifespan_stack
10
+
11
+
12
+ @asynccontextmanager
13
+ async def db_lifespan(app: FastAPI):
14
+ app.state.db = "connected"
15
+ yield {"db": "connected"}
16
+ app.state.db = None
17
+
18
+
19
+ @asynccontextmanager
20
+ async def cache_lifespan(app: FastAPI):
21
+ yield {"cache": "ready"}
22
+
23
+
24
+ @asynccontextmanager
25
+ async def void_lifespan(app: FastAPI):
26
+ yield # yields None — no state to merge
27
+
28
+
29
+ @asynccontextmanager
30
+ async def bad_lifespan(app: FastAPI):
31
+ yield "not_a_mapping" # should trigger warning
32
+
33
+
34
+ class TestLifespanStack:
35
+ @pytest.mark.asyncio
36
+ async def test_single_lifespan(self):
37
+ app = FastAPI()
38
+ stack = lifespan_stack(db_lifespan)
39
+ async with stack(app) as state:
40
+ assert state == {"db": "connected"}
41
+
42
+ @pytest.mark.asyncio
43
+ async def test_multiple_lifespans(self):
44
+ app = FastAPI()
45
+ stack = lifespan_stack(db_lifespan, cache_lifespan)
46
+ async with stack(app) as state:
47
+ assert state == {"db": "connected", "cache": "ready"}
48
+
49
+ @pytest.mark.asyncio
50
+ async def test_void_lifespan_skipped(self):
51
+ app = FastAPI()
52
+ stack = lifespan_stack(void_lifespan, db_lifespan)
53
+ async with stack(app) as state:
54
+ assert state == {"db": "connected"}
55
+
56
+ @pytest.mark.asyncio
57
+ async def test_bad_lifespan_warns(self):
58
+ app = FastAPI()
59
+ stack = lifespan_stack(bad_lifespan)
60
+ with warnings.catch_warnings(record=True) as w:
61
+ warnings.simplefilter("always")
62
+ async with stack(app) as state:
63
+ assert state == {}
64
+ assert len(w) == 1
65
+ assert "Unexpected value" in str(w[0].message)
66
+
67
+ @pytest.mark.asyncio
68
+ async def test_nested_list_flattening(self):
69
+ app = FastAPI()
70
+ stack = lifespan_stack([db_lifespan, cache_lifespan])
71
+ async with stack(app) as state:
72
+ assert state == {"db": "connected", "cache": "ready"}
73
+
74
+ @pytest.mark.asyncio
75
+ async def test_empty_stack(self):
76
+ app = FastAPI()
77
+ stack = lifespan_stack()
78
+ async with stack(app) as state:
79
+ assert state == {}
80
+
81
+ @pytest.mark.asyncio
82
+ async def test_cleanup_runs_on_exit(self):
83
+ app = FastAPI()
84
+ stack = lifespan_stack(db_lifespan)
85
+ async with stack(app):
86
+ assert app.state.db == "connected"
87
+ assert app.state.db is None