-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
91 lines (76 loc) · 2.62 KB
/
Copy pathcache.py
File metadata and controls
91 lines (76 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""SQLite-backed result cache for StealthOps (all modes)."""
from __future__ import annotations
import hashlib
import json
import os
import sqlite3
import time
_TTL_TRAINING = 86400 # 24 h — training mode
_TTL_DEFAULT = 21600 # 6 h — personal and server modes
_SWEEP_AGE = 172800 # 48 h — sweep threshold
def _db_path() -> str:
return os.environ.get("CACHE_PATH", os.path.join("cache", "stealthops.db"))
def _open() -> sqlite3.Connection:
path = _db_path()
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
conn = sqlite3.connect(path)
conn.execute("""
CREATE TABLE IF NOT EXISTS result_cache (
key TEXT PRIMARY KEY,
target TEXT NOT NULL,
scope TEXT NOT NULL,
payload TEXT NOT NULL,
fetched_at INTEGER NOT NULL
)
""")
conn.commit()
return conn
def _cache_key(target: str, scope: str) -> str:
return hashlib.sha256(f"{target.lower()}|{scope}".encode()).hexdigest()
def get(target: str, scope: str, ttl: int = _TTL_DEFAULT) -> tuple[dict, int] | None:
"""Return (payload, fetched_at) for (target, scope), or None on miss/expiry."""
key = _cache_key(target, scope)
try:
conn = _open()
try:
row = conn.execute(
"SELECT payload, fetched_at FROM result_cache WHERE key = ?", (key,)
).fetchone()
finally:
conn.close()
if row is None:
return None
payload_json, fetched_at = row
if time.time() - fetched_at > ttl:
return None
return json.loads(payload_json), int(fetched_at)
except Exception:
return None
def put(target: str, scope: str, payload: dict) -> None:
"""Store payload for (target, scope). Silently swallows errors."""
key = _cache_key(target, scope)
try:
conn = _open()
try:
conn.execute(
"INSERT OR REPLACE INTO result_cache "
"(key, target, scope, payload, fetched_at) VALUES (?, ?, ?, ?, ?)",
(key, target.lower(), scope, json.dumps(payload), int(time.time())),
)
conn.commit()
finally:
conn.close()
except Exception:
pass
def sweep() -> None:
"""Delete entries older than 48 hours. Called once at app startup."""
cutoff = int(time.time()) - _SWEEP_AGE
try:
conn = _open()
try:
conn.execute("DELETE FROM result_cache WHERE fetched_at < ?", (cutoff,))
conn.commit()
finally:
conn.close()
except Exception:
pass