forge
Explore
Log in

Don't you dare go Hollow

hezarfen_zeka

Clone
★ 0

0 watching0 forksPython1.9 MiBe01a4faAhmet Kaan Gümüş2 months ago25 commits

cache.py106 lines, 3.3 KiBHistoryRawDownload
1"""Yanit onbellegi: (soru + istem surumu + model) -> yanit.
2
3Neden: tekrar kosular BEDAVA olsun. 3.833 madde x birden fazla varyant x
4kararlilik tekrarlari, onbelleksiz her deneyde bastan ucretlenir.
5
6Anahtar `provider.cache_key()` ile uretilir ve model, sistem istemi, TAM istem
7metni (istem surumu ve sorunun kendisi bunun icindedir), sicaklik ve tekrar
8indeksini kapsar. Bulgu 5 geregi istem surumu anahtarin ayrilmaz parcasidir:
9istem degisince onbellek DOGAL OLARAK gecersizlesir.
10
11Bicim: dizin altinda `<ilk2>/<hash>.json`. Tek dosyalik dev JSON yerine
12parca dosyalar — es zamanli yazimda kayip olmaz, kismi kosu kurtarilabilir.
13"""
14
15from __future__ import annotations
16
17import json
18import os
19import tempfile
20import threading
21from pathlib import Path
22from typing import Any
23
24
25class ResponseCache:
26 """Dosya tabanli, es zamanli yazima dayanikli onbellek."""
27
28 def __init__(self, root: Path | str, *, enabled: bool = True):
29 self.root = Path(root)
30 self.enabled = enabled
31 self._mem: dict[str, dict] = {}
32 self._lock = threading.Lock()
33 self.hits = 0
34 self.misses = 0
35 self.writes = 0
36
37 def _path(self, key: str) -> Path:
38 return self.root / key[:2] / f"{key}.json"
39
40 def get(self, key: str) -> dict[str, Any] | None:
41 if not self.enabled:
42 return None
43 with self._lock:
44 if key in self._mem:
45 self.hits += 1
46 return self._mem[key]
47 p = self._path(key)
48 if not p.exists():
49 with self._lock:
50 self.misses += 1
51 return None
52 try:
53 data = json.loads(p.read_text(encoding="utf-8"))
54 except (OSError, json.JSONDecodeError):
55 # Bozuk onbellek girdisi sessizce DOGRU sayilmaz: yok kabul edilir.
56 with self._lock:
57 self.misses += 1
58 return None
59 with self._lock:
60 self._mem[key] = data
61 self.hits += 1
62 return data
63
64 def put(self, key: str, value: dict[str, Any]) -> None:
65 if not self.enabled:
66 return
67 with self._lock:
68 self._mem[key] = value
69 self.writes += 1
70 p = self._path(key)
71 p.parent.mkdir(parents=True, exist_ok=True)
72 # Atomik yazim: gecici dosya + rename (yarim dosya kalmaz).
73 fd, tmp = tempfile.mkstemp(dir=str(p.parent), suffix=".tmp")
74 try:
75 with os.fdopen(fd, "w", encoding="utf-8") as fh:
76 json.dump(value, fh, ensure_ascii=False)
77 os.replace(tmp, p)
78 except BaseException:
79 try:
80 os.unlink(tmp)
81 except OSError:
82 pass
83 raise
84
85 def stats(self) -> dict[str, int]:
86 with self._lock:
87 return {"hits": self.hits, "misses": self.misses,
88 "writes": self.writes, "mem": len(self._mem)}
89
90 def clear(self) -> int:
91 """Onbellegi siler; silinen dosya sayisini dondurur."""
92 n = 0
93 if self.root.exists():
94 for p in self.root.rglob("*.json"):
95 p.unlink()
96 n += 1
97 with self._lock:
98 self._mem.clear()
99 return n
100
101
102class NullCache(ResponseCache):
103 """Onbelleksiz kosu icin (testlerde yalitim)."""
104
105 def __init__(self):
106 super().__init__(Path("."), enabled=False)