flameo 0.1.1__py3-none-any.whl

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.
flameo/__init__.py ADDED
@@ -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
+
flameo/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
flameo/cleanup.py ADDED
@@ -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