flameo 0.1.1__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.
Files changed (36) hide show
  1. flameo-0.1.1/LICENSE +21 -0
  2. flameo-0.1.1/PKG-INFO +203 -0
  3. flameo-0.1.1/README.md +139 -0
  4. flameo-0.1.1/flameo/__init__.py +15 -0
  5. flameo-0.1.1/flameo/__main__.py +4 -0
  6. flameo-0.1.1/flameo/cleanup.py +197 -0
  7. flameo-0.1.1/flameo/cli.py +800 -0
  8. flameo-0.1.1/flameo/cors.py +174 -0
  9. flameo-0.1.1/flameo/cycles.py +3508 -0
  10. flameo-0.1.1/flameo/docs.py +791 -0
  11. flameo-0.1.1/flameo/endpoint_cache.py +368 -0
  12. flameo-0.1.1/flameo/flameo.py +3956 -0
  13. flameo-0.1.1/flameo/logger.py +655 -0
  14. flameo-0.1.1/flameo/models.py +54 -0
  15. flameo-0.1.1/flameo/parser.py +589 -0
  16. flameo-0.1.1/flameo/ratelimit.py +50 -0
  17. flameo-0.1.1/flameo/scaffold.py +329 -0
  18. flameo-0.1.1/flameo/sessions.py +311 -0
  19. flameo-0.1.1/flameo/static/redoc/redoc.standalone.js +1826 -0
  20. flameo-0.1.1/flameo/static/swagger-ui/favicon-16x16.png +0 -0
  21. flameo-0.1.1/flameo/static/swagger-ui/favicon-32x32.png +0 -0
  22. flameo-0.1.1/flameo/static/swagger-ui/oauth2-redirect.html +79 -0
  23. flameo-0.1.1/flameo/static/swagger-ui/swagger-ui-bundle.js +2 -0
  24. flameo-0.1.1/flameo/static/swagger-ui/swagger-ui-standalone-preset.js +2 -0
  25. flameo-0.1.1/flameo/static/swagger-ui/swagger-ui.css +3 -0
  26. flameo-0.1.1/flameo/templates.py +281 -0
  27. flameo-0.1.1/flameo/utils.py +56 -0
  28. flameo-0.1.1/flameo/validation.py +565 -0
  29. flameo-0.1.1/flameo.egg-info/PKG-INFO +203 -0
  30. flameo-0.1.1/flameo.egg-info/SOURCES.txt +34 -0
  31. flameo-0.1.1/flameo.egg-info/dependency_links.txt +1 -0
  32. flameo-0.1.1/flameo.egg-info/entry_points.txt +2 -0
  33. flameo-0.1.1/flameo.egg-info/requires.txt +49 -0
  34. flameo-0.1.1/flameo.egg-info/top_level.txt +1 -0
  35. flameo-0.1.1/pyproject.toml +98 -0
  36. flameo-0.1.1/setup.cfg +4 -0
flameo-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mozammel Hoque, mozammelshbl@gmail.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
flameo-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.4
2
+ Name: flameo
3
+ Version: 0.1.1
4
+ Summary: An asynchronous Python web framework with ASGI and RSGI support
5
+ Author-email: Mozammel Hoque <mozammelshbl@gmail.com>
6
+ Maintainer-email: Mozammel Hoque <mozammelshbl@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Repository, https://github.com/flameohq/flameo
9
+ Project-URL: Issues, https://github.com/flameohq/flameo/issues
10
+ Keywords: web framework,asgi,rsgi,async,granian,uvloop,http server
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: aiofiles>=23
27
+ Requires-Dist: granian>=2
28
+ Requires-Dist: orjson>=3.9
29
+ Requires-Dist: pydantic>=2.0
30
+ Requires-Dist: uvloop>=0.19; platform_system != "Windows"
31
+ Provides-Extra: cache
32
+ Requires-Dist: redis[hiredis]>=5; extra == "cache"
33
+ Provides-Extra: compression
34
+ Requires-Dist: brotli>=1.1; extra == "compression"
35
+ Requires-Dist: zstandard>=0.22; extra == "compression"
36
+ Provides-Extra: database
37
+ Requires-Dist: aiosqlite>=0.20; extra == "database"
38
+ Requires-Dist: asyncmy>=0.2; extra == "database"
39
+ Requires-Dist: asyncpg>=0.29; extra == "database"
40
+ Requires-Dist: oracledb>=2; extra == "database"
41
+ Requires-Dist: pymongo>=4.17; extra == "database"
42
+ Provides-Extra: sqlite
43
+ Requires-Dist: aiosqlite>=0.20; extra == "sqlite"
44
+ Provides-Extra: mysql
45
+ Requires-Dist: asyncmy>=0.2; extra == "mysql"
46
+ Requires-Dist: cryptography; extra == "mysql"
47
+ Provides-Extra: postgres
48
+ Requires-Dist: asyncpg>=0.29; extra == "postgres"
49
+ Provides-Extra: oracle
50
+ Requires-Dist: oracledb>=2; extra == "oracle"
51
+ Provides-Extra: mongo
52
+ Requires-Dist: pymongo>=4.17; extra == "mongo"
53
+ Provides-Extra: templates
54
+ Requires-Dist: jinja2>=3.1; extra == "templates"
55
+ Provides-Extra: test
56
+ Requires-Dist: aiofiles>=23; extra == "test"
57
+ Requires-Dist: aiosqlite>=0.20; extra == "test"
58
+ Requires-Dist: jinja2>=3.1; extra == "test"
59
+ Requires-Dist: numpy>=1.24; extra == "test"
60
+ Requires-Dist: pytest>=8; extra == "test"
61
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
62
+ Requires-Dist: pytest-cov>=5; extra == "test"
63
+ Dynamic: license-file
64
+
65
+ <div align="center">
66
+ <img src="https://raw.githubusercontent.com/flameohq/flameo/main/flameo_logo.svg" alt="Flameo" width="220">
67
+ </div>
68
+
69
+ <hr />
70
+
71
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-3776AB?logo=python&logoColor=white)](https://www.python.org/)
72
+ [![Tests](https://github.com/flameohq/flameo/actions/workflows/tests.yml/badge.svg)](https://github.com/flameohq/flameo/actions/workflows/tests.yml)
73
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/flameohq/flameo)
74
+ [![Version](https://img.shields.io/badge/version-0.1.1-blue)](https://github.com/flameohq/flameo/blob/main/pyproject.toml)
75
+ [![Protocols](https://img.shields.io/badge/protocols-ASGI%20%7C%20RSGI-ff6b35)](#asgi-rsgi-and-uvloop)
76
+
77
+
78
+ <p align="center">
79
+ <em>Fast, Flexible, Less Verbose Framework. Syntax are as easy as you can think</em>
80
+ </p>
81
+
82
+
83
+ Flameo is a fast, easy to learn and code framework that pairs a minimal, familiar API with Python's flexibility. The same code supports Granians' **RSGI** and also Uvicon/Hypercor's **ASGI** natively.
84
+
85
+ ```python
86
+ from flameo import Flameo
87
+
88
+ app = Flameo()
89
+
90
+ @app.get("/")
91
+ async def home(req, res):
92
+ await res.json({"message": "Hello from Flameo 🔥"})
93
+ ```
94
+
95
+ Handlers receive standard `req` and `res` objects. Add any of `db`, `cache`, `app` or `state` to the signature and **Flameo** injects the managed database handle, cache instance, app instance and app state.
96
+
97
+ ```python
98
+ @app.get("/users")
99
+ async def get_user_json(req, res, db): # request-scoped pooled DB handle provided by Flameo
100
+ rows = await db.fetch("SELECT id, name FROM users") #returns json by default
101
+ await res.json(rows)
102
+
103
+ @app.get("/visits")
104
+ async def visits(req, res, cache): # cache instance (works both with and without Redis)
105
+ total = await cache.incr("visits")
106
+ await res.json({"visits": total})
107
+
108
+ @app.get("/debug")
109
+ async def debug(req, res, app): # the Flameo app instance
110
+ await res.json({"debug": app.debug})
111
+
112
+ @app.get("/counter")
113
+ async def counter(req, res, state): # shared app state
114
+ state.visits = (state.visits or 0) + 1
115
+ await res.json({"visits": state.visits})
116
+ ```
117
+
118
+ There is no need to reach through `req.app.state`, `req.app` or fetch handles manually. Just name the parameter and **Flameo** hands you the object directly.
119
+
120
+
121
+ ## Why Flameo?
122
+ - **Faster by design** 🚀 — **Flameo** speaks Granian's native RSGI protocol and also supports Uvicorn/Hypercorn's ASGI protocol. On benchmark it [beats](https://raw.githubusercontent.com/flameohq/flameo/docs/benchmark.html) the likes of FastAPI, Robyn and Sanic.
123
+ - **Named dependencies, not plumbing** — Type `db`, `cache`, `app` or `state` in the handler signature and the managed object arrives.
124
+ - **No framework under the framework** — Flameo depends only on `orjson`, `pydantic`, `aiofiles`, `granian`, and `uvloop` (on Linux and macOS). No Starlette, no ASGI toolkit, no wrapper around a wrapper. What you write is what you debug.
125
+ - **Batteries included** — Managed DB and cache pools, pydantic validation with file upload, sessions, static files, templates, rate limiting, compression, CORS and OpenAPI docs all out of the box.
126
+
127
+ ## Features
128
+ - **Middleware** ⛓️ — global, router, and per-route, sync or async.
129
+ - **Dependency injection** 💉 — `db`, `cache`, `app`, and `state` parameters.
130
+ - **Validation** ✅ — Pydantic request bodies and uploaded files with structured errors.
131
+ - **Template rendering** 🖼️ — built in with Jinja2.
132
+ - **Streaming** 🌊 — chunked responses and Server-Sent Events.
133
+ - **Static files** 📁 — built-in serving with ETag and cache validators.
134
+ - **Compression** 🗜️ — out of the box with gzip, deflate, Brotli, and Zstandard.
135
+ - **Caching** ⚡ — built in both with and without Redis, with framework-managed pools.
136
+ - **Rate limiting** 🚦 — per endpoint or per key.
137
+ - **Sessions and CORS** 🍪 — signed cookies and configurable CORS.
138
+ - **Databases** 🗄️ — framework-managed pools for SQLite, PostgreSQL, MySQL, Oracle, and MongoDB.
139
+ - **API docs** 📚 — OpenAPI with Swagger UI and ReDoc.
140
+ - **Lifecycle** 🧭 — startup and shutdown hooks.
141
+ - **Logging** 📝 — built-in request logging.
142
+ - **CLI** 🧰 — project scaffolding, router generation, and a Granian RSGI runner.
143
+ - **Request limits** 🛠️ — configurable body-size limits.
144
+
145
+ ## Quick Start
146
+
147
+ ```bash
148
+ pip install flameo
149
+ ```
150
+
151
+ ```bash
152
+
153
+ # RSGI — Granian through the Flameo CLI
154
+ flameo run main:app --reload
155
+
156
+ # ASGI — Uvicorn
157
+ uvicorn main:app --reload
158
+ ```
159
+
160
+ Optional extras:
161
+
162
+ ```bash
163
+ pip install "flameo[postgres,cache,templates,compression]"
164
+ ```
165
+
166
+ Replace `postgres` with `mysql`, `sqlite`, `oracle`, or `mongo` for your database.
167
+
168
+
169
+
170
+ ## Optional extras
171
+
172
+ | Extra | Adds |
173
+ | --- | --- |
174
+ | `sqlite` | SQLite driver (`aiosqlite`) |
175
+ | `postgres` | PostgreSQL driver (`asyncpg`) |
176
+ | `mysql` | MySQL driver (`asyncmy` + `cryptography`) |
177
+ | `oracle` | Oracle driver (`oracledb`) |
178
+ | `mongo` | MongoDB driver (`pymongo`) |
179
+ | `database` | All five database drivers |
180
+ | `cache` | Redis client support (works with Redis, Valkey, and Dragonfly) |
181
+ | `templates` | Jinja2 template rendering |
182
+ | `compression` | Brotli and Zstandard codecs |
183
+ | `test` | Test and development dependencies |
184
+
185
+ ## Documentation
186
+
187
+ - [Feature tour](#features)
188
+ - [Optional extras](#optional-extras)
189
+ - [Load-test benchmarks](benchmarks/README.md)
190
+ - [Test scope and coverage map](tests/README.md)
191
+
192
+ ## Contributing
193
+
194
+ Contributions are welcome.
195
+
196
+ - **Report a bug** — open an issue with a minimal reproduction.
197
+ - **Propose a feature** — describe the behavior you want to add.
198
+ - **Send a pull request** — keep changes focused and add tests for new features.
199
+ - **Improve the docs** — examples and clarifications are always appreciated.
200
+
201
+ ## License
202
+
203
+ Distributed under the [MIT License](LICENSE).
flameo-0.1.1/README.md ADDED
@@ -0,0 +1,139 @@
1
+ <div align="center">
2
+ <img src="https://raw.githubusercontent.com/flameohq/flameo/main/flameo_logo.svg" alt="Flameo" width="220">
3
+ </div>
4
+
5
+ <hr />
6
+
7
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-3776AB?logo=python&logoColor=white)](https://www.python.org/)
8
+ [![Tests](https://github.com/flameohq/flameo/actions/workflows/tests.yml/badge.svg)](https://github.com/flameohq/flameo/actions/workflows/tests.yml)
9
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/flameohq/flameo)
10
+ [![Version](https://img.shields.io/badge/version-0.1.1-blue)](https://github.com/flameohq/flameo/blob/main/pyproject.toml)
11
+ [![Protocols](https://img.shields.io/badge/protocols-ASGI%20%7C%20RSGI-ff6b35)](#asgi-rsgi-and-uvloop)
12
+
13
+
14
+ <p align="center">
15
+ <em>Fast, Flexible, Less Verbose Framework. Syntax are as easy as you can think</em>
16
+ </p>
17
+
18
+
19
+ Flameo is a fast, easy to learn and code framework that pairs a minimal, familiar API with Python's flexibility. The same code supports Granians' **RSGI** and also Uvicon/Hypercor's **ASGI** natively.
20
+
21
+ ```python
22
+ from flameo import Flameo
23
+
24
+ app = Flameo()
25
+
26
+ @app.get("/")
27
+ async def home(req, res):
28
+ await res.json({"message": "Hello from Flameo 🔥"})
29
+ ```
30
+
31
+ Handlers receive standard `req` and `res` objects. Add any of `db`, `cache`, `app` or `state` to the signature and **Flameo** injects the managed database handle, cache instance, app instance and app state.
32
+
33
+ ```python
34
+ @app.get("/users")
35
+ async def get_user_json(req, res, db): # request-scoped pooled DB handle provided by Flameo
36
+ rows = await db.fetch("SELECT id, name FROM users") #returns json by default
37
+ await res.json(rows)
38
+
39
+ @app.get("/visits")
40
+ async def visits(req, res, cache): # cache instance (works both with and without Redis)
41
+ total = await cache.incr("visits")
42
+ await res.json({"visits": total})
43
+
44
+ @app.get("/debug")
45
+ async def debug(req, res, app): # the Flameo app instance
46
+ await res.json({"debug": app.debug})
47
+
48
+ @app.get("/counter")
49
+ async def counter(req, res, state): # shared app state
50
+ state.visits = (state.visits or 0) + 1
51
+ await res.json({"visits": state.visits})
52
+ ```
53
+
54
+ There is no need to reach through `req.app.state`, `req.app` or fetch handles manually. Just name the parameter and **Flameo** hands you the object directly.
55
+
56
+
57
+ ## Why Flameo?
58
+ - **Faster by design** 🚀 — **Flameo** speaks Granian's native RSGI protocol and also supports Uvicorn/Hypercorn's ASGI protocol. On benchmark it [beats](https://raw.githubusercontent.com/flameohq/flameo/docs/benchmark.html) the likes of FastAPI, Robyn and Sanic.
59
+ - **Named dependencies, not plumbing** — Type `db`, `cache`, `app` or `state` in the handler signature and the managed object arrives.
60
+ - **No framework under the framework** — Flameo depends only on `orjson`, `pydantic`, `aiofiles`, `granian`, and `uvloop` (on Linux and macOS). No Starlette, no ASGI toolkit, no wrapper around a wrapper. What you write is what you debug.
61
+ - **Batteries included** — Managed DB and cache pools, pydantic validation with file upload, sessions, static files, templates, rate limiting, compression, CORS and OpenAPI docs all out of the box.
62
+
63
+ ## Features
64
+ - **Middleware** ⛓️ — global, router, and per-route, sync or async.
65
+ - **Dependency injection** 💉 — `db`, `cache`, `app`, and `state` parameters.
66
+ - **Validation** ✅ — Pydantic request bodies and uploaded files with structured errors.
67
+ - **Template rendering** 🖼️ — built in with Jinja2.
68
+ - **Streaming** 🌊 — chunked responses and Server-Sent Events.
69
+ - **Static files** 📁 — built-in serving with ETag and cache validators.
70
+ - **Compression** 🗜️ — out of the box with gzip, deflate, Brotli, and Zstandard.
71
+ - **Caching** ⚡ — built in both with and without Redis, with framework-managed pools.
72
+ - **Rate limiting** 🚦 — per endpoint or per key.
73
+ - **Sessions and CORS** 🍪 — signed cookies and configurable CORS.
74
+ - **Databases** 🗄️ — framework-managed pools for SQLite, PostgreSQL, MySQL, Oracle, and MongoDB.
75
+ - **API docs** 📚 — OpenAPI with Swagger UI and ReDoc.
76
+ - **Lifecycle** 🧭 — startup and shutdown hooks.
77
+ - **Logging** 📝 — built-in request logging.
78
+ - **CLI** 🧰 — project scaffolding, router generation, and a Granian RSGI runner.
79
+ - **Request limits** 🛠️ — configurable body-size limits.
80
+
81
+ ## Quick Start
82
+
83
+ ```bash
84
+ pip install flameo
85
+ ```
86
+
87
+ ```bash
88
+
89
+ # RSGI — Granian through the Flameo CLI
90
+ flameo run main:app --reload
91
+
92
+ # ASGI — Uvicorn
93
+ uvicorn main:app --reload
94
+ ```
95
+
96
+ Optional extras:
97
+
98
+ ```bash
99
+ pip install "flameo[postgres,cache,templates,compression]"
100
+ ```
101
+
102
+ Replace `postgres` with `mysql`, `sqlite`, `oracle`, or `mongo` for your database.
103
+
104
+
105
+
106
+ ## Optional extras
107
+
108
+ | Extra | Adds |
109
+ | --- | --- |
110
+ | `sqlite` | SQLite driver (`aiosqlite`) |
111
+ | `postgres` | PostgreSQL driver (`asyncpg`) |
112
+ | `mysql` | MySQL driver (`asyncmy` + `cryptography`) |
113
+ | `oracle` | Oracle driver (`oracledb`) |
114
+ | `mongo` | MongoDB driver (`pymongo`) |
115
+ | `database` | All five database drivers |
116
+ | `cache` | Redis client support (works with Redis, Valkey, and Dragonfly) |
117
+ | `templates` | Jinja2 template rendering |
118
+ | `compression` | Brotli and Zstandard codecs |
119
+ | `test` | Test and development dependencies |
120
+
121
+ ## Documentation
122
+
123
+ - [Feature tour](#features)
124
+ - [Optional extras](#optional-extras)
125
+ - [Load-test benchmarks](benchmarks/README.md)
126
+ - [Test scope and coverage map](tests/README.md)
127
+
128
+ ## Contributing
129
+
130
+ Contributions are welcome.
131
+
132
+ - **Report a bug** — open an issue with a minimal reproduction.
133
+ - **Propose a feature** — describe the behavior you want to add.
134
+ - **Send a pull request** — keep changes focused and add tests for new features.
135
+ - **Improve the docs** — examples and clarifications are always appreciated.
136
+
137
+ ## License
138
+
139
+ Distributed under the [MIT License](LICENSE).
@@ -0,0 +1,15 @@
1
+ from .flameo import (
2
+ Flameo, Router, DBType, CacheType, File, FlameoError, TransactionError,
3
+ )
4
+ from .utils import template_to_string
5
+ from .logger import logger, FlameoLogger, set_log_dir, set_max_log_bytes
6
+ from .validation import ValidationError, is_pydantic_model, validate_model
7
+ from .sessions import Session
8
+ from .docs import build_openapi
9
+
10
+ __all__ = ["DBType", "CacheType", "Flameo", "Router", "File", "template_to_string", "logger",
11
+ "FlameoLogger", "set_log_dir", "set_max_log_bytes",
12
+ "FlameoError", "TransactionError",
13
+ "ValidationError", "is_pydantic_model", "validate_model",
14
+ "Session", "build_openapi"]
15
+
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,197 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from .parser import get_temp_dir
9
+
10
+ _log = logging.getLogger("flameo.cleanup")
11
+
12
+ # Filename prefixes the spill files use. Anything else under the temp
13
+ # dir is left alone (a deploy script might drop a sentinel file there
14
+ # intentionally, e.g. ``.gitkeep``).
15
+ _SPILL_PREFIXES = ("upload_", "body_")
16
+
17
+ # The first pass runs when ``start()`` is scheduled so a fresh process
18
+ # never carries old junk. The periodic timer kicks in afterwards.
19
+ _DEFAULT_INTERVAL = 30 * 60 # 30 minutes
20
+ _DEFAULT_THRESHOLD = 30 * 60 # 30 minutes
21
+
22
+
23
+ def _iter_spill_files(directory: Path):
24
+ """Yield every spill file inside ``directory``.
25
+
26
+ Skips directories, hidden files, and anything whose name does not
27
+ start with one of the known spill prefixes. The check is purely
28
+ lexical -- we don't stat the contents, just hand the Path objects
29
+ to the caller.
30
+ """
31
+ if not directory.exists() or not directory.is_dir():
32
+ return
33
+ try:
34
+ entries = directory.iterdir()
35
+ except OSError:
36
+ return
37
+ for entry in entries:
38
+ if not entry.is_file():
39
+ continue
40
+ name = entry.name
41
+ if name.startswith("."):
42
+ continue
43
+ if not name.startswith(_SPILL_PREFIXES):
44
+ continue
45
+ yield entry
46
+
47
+
48
+ def _sweep_once(threshold_seconds: float) -> int:
49
+ """Synchronous one-shot sweep. Returns number of files removed.
50
+
51
+ Run on a thread via ``asyncio.to_thread`` from the asyncio side
52
+ because ``Path.stat`` and ``Path.unlink`` can block (especially
53
+ on slow disks or large directories). The work is tiny -- a
54
+ single ``iterdir`` + a ``stat`` per file -- but on Windows
55
+ ``iterdir`` can briefly stall, so we keep it off the loop.
56
+ """
57
+ now = time.time()
58
+ threshold_cutoff = now - threshold_seconds
59
+ removed = 0
60
+ for path in _iter_spill_files(get_temp_dir()):
61
+ try:
62
+ mtime = path.stat().st_mtime
63
+ except OSError:
64
+ # File vanished between ``iterdir`` and ``stat`` -- a
65
+ # concurrent request just uploaded it. Move on.
66
+ continue
67
+ if mtime >= threshold_cutoff:
68
+ continue
69
+ try:
70
+ path.unlink()
71
+ removed += 1
72
+ except OSError as e:
73
+ # Permission denied / file in use / etc. Don't crash the
74
+ # sweeper for one stray file -- log and continue. We'll
75
+ # re-evaluate it next interval.
76
+ _log.debug("cleanup: could not delete %s: %s", path, e)
77
+ return removed
78
+
79
+
80
+ class TempSweeper:
81
+ """Background task that periodically cleans stale spill files.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ interval_seconds: float = _DEFAULT_INTERVAL,
87
+ threshold_seconds: float = _DEFAULT_THRESHOLD,
88
+ ):
89
+ if interval_seconds <= 0:
90
+ raise ValueError("interval_seconds must be > 0")
91
+ if threshold_seconds <= 0:
92
+ raise ValueError("threshold_seconds must be > 0")
93
+ self.interval_seconds = interval_seconds
94
+ self.threshold_seconds = threshold_seconds
95
+ self._task: Optional[asyncio.Task] = None
96
+ self._started = False
97
+ self._stopping = asyncio.Event()
98
+
99
+ async def start(self) -> None:
100
+ """Run the startup sweep, then start the periodic timer.
101
+
102
+ Called once during app startup. Returns immediately -- the
103
+ background timer is fire-and-forget until ``stop()``.
104
+ """
105
+ if self._task is not None:
106
+ return
107
+
108
+ if self._started:
109
+ return
110
+
111
+ try:
112
+ get_temp_dir().mkdir(parents=True, exist_ok=True)
113
+ except OSError as e:
114
+ _log.warning("cleanup: cannot create temp dir: %s", e)
115
+ return
116
+ self._started = True
117
+
118
+ try:
119
+ removed = await asyncio.to_thread(_sweep_once, self.threshold_seconds)
120
+ if removed:
121
+ _log.info(
122
+ "cleanup: removed %d stale spill file(s) on startup", removed
123
+ )
124
+ except Exception as e:
125
+ _log.warning("cleanup: startup sweep failed: %s", e)
126
+
127
+ # Periodic timer.
128
+ self._task = asyncio.create_task(
129
+ self._run_periodic(), name="flameo-temp-sweeper"
130
+ )
131
+
132
+ async def stop(self) -> None:
133
+ """Cancel the periodic task. Idempotent."""
134
+ if self._stopping.is_set():
135
+ return
136
+ self._stopping.set()
137
+ task = self._task
138
+ if task is not None and not task.done():
139
+ task.cancel()
140
+ try:
141
+ await task
142
+ except (asyncio.CancelledError, Exception):
143
+ pass
144
+ self._task = None
145
+
146
+ async def _run_periodic(self) -> None:
147
+ """Sleep loop: wait ``interval_seconds``, sweep, repeat.
148
+
149
+ We sleep on ``self._stopping.wait()`` rather than
150
+ ``asyncio.sleep`` so ``stop()`` unblocks immediately instead
151
+ of waiting up to ``interval_seconds`` for the next tick.
152
+ """
153
+ while not self._stopping.is_set():
154
+ try:
155
+ await asyncio.wait_for(
156
+ self._stopping.wait(), timeout=self.interval_seconds
157
+ )
158
+
159
+ break
160
+ except asyncio.TimeoutError:
161
+ pass # normal timer expiry -- run a sweep
162
+
163
+ try:
164
+ removed = await asyncio.to_thread(
165
+ _sweep_once, self.threshold_seconds
166
+ )
167
+ if removed:
168
+ _log.info(
169
+ "cleanup: removed %d stale spill file(s)", removed
170
+ )
171
+ except asyncio.CancelledError:
172
+ raise
173
+ except Exception as e:
174
+ _log.warning("cleanup: periodic sweep failed: %s", e)
175
+
176
+
177
+ def start_sweeper(
178
+ interval_seconds: float = _DEFAULT_INTERVAL,
179
+ threshold_seconds: float = _DEFAULT_THRESHOLD,
180
+ ) -> TempSweeper:
181
+ """Convenience factory used by :class:`Flameo`.
182
+
183
+ Creates a ``TempSweeper`` and calls ``start()`` against the
184
+ currently-running event loop. Returns the started instance so the
185
+ caller can stash it for ``stop()`` on shutdown.
186
+ """
187
+ sweeper = TempSweeper(
188
+ interval_seconds=interval_seconds,
189
+ threshold_seconds=threshold_seconds
190
+ )
191
+
192
+ try:
193
+ loop = asyncio.get_running_loop()
194
+ except RuntimeError:
195
+ return sweeper
196
+ loop.create_task(sweeper.start())
197
+ return sweeper