suraj-ml-projects commited on
Commit
f3928e8
Β·
verified Β·
1 Parent(s): 63d5cd4

Upload session_manager_py.py

Browse files
Files changed (1) hide show
  1. session_manager_py.py +209 -0
session_manager_py.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ utils/session_manager.py
3
+ ========================
4
+ Privacy-first temporary session storage manager.
5
+
6
+ Guarantees:
7
+ - Each session gets an isolated /tmp/cineai/<session_id>/ directory
8
+ - All files (video, audio, frames, TTS) auto-deleted after SESSION_TTL_MINUTES
9
+ - Background GC thread sweeps expired sessions every 5 minutes
10
+ - Manual delete available via UI button
11
+ - Never writes outside the temp base dir
12
+ - No database, no persistent logs, no analytics
13
+
14
+ Security:
15
+ - Session IDs are UUIDs (unguessable)
16
+ - Temp dir is mode 700 (user-only readable)
17
+ - Symlink attacks prevented by checking real path
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import uuid
24
+ import shutil
25
+ import time
26
+ import stat
27
+ import threading
28
+ from pathlib import Path
29
+ from typing import Dict, Optional
30
+ from loguru import logger
31
+
32
+
33
+ BASE_TEMP_DIR = Path(os.environ.get("CINEAI_TEMP_DIR", "/tmp/cineai"))
34
+ SESSION_TTL_MINUTES = int(os.environ.get("SESSION_TTL_MINUTES", "60"))
35
+ GC_INTERVAL_SEC = 300 # sweep every 5 minutes
36
+
37
+
38
+ class SessionManager:
39
+ """
40
+ Manages temp storage for a single session.
41
+ Safe to instantiate multiple times with the same session_id.
42
+ """
43
+
44
+ def __init__(self, session_id: str):
45
+ if not _is_safe_id(session_id):
46
+ raise ValueError(f"Invalid session_id: {session_id}")
47
+ self.session_id = session_id
48
+ self._dir = BASE_TEMP_DIR / session_id
49
+ self._created_at = time.time()
50
+
51
+ def get_dir(self) -> Path:
52
+ """Return (and create) the session temp directory."""
53
+ self._dir.mkdir(parents=True, exist_ok=True)
54
+ # Set restrictive permissions (owner only)
55
+ try:
56
+ os.chmod(str(self._dir), stat.S_IRWXU)
57
+ except Exception:
58
+ pass
59
+ return self._dir
60
+
61
+ def get_path(self, filename: str) -> Path:
62
+ """Get a safe path within the session directory."""
63
+ target = (self._dir / filename).resolve()
64
+ # Guard against path traversal
65
+ if not str(target).startswith(str(self._dir.resolve())):
66
+ raise ValueError(f"Path traversal attempt: {filename}")
67
+ return target
68
+
69
+ def write_marker(self) -> None:
70
+ """Write a last-access marker for TTL tracking."""
71
+ marker = self._dir / ".last_access"
72
+ marker.parent.mkdir(parents=True, exist_ok=True)
73
+ marker.touch()
74
+
75
+ def touch(self) -> None:
76
+ """Refresh the TTL marker."""
77
+ marker = self._dir / ".last_access"
78
+ if marker.exists():
79
+ marker.touch()
80
+
81
+ def delete(self) -> None:
82
+ """Immediately delete all session files."""
83
+ try:
84
+ if self._dir.exists():
85
+ shutil.rmtree(str(self._dir), ignore_errors=True)
86
+ logger.info(f"Session {self.session_id} deleted")
87
+ except Exception as e:
88
+ logger.warning(f"Session delete error: {e}")
89
+
90
+ def exists(self) -> bool:
91
+ return self._dir.exists()
92
+
93
+ def size_mb(self) -> float:
94
+ """Return total size of session directory in MB."""
95
+ total = 0
96
+ try:
97
+ for f in self._dir.rglob("*"):
98
+ if f.is_file():
99
+ total += f.stat().st_size
100
+ except Exception:
101
+ pass
102
+ return total / 1e6
103
+
104
+ def list_files(self) -> list:
105
+ """List all files in the session directory."""
106
+ try:
107
+ return [str(f.relative_to(self._dir)) for f in self._dir.rglob("*") if f.is_file()]
108
+ except Exception:
109
+ return []
110
+
111
+
112
+ # ── Global GC thread ──────────────────────────────────────────────────────────
113
+
114
+ class _SessionGC:
115
+ """Background garbage collector for expired sessions."""
116
+
117
+ def __init__(self):
118
+ self._thread: Optional[threading.Thread] = None
119
+ self._stop_event = threading.Event()
120
+ self._started = False
121
+
122
+ def start(self) -> None:
123
+ if self._started:
124
+ return
125
+ self._started = True
126
+ self._thread = threading.Thread(
127
+ target=self._gc_loop,
128
+ name="SessionGC",
129
+ daemon=True,
130
+ )
131
+ self._thread.start()
132
+ logger.info(f"SessionGC started (TTL={SESSION_TTL_MINUTES}min, sweep={GC_INTERVAL_SEC}s)")
133
+
134
+ def _gc_loop(self) -> None:
135
+ while not self._stop_event.wait(GC_INTERVAL_SEC):
136
+ self._sweep()
137
+
138
+ def _sweep(self) -> None:
139
+ if not BASE_TEMP_DIR.exists():
140
+ return
141
+ ttl_sec = SESSION_TTL_MINUTES * 60
142
+ now = time.time()
143
+ swept = 0
144
+ try:
145
+ for entry in BASE_TEMP_DIR.iterdir():
146
+ if not entry.is_dir():
147
+ continue
148
+ # Skip obviously non-session dirs
149
+ if not _is_safe_id(entry.name):
150
+ continue
151
+ # Check last-access marker
152
+ marker = entry / ".last_access"
153
+ if marker.exists():
154
+ age = now - marker.stat().st_mtime
155
+ else:
156
+ # No marker β†’ use directory mtime
157
+ age = now - entry.stat().st_mtime
158
+
159
+ if age > ttl_sec:
160
+ try:
161
+ shutil.rmtree(str(entry), ignore_errors=True)
162
+ swept += 1
163
+ logger.info(f"GC: swept session {entry.name} (age={age/60:.1f}min)")
164
+ except Exception as e:
165
+ logger.warning(f"GC: failed to sweep {entry.name}: {e}")
166
+ except Exception as e:
167
+ logger.warning(f"GC sweep error: {e}")
168
+
169
+ if swept:
170
+ logger.info(f"GC: swept {swept} expired sessions")
171
+
172
+ def stop(self) -> None:
173
+ self._stop_event.set()
174
+
175
+
176
+ # ── Module-level GC (auto-start on import) ────────────────────────────────────
177
+ _gc = _SessionGC()
178
+ _gc.start()
179
+
180
+
181
+ # ── Session ID factory ────────────────────────────────────────────────────────
182
+
183
+ def new_session_id() -> str:
184
+ return str(uuid.uuid4())
185
+
186
+
187
+ def _is_safe_id(sid: str) -> bool:
188
+ """Only allow UUID-like session IDs to prevent path injection."""
189
+ import re
190
+ return bool(re.fullmatch(r'[a-f0-9\-]{36}', sid))
191
+
192
+
193
+ # ── Convenience: delete session by ID ─────────────────────────────────────────
194
+
195
+ def delete_session(session_id: str) -> None:
196
+ mgr = SessionManager(session_id)
197
+ mgr.delete()
198
+
199
+
200
+ def get_all_sessions() -> Dict[str, float]:
201
+ """Return {session_id: size_mb} for all active sessions."""
202
+ result = {}
203
+ if not BASE_TEMP_DIR.exists():
204
+ return result
205
+ for entry in BASE_TEMP_DIR.iterdir():
206
+ if entry.is_dir() and _is_safe_id(entry.name):
207
+ mgr = SessionManager(entry.name)
208
+ result[entry.name] = mgr.size_mb()
209
+ return result