Repository navigation
Expand file tree
/
Copy pathcache_manager.py
More file actions
1521 lines (1341 loc) · 66.6 KB
/
Copy pathcache_manager.py
File metadata and controls
1521 lines (1341 loc) · 66.6 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
מנהל Cache מתקדם עם Redis
Advanced Cache Manager with Redis
"""
import json
import logging
import os
import time
import re
import hashlib
from functools import wraps
from typing import (
Any,
Dict,
List,
Optional,
Union,
Callable,
TypeVar,
ParamSpec,
Coroutine,
Iterator,
Sequence,
cast,
Tuple,
)
import copy
import random
import threading
try:
import redis
except Exception: # redis אינו חובה – נריץ במצב מושבת אם חסר
redis = None
import asyncio
from datetime import datetime, timedelta
from runtime_settings import redis_timeouts, safe_mode_enabled
logger = logging.getLogger(__name__)
# מטריקות Prometheus (best-effort) — רישום חסין כפילויות
try: # pragma: no cover
from prometheus_client import Counter, Histogram, REGISTRY
except Exception: # pragma: no cover
Counter = Histogram = REGISTRY = None
def _ensure_metric(name: str, create_fn):
"""יוצר או מחזיר מטריקה קיימת באותו שם מ-REGISTRY.
המטרה: למנוע ValueError על רישום כפול כאשר המודול נטען מחדש (importlib.reload).
"""
# אם prometheus_client לא זמין, נחזיר None כדי שהקוד יקצר דרך best-effort
if REGISTRY is None:
try:
return create_fn() # ייתכן שמחזיר None ממילא
except Exception:
return None
try:
# שימוש ב-API פנימי אך יציב יחסית כדי לאתר קולקטור קיים
existing = getattr(REGISTRY, "_names_to_collectors", {}).get(name)
if existing is not None:
return existing
except Exception:
# נפילה שקטה — ננסה ליצור ונחזור אם תתרחש כפילות
pass
try:
return create_fn()
except Exception:
# במקרה של ValueError: Duplicated timeseries... נחפש ונחזיר את הקיים
try:
return getattr(REGISTRY, "_names_to_collectors", {}).get(name)
except Exception:
return None
# Cache metrics (labels kept minimal) — נרשמות באופן אידמפוטנטי
cache_hits_total = _ensure_metric(
"cache_hits_total",
lambda: Counter("cache_hits_total", "Total cache hits", ["backend"]) if Counter else None,
)
cache_misses_total = _ensure_metric(
"cache_misses_total",
lambda: Counter("cache_misses_total", "Total cache misses", ["backend"]) if Counter else None,
)
cache_op_duration_seconds = _ensure_metric(
"cache_op_duration_seconds",
lambda: (
Histogram(
"cache_op_duration_seconds",
"Cache operation duration in seconds",
["operation", "backend"],
)
if Histogram
else None
),
)
# ===================== Dynamic TTL utilities =====================
class DynamicTTL:
"""ניהול TTL דינמי לפי סוג תוכן וקונטקסט.
הערכים כאן מייצגים TTL בסיסי בשניות עבור סוגי תוכן שכיחים.
"""
BASE_TTL: Dict[str, int] = {
"user_stats": 600, # 10 דקות
"file_content": 3600, # שעה
"file_list": 300, # 5 דקות
"markdown_render": 1800, # 30 דקות
"search_results": 180, # 3 דקות
"public_stats": 600, # 10 דקות
"bookmarks": 120, # 2 דקות
"tags": 300, # 5 דקות
"settings": 60, # דקה
"sticky_summary": 60, # דקה (מרגיע polling)
# Collections (My Collections) – TTL מומלץ לפי המדריך
"collections_list": 60,
"collections_detail": 30,
"collections_items": 180,
}
@classmethod
def calculate_ttl(cls, content_type: str, context: Dict[str, Any] | None = None) -> int:
"""חשב TTL בסיסי מוכוון קונטקסט.
מבטיח גבולות בטוחים: מינימום 60 שניות, מקסימום 7200 (שעתיים).
"""
ctx: Dict[str, Any] = context or {}
base_ttl: int = int(cls.BASE_TTL.get(content_type, 300))
# התאמות לפי קונטקסט
if bool(ctx.get("is_favorite")):
base_ttl = int(base_ttl * 1.5)
try:
last_mod_hours = float(ctx.get("last_modified_hours_ago", 24))
except Exception:
last_mod_hours = 24.0
if last_mod_hours < 1.0:
base_ttl = int(base_ttl * 0.5)
if str(ctx.get("access_frequency", "low")).lower() == "high":
base_ttl = int(base_ttl * 2)
if str(ctx.get("user_tier", "regular")).lower() == "premium":
# משתמשי פרימיום יעדיפו עדכונים מהירים
base_ttl = int(base_ttl * 0.7)
return max(60, min(base_ttl, 7200))
class ActivityBasedTTL:
"""התאמת TTL לפי שעות פעילות (best-effort)."""
@staticmethod
def _now_hour() -> int:
try:
from datetime import datetime
return int(datetime.now().hour)
except Exception:
return 12
@classmethod
def get_activity_multiplier(cls) -> float:
hour = cls._now_hour()
if 9 <= hour < 18: # שעות שיא – קצר יותר
return 0.7
if 18 <= hour < 23: # ערב – בינוני
return 1.0
return 1.5 # לילה – ארוך יותר
@classmethod
def adjust_ttl(cls, base_ttl: int) -> int:
try:
mult = float(cls.get_activity_multiplier())
except Exception:
mult = 1.0
# הוסף jitter קטן למניעת thundering herd
ttl = int(max(1, base_ttl) * mult)
jitter = int(max(1, ttl // 10)) # עד ±10%
try:
ttl = ttl + random.randint(-jitter, jitter)
except Exception:
pass
return max(60, min(int(ttl), 7200))
def build_cache_key(*parts: Any) -> str:
"""בניית מפתח cache יעיל ומובנה מהחלקים הנתונים.
- מסנן חלקים ריקים
- ממיר לתווים בטוחים (רווחים/סלאשים)
- מגביל אורך ומוסיף hash קצר במידת הצורך
"""
from hashlib import sha256
clean_parts: List[str] = [str(p) for p in parts if p not in (None, "")]
key: str = ":".join(clean_parts)
key = key.replace(" ", "_").replace("/", "-")
if len(key) > 200:
key_hash = sha256(key.encode("utf-8")).hexdigest()[:8]
key = f"{key[:150]}:{key_hash}"
return key
class CacheManager:
"""מנהל Cache מתקדם עם Redis"""
def __init__(self):
# Debug זמני לניתוח Hit/Miss/Set (ברירת מחדל: כבוי)
# ניתן להפעיל ידנית דרך enable_debug_for(seconds)
self.debug_until: float = 0.0
self.redis_client = None
self.is_enabled = False
self.connect()
def enable_debug_for(self, seconds: int) -> float:
"""הפעל/הארך חלון דיבאג זמני ללוגים של HIT/MISS/SET.
- אם seconds <= 0: מכבה דיבאג (debug_until=0)
- אחרת: מאריך (לא מקצר) את החלון כך שיסתיים לפחות בעוד seconds שניות מהעכשיו
מחזיר את timestamp החדש של debug_until.
"""
try:
sec = int(seconds)
except Exception:
sec = 0
if sec <= 0:
self.debug_until = 0.0
return float(self.debug_until)
now = float(time.time())
new_until = float(now + sec)
try:
self.debug_until = float(
max(float(getattr(self, "debug_until", 0.0) or 0.0), new_until)
)
except Exception:
self.debug_until = float(new_until)
return float(self.debug_until)
def _debug_active(self) -> bool:
try:
return float(time.time()) < float(getattr(self, "debug_until", 0.0) or 0.0)
except Exception:
return False
def _debug_log(self, action: str, key: str, **extra: Any) -> None:
"""לוג דיבאג מבוקר־זמן עבור פעולות קאש."""
if not self._debug_active():
return
try:
safe_key = str(key)
if len(safe_key) > 300:
safe_key = safe_key[:300] + "…"
if extra:
logger.info("cache %s key=%s extra=%s", str(action), safe_key, extra)
else:
logger.info("cache %s key=%s", str(action), safe_key)
except Exception:
# דיבאג לא אמור להפיל זרימה
return
@staticmethod
def _resolve_redis_url(cfg: Any) -> Optional[str]:
"""כתובת ה-Redis לשימוש, או None אם הקאש אמור להיות מושבת.
קדימות ל-ENV: אם המשתנה הוגדר (גם אם ריק) זה אות להשבתה מפורשת
בטסטים/CI. גם ערך שמתחיל ב-"disabled" נחשב השבתה.
"""
env_url = os.getenv("REDIS_URL")
if env_url is not None:
url = env_url
else:
url = getattr(cfg, "REDIS_URL", None) if cfg is not None else None
if not url or str(url).strip() == "" or str(url).startswith("disabled"):
return None
return str(url)
@staticmethod
def _cache_disabled_explicitly(cfg: Any) -> bool:
"""האם ביקשו לכבות את הקאש דרך CACHE_ENABLED, בלי למחוק את ה-URL.
ברירת המחדל היא "פעיל", כדי לשמור על ההתנהגות שהייתה עד היום:
ההגדרה לא נקראה כלל, ושירות עם REDIS_URL תמיד קיבל קאש.
"""
env_flag = os.getenv("CACHE_ENABLED")
if env_flag is not None:
return str(env_flag).strip().lower() not in ("1", "true", "yes", "y", "on")
cfg_flag = getattr(cfg, "CACHE_ENABLED", True) if cfg is not None else True
return not bool(cfg_flag)
def connect(self):
"""התחברות ל-Redis"""
try:
if redis is None:
self.is_enabled = False
logger.info("חבילת redis לא מותקנת – Cache מושבת")
return
# קונפיג דרך pydantic אם זמין, אחרת ENV ישיר – לשמירת תאימות
try:
from config import config as _cfg
except Exception:
_cfg = None
redis_url = self._resolve_redis_url(_cfg)
if not redis_url:
self.is_enabled = False
logger.info("Redis אינו מוגדר - Cache מושבת")
return
if self._cache_disabled_explicitly(_cfg):
self.is_enabled = False
logger.info("CACHE_ENABLED=false - Cache מושבת במפורש")
return
# ה-timeouts מוכרעים במקום אחד בלבד. קודם ההכרעה ישבה כאן, עם
# ברירות מחדל משלה (5 ו-5) שסתרו את אלה שב-config.py (3 ו-5),
# והענף של SAFE_MODE לא נגע לעולם — כי השדה בקונפיג אף פעם לא
# היה None.
socket_connect_timeout, socket_timeout = redis_timeouts(_cfg)
try:
max_conns_env = (
str(getattr(_cfg, "REDIS_MAX_CONNECTIONS", "") or "")
if _cfg is not None
else ""
) or os.getenv("REDIS_MAX_CONNECTIONS")
max_connections = (
int(max_conns_env)
if max_conns_env not in (None, "")
else int(getattr(_cfg, "REDIS_MAX_CONNECTIONS", 50) if _cfg is not None else 50)
)
except Exception:
max_connections = int(
getattr(_cfg, "REDIS_MAX_CONNECTIONS", 50) if _cfg is not None else 50
)
self.redis_client = redis.from_url(
redis_url,
decode_responses=True,
socket_connect_timeout=socket_connect_timeout,
socket_timeout=socket_timeout,
retry_on_timeout=True,
health_check_interval=30,
max_connections=max_connections,
)
# בדיקת חיבור
self.redis_client.ping()
self.is_enabled = True
logger.info("התחברות ל-Redis הצליחה - Cache מופעל")
except Exception as e:
logger.warning(f"לא ניתן להתחבר ל-Redis: {e} - Cache מושבת")
self.is_enabled = False
def _make_key(self, prefix: str, *args, **kwargs) -> str:
"""יוצר מפתח cache ייחודי"""
def _clean_repr(s: str) -> str:
# מנקה כתובות זיכרון נפוצות ב-repr ברירת מחדל: "0x7f...."
return re.sub(r"0x[0-9a-fA-F]+", "0x", str(s or ""))
def _stable_scalar(v: Any) -> Optional[str]:
"""החזר ייצוג מחרוזתי לטיפוסים פשוטים בלבד; אחרת None.
חשוב: מחרוזת ריקה היא ערך לגיטימי ולכן אינה משמשת כסנטינל.
"""
if v is None:
return "None"
if isinstance(v, (str, int, float, bool)):
# str("") חייב להישמר כ-"" ולא להיחשב "לא scalar"
return str(v)
if isinstance(v, (bytes, bytearray)):
h = hashlib.sha256(bytes(v)).hexdigest()[:16]
return f"bytes:{h}"
return None
def _stable_part(v: Any, *, _depth: int = 0) -> str:
# 1) טיפוסים פשוטים
scalar = _stable_scalar(v)
if scalar is not None:
return scalar
# 2) מבנים מובנים עם סדר דטרמיניסטי
if isinstance(v, (list, tuple)):
if _depth >= 3:
try:
return f"[len={len(v)}]"
except Exception:
return "[len=?]"
return "[" + ",".join(_stable_part(x, _depth=_depth + 1) for x in v) + "]"
if isinstance(v, set):
if _depth >= 3:
try:
return f"{{len={len(v)}}}"
except Exception:
return "{len=?}"
return "{" + ",".join(sorted(_stable_part(x, _depth=_depth + 1) for x in v)) + "}"
if isinstance(v, dict):
if _depth >= 3:
try:
return f"{{len={len(v)}}}"
except Exception:
return "{len=?}"
try:
items = sorted(v.items(), key=lambda kv: str(kv[0]))
except Exception:
items = list(v.items())
# הגבלת גודל כדי למנוע מפתחות ענקיים
limited = items[:30]
return (
"{"
+ ",".join(
f"{_stable_part(k, _depth=_depth + 1)}={_stable_part(val, _depth=_depth + 1)}"
for k, val in limited
)
+ ("…" if len(items) > 30 else "")
+ "}"
)
# 3) אובייקטים עם מזהה מוכר: נשתמש רק במזהה (כדי למנוע כתובות זיכרון במפתח)
for attr in ("user_id", "id", "pk", "uuid"):
try:
if hasattr(v, attr):
ident = getattr(v, attr)
ident_scalar = _stable_scalar(ident)
if ident_scalar is not None:
return ident_scalar
return _clean_repr(str(ident))
except Exception:
continue
# 4) אובייקטים "רגילים" עם __dict__: נבנה fingerprint דטרמיניסטי מהתוכן (מוגבל עומק/גודל)
try:
cls = v.__class__
cls_name = f"{getattr(cls, '__module__', '')}.{getattr(cls, '__qualname__', getattr(cls, '__name__', 'object'))}"
except Exception:
cls_name = "object"
try:
if (
_depth < 3
and hasattr(v, "__dict__")
and isinstance(getattr(v, "__dict__", None), dict)
):
d = cast(dict, getattr(v, "__dict__", {}) or {})
if d:
try:
items = sorted(d.items(), key=lambda kv: str(kv[0]))
except Exception:
items = list(d.items())
# דוגמים רק חלק מהשדות כדי להימנע מהעמסה/דליפה של נתונים כבדים
sampled: dict[str, str] = {}
for k, val in items[:25]:
try:
sampled[str(k)] = _stable_part(val, _depth=_depth + 1)
except Exception:
sampled[str(k)] = "<?>"
material = json.dumps(sampled, sort_keys=True, ensure_ascii=False)
h = hashlib.sha256(
f"{cls_name}:{material}".encode("utf-8", errors="ignore")
).hexdigest()[:16]
return f"{cls_name}:{h}"
except Exception:
# ניפול ל-fallback הבא
pass
# 5) fallback אחרון: hash דטרמיניסטי על בסיס class + repr נקי
try:
raw = _clean_repr(str(v))
except Exception:
raw = ""
material = f"{cls_name}:{raw}"
h = hashlib.sha256(material.encode("utf-8", errors="ignore")).hexdigest()[:16]
return f"{cls_name}:{h}"
key_parts: List[str] = [str(prefix)]
key_parts.extend(_stable_part(arg) for arg in args)
if kwargs:
try:
sorted_kwargs = sorted(kwargs.items(), key=lambda kv: str(kv[0]))
except Exception:
sorted_kwargs = list(kwargs.items())
key_parts.extend(f"{str(k)}:{_stable_part(v)}" for k, v in sorted_kwargs)
return ":".join(key_parts)
def get(self, key: str) -> Optional[Any]:
"""קבלת ערך מה-cache"""
if not self.is_enabled:
return None
backend = "redis"
timer_ctx = (
cache_op_duration_seconds.labels(operation="get", backend=backend).time()
if cache_op_duration_seconds
else None
)
try:
value = self.redis_client.get(key)
if value:
if cache_hits_total is not None:
cache_hits_total.labels(backend=backend).inc()
self._debug_log("HIT", key)
return json.loads(value)
if cache_misses_total is not None:
cache_misses_total.labels(backend=backend).inc()
self._debug_log("MISS", key)
except Exception as e:
logger.error(f"שגיאה בקריאה מ-cache: {e}")
finally:
try:
if timer_ctx:
timer_ctx() # stop timer
except Exception:
pass
return None
def set(self, key: str, value: Any, expire_seconds: int = 300) -> bool:
"""שמירת ערך ב-cache"""
if not self.is_enabled:
return False
backend = "redis"
timer_ctx = (
cache_op_duration_seconds.labels(operation="set", backend=backend).time()
if cache_op_duration_seconds
else None
)
try:
serialized = json.dumps(value, default=str, ensure_ascii=False)
# תמיכה בלקוחות ללא setex: ננסה set(ex=) או set+expire
client = self.redis_client
if hasattr(client, "setex"):
ok = bool(client.setex(key, expire_seconds, serialized))
self._debug_log("SET", key, ok=ok, ttl=int(expire_seconds))
return ok
# חלק מהלקוחות תומכים ב-ex ב-set
try:
ok = bool(client.set(key, serialized, ex=expire_seconds))
self._debug_log("SET", key, ok=ok, ttl=int(expire_seconds))
return ok
except Exception:
pass
# נסה set ואז expire
ok = bool(client.set(key, serialized))
try:
_ = client.expire(key, int(expire_seconds))
except Exception:
pass
self._debug_log("SET", key, ok=ok, ttl=int(expire_seconds))
return ok
except Exception as e:
logger.error(f"שגיאה בכתיבה ל-cache: {e}")
return False
finally:
try:
if timer_ctx:
timer_ctx()
except Exception:
pass
# ===================== Dynamic TTL helpers =====================
def set_dynamic(
self,
key: str,
value: Any,
content_type: str,
context: Optional[Dict[str, Any]] = None,
) -> bool:
"""שמירה ב-cache עם TTL דינמי ותיעוד מינימלי במטריקות/לוגים."""
# חישוב TTL דינמי וביצוע התאמות פעילות + jitter
base_ttl = DynamicTTL.calculate_ttl(content_type, context or {})
adjusted_ttl = ActivityBasedTTL.adjust_ttl(base_ttl)
try:
logger.debug(
"cache_set_dynamic",
extra={
"key": str(key)[:120],
"ttl": int(adjusted_ttl),
"content_type": str(content_type),
},
)
except Exception:
pass
return self.set(key, value, int(adjusted_ttl))
def get_with_refresh(
self,
key: str,
refresh_func: Callable[[], Any],
*,
content_type: str,
context: Optional[Dict[str, Any]] = None,
) -> Any:
"""קריאה מ-cache; אם חסר – מחשב, שומר דינמית ומחזיר."""
cached_value = self.get(key)
if cached_value is not None:
return cached_value
fresh_value = refresh_func()
if fresh_value is not None:
try:
self.set_dynamic(key, fresh_value, content_type, context)
except Exception:
# Fail-open: אם שמירה נכשלה לא נשבור זרימה
pass
return fresh_value
def delete(self, key: str) -> bool:
"""מחיקת ערך מה-cache"""
if not self.is_enabled:
return False
backend = "redis"
timer_ctx = (
cache_op_duration_seconds.labels(operation="delete", backend=backend).time()
if cache_op_duration_seconds
else None
)
try:
return bool(self.redis_client.delete(key))
except Exception as e:
logger.error(f"שגיאה במחיקה מ-cache: {e}")
return False
finally:
try:
if timer_ctx:
timer_ctx()
except Exception:
pass
def _warn_invalidation_is_local_only(self) -> None:
"""מתריע פעם אחת שביטול הקאש מוגבל לתהליך הנוכחי.
בלי זה, קריאת ביטול שמחזירה 0 נראית בדיוק כמו הצלחה — וזה בדיוק
הסוג של כשל שקט שהסתיר את הבאג המקורי. פעם אחת בלבד, כדי שהאזהרה
לא תוצף בכל תצוגה.
"""
if getattr(self, "_warned_local_only_invalidation", False):
return
self._warned_local_only_invalidation = True
logger.warning(
"cache_invalidation_local_only: Redis אינו זמין, ולכן ביטול הקאש "
"חל רק על הפולבק שבתהליך הזה. נתונים שחייבים להיות טריים לא "
"אמורים לעבור דרך הקאש."
)
def delete_pattern(self, pattern: str) -> int:
"""מחיקת כל המפתחות שמתאימים לתבנית, ב-Redis ובפולבק המקומי גם יחד.
מקרה פרטי של :meth:`delete_patterns` עם דפוס אחד, וכל התיעוד שם חל
גם כאן. נשארת כי היא ה-API שרוב הקוראים בריפו משתמשים בו.
"""
return self.delete_patterns([pattern])
def delete_patterns(self, patterns: Sequence[str]) -> int:
"""מחיקת כל המפתחות שמתאימים ל**אחד** מהדפוסים, בקריאה אחת.
הפולבק המקומי מנוקה תמיד ולפני בדיקת ``is_enabled``: הוא מאוכלס דווקא
כש-Redis אינו זמין, ולכן דילוג עליו כאן משאיר נתונים ישנים בזיכרון עד
שה-TTL פג — גם אחרי כתיבה שהצליחה.
**סריקה נפרדת לכל דפוס, עם ``MATCH`` בצד השרת.** גרסת ביניים של
הפונקציה הזו הריצה סריקה אחת בלי ``MATCH`` וסיננה בפייתון, ונמדדה
מול Redis 7 עם 200,000 מפתחות (flask-limiter, סשנים וקאש חולקים
אותו מסד): ``delete_pattern`` עם דפוס יחיד משך **200,007 מפתחות**
לתהליך כדי למחוק אחד. יש בריפו עשרות קוראים כאלה, וב-MCP הקריאה
רצה על ה-worker היחיד של ``_WRITE_POOL`` — כלומר עדכון תיאור אחד
חסם כל כתיבה אחרת למשך המשיכה. ``MATCH`` אינו מקצר את המעבר של
Redis על ה-keyspace, אבל הוא קובע מה חוצה את הרשת ומה מעובד כאן:
עם ``match`` חוזרים רק המפתחות שמתאימים. מספר ה-roundtrips לתבנית
הוא DBSIZE / :data:`_SCAN_COUNT`, וזה — כפול ה-RTT — מה שקובע את
זמן הקריאה בייצור; הנימוק למספר כתוב על הקבוע.
**מה כן מאוחד:** תקציב הזמן, ה-batch, והספירה. הצורה המקורית
קראה ל-``delete_pattern`` בלולאה וכל קריאה קיבלה
``CACHE_DELETE_PATTERN_BUDGET_SECONDS`` משלה — עשרה דפוסים יכלו
לחסום עד 50 שניות. כאן הדדליין אחד לכל הקריאה.
**מפתח שהותאם לעולם אינו נזרק.** בצורה הקודמת, כשהתקציב נגמר, ה-
``batch`` החלקי — עד 199 מפתחות שכבר עברו התאמה — נזרק בלי ``DEL``,
והתוצאה הייתה בדיוק הקאש הישן שהניקוי בא להסיר. כאן ה-batch
נשטף לפני **כל** יציאה, כולל מיצוי תקציב וחריגה; ומיצוי תקציב
נרשם ב-``WARNING`` עם מספר הדפוסים שהושלמו, כי ניקוי חלקי שנראה
כמו ניקוי מלא הוא הכשל השקט של הפונקציה הזו.
**שני סירובים שהם שגיאת קורא, ולכן זורקים ולא נבלעים:**
- מחרוזת במקום רשימה — ``TypeError``. ``str`` עומד ב-``Sequence[str]``,
ו-``[str(p) for p in "file_content:*"]`` מתפרק לדפוס לכל תו; התו
``*`` לבדו מתאים ל**כל** מפתח. טעות של תו אחד בין ``delete_pattern``
ל-``delete_patterns`` הייתה מוחקת את המסד כולו, כולל מוני
ה-rate-limit.
- דפוס שמתאים לכל מפתח (``*``, ``**``, ``?*`` — בלי תו מילולי
כלל) — ``ValueError``. ניקוי של כל הקאש עובר דרך :meth:`clear_all`,
שעושה זאת במפורש ובמבוקר, ולא דרך כאן. **הקריטריון הוא "אין
תו מילולי בכלל" ולא "אין תו מילולי לפני הכוכבית הראשונה":**
``*:user:{uid}:*`` ב-:meth:`invalidate_user_cache` מתחיל בכוכבית
ואינו מתאים לכל מפתח — הוא דורש ``:user:{uid}:`` — והצורה השנייה
הייתה פוסלת אותו.
על הערך המוחזר: המספר סופר רק מה שנמחק *בתהליך הזה*. שתי מגבלות
שהקורא חייב להכיר, כי אף אחת מהן לא משתקפת במספר:
1. הפולבק המקומי הוא פר-תהליך. עם יותר מ-worker אחד, ניקוי כאן לא
נוגע בעותקים של ה-workers האחרים. נתון שאסור להגיש ישן — למשל
מספר גרסה — לא יכול להסתמך על הקאש הזה בכלל, בשום מצב.
2. כש-Redis אינו זמין, 0 אינו מבחין בין "לא היה מה למחוק" לבין
"לא יכולתי לגשת". לכן המצב נרשם ללוג פעם אחת במקום להיבלע.
"""
# שני הסירובים יושבים **לפני** ה-try, אחרת ה-except הכללי שלמטה
# היה בולע אותם ומחזיר 0 — כלומר "לא היה מה למחוק" על שגיאת קורא.
if isinstance(patterns, (str, bytes)):
raise TypeError(
"delete_patterns מקבל רשימת דפוסים, לא מחרוזת. מחרוזת הייתה "
"מתפרקת לדפוס לכל תו, ו-'*' לבדו מוחק את כל המסד. "
"לדפוס יחיד: delete_pattern(pattern)."
)
pattern_list = [str(p) for p in (patterns or [])]
if not pattern_list:
return 0
for pattern in pattern_list:
if _matches_every_key(pattern):
logger.error(
"cache delete_patterns: סירוב לדפוס %r — הוא מתאים לכל מפתח. "
"ניקוי מלא עובר דרך clear_all(), לא דרך כאן.",
pattern,
)
raise ValueError(
f"הדפוס {pattern!r} מתאים לכל מפתח ב-Redis. ניקוי מלא של הקאש "
"הוא clear_all(); delete_patterns מסרב לו בכוונה."
)
deleted_local = 0
for pattern in pattern_list:
deleted_local += _delete_local_cache_pattern(pattern)
if not self.is_enabled:
self._warn_invalidation_is_local_only()
return deleted_local
backend = "redis"
timer_ctx = (
cache_op_duration_seconds.labels(operation="delete_pattern", backend=backend).time()
if cache_op_duration_seconds
else None
)
deleted = 0
batch: List[Any] = []
batch_size = 200
client: Any = None
def _flush() -> None:
"""DEL על מה שכבר הותאם. נקרא לפני כל יציאה, ולכן לא זורק."""
nonlocal deleted
if not batch:
return
try:
deleted += int(client.delete(*batch) or 0)
except Exception as e:
logger.warning("cache delete_patterns: DEL של %d מפתחות נכשל: %s", len(batch), e)
batch.clear()
try:
client = self.redis_client
# תואם Redis MATCH pattern (במקרים של FakeRedis/scan_iter שלא מכבד match)
import fnmatch
import re as _re
# תקציב זמן כדי להימנע מחסימת תהליך במאגרים גדולים — **אחד לכל
# הקריאה**, ולא אחד לכל דפוס.
budget_seconds = float(
os.getenv(
"CACHE_DELETE_PATTERN_BUDGET_SECONDS",
os.getenv("CACHE_CLEAR_BUDGET_SECONDS", "5"),
)
)
deadline = time.time() + max(0.0, budget_seconds)
if not hasattr(client, "scan_iter") and not hasattr(client, "scan"):
if not hasattr(client, "keys"):
# אין יכולת סריקה בטוחה -> אל תמחוק
return deleted_local
# fallback שמיועד *רק* ללקוחות Fake בטסטים.
# חשוב: ב-Redis אמיתי scan_iter קיים ולכן לא נגיע לכאן.
mod = str(getattr(getattr(client, "__class__", object), "__module__", "") or "")
if mod.startswith("redis"):
# ב-Redis אמיתי לא נרשה שימוש ב-KEYS
return deleted_local
found: List[Any] = []
seen_keys: set = set()
for pattern in pattern_list:
for k in client.keys(pattern) or []:
if k not in seen_keys:
seen_keys.add(k)
found.append(k)
if found:
try:
return deleted_local + int(client.delete(*found) or 0)
except Exception:
return deleted_local
return deleted_local
# ``SCAN`` יכול להחזיר את אותו מפתח פעמיים באותו מעבר, ומפתח יכול
# להתאים לשני דפוסים. ``seen`` שומר את הספירה נכונה ואת ה-batch
# בלי כפילויות; הוא גדל רק במספר המפתחות שנמחקו.
seen: set = set()
exhausted = False
patterns_done = 0
try:
for pattern in pattern_list:
if time.time() > deadline:
exhausted = True
break
matcher = _re.compile(fnmatch.translate(pattern))
for k in _scan_matching(client, pattern):
if time.time() > deadline:
exhausted = True
break
ks = str(k)
# הגנה נוספת: חלק מלקוחות Fake לא מכבדים match ב-scan_iter
if ks in seen or not matcher.match(ks):
continue
seen.add(ks)
batch.append(k)
if len(batch) >= batch_size:
_flush()
if exhausted:
break
patterns_done += 1
finally:
# לפני כל יציאה — תקציב, חריגה, או סיום רגיל. מה שכבר הותאם
# נמחק; אחרת מיצוי תקציב היה משאיר בדיוק את המפתחות
# שהניקוי בא להסיר.
_flush()
if exhausted:
logger.warning(
"cache delete_patterns: תקציב %.1fs נגמר אחרי %d/%d דפוסים — "
"הניקוי **חלקי**. נמחקו %d מפתחות; הדפוס שנקטע: %r",
budget_seconds,
patterns_done,
len(pattern_list),
deleted,
pattern_list[min(patterns_done, len(pattern_list) - 1)],
)
return deleted_local + int(deleted)
except Exception as e:
# ``deleted`` כולל את מה שנשטף ב-finally הפנימי לפני החריגה.
logger.error(f"שגיאה במחיקת תבנית מ-cache (נמחקו {deleted} לפני הכשל): {e}")
return deleted_local + int(deleted)
finally:
try:
if timer_ctx:
timer_ctx()
except Exception:
pass
def invalidate_user_cache(self, user_id: int) -> int:
"""מחיקת כל ה-cache של משתמש ספציפי"""
# התאמה רחבה יותר למפתחות כפי שהם נוצרים כיום ב-_make_key
# המפתחות נראים כך: "<prefix>:<func_name>:<self>:<user_id>:..."
# לכן נמחק לפי prefixes הרלוונטיים ולפי user_id גולמי.
total_deleted = 0
try:
patterns = [
f"*:user:{user_id}:*", # תמיכה לאחור אם יתווסף prefix "user:" בעתיד
f"user_files:*:{user_id}:*", # רשימת קבצי משתמש
f"latest_version:*:{user_id}:*", # גרסה אחרונה לקובץ
f"search_code:*:{user_id}:*", # תוצאות חיפוש למשתמש
f"user_stats:*:{user_id}", # סטטיסטיקות משתמש — מסתיים ב-:<user_id>
f"user_stats:*:{user_id}:*", # גיבוי: אם יתווספו פרמטרים/סופיות בעתיד
f"*:{user_id}:*", # נפילה לאחור: כל מפתח שמכיל את המזהה
f"*:{user_id}", # נפילה לאחור: מפתחות שמסתיימים במזהה
]
# קריאה אחת ולא לולאה על ``delete_pattern``: תקציב זמן אחד לכל
# השמונה במקום שמונה נפרדים, ו-batch שנשטף גם כשהתקציב נגמר.
# הסריקות עצמן נשארות אחת לכל דפוס, עם ``MATCH`` בשרת — ראו
# :meth:`delete_patterns`.
total_deleted += int(self.delete_patterns(patterns) or 0)
except Exception as e:
logger.warning(f"invalidate_user_cache failed for user {user_id}: {e}")
# חשוב: זהו מספר המחיקות בפועל כפי ש-Redis החזיר מהפקודת DEL (לא רק מספר דפוסים).
logger.info(
f"invalidate_user_cache: נמחקו בפועל {total_deleted} מפתחות עבור משתמש {user_id} (Redis + פולבק מקומי)"
)
return total_deleted
def clear_all(self) -> int:
"""ניקוי כל המטמון באופן מבוקר.
- הפולבק המקומי מנוקה תמיד, גם כש-Redis מושבת. אחרת "נקה הכל"
משאיר בדיוק את הקאש שפעיל כשאין Redis.
- אם Redis פעיל – מוחק גם את כל המפתחות שלו באמצעות SCAN+DEL
(best-effort).
"""
deleted_local = _clear_local_cache()
if not self.is_enabled:
return deleted_local
deleted = deleted_local
try:
client = self.redis_client
# תקציב זמן לניקוי כדי לא לחסום worker אם Redis איטי
budget_seconds = float(os.getenv("CACHE_CLEAR_BUDGET_SECONDS", "5"))
deadline = time.time() + max(0.0, budget_seconds)
if hasattr(client, "scan_iter"):
for k in client.scan_iter(match="*", count=500):
if time.time() > deadline:
break
try:
deleted += int(client.delete(k) or 0)
except Exception:
pass
if time.time() > deadline:
break
else:
# Fallback: keys + delete
keys = client.keys("*")
if keys:
deleted += int(client.delete(*keys) or 0)
except Exception as e:
logger.warning(f"clear_all failed: {e}")
logger.info(f"ניקוי cache מלא: {deleted} מפתחות נמחקו (Redis + פולבק מקומי)")
return deleted
# ===================== Invalidation helpers (tag/pattern-based) =====================
def invalidate_file_related(
self, file_id: str, user_id: Optional[Union[int, str]] = None
) -> int:
"""ביטול קאש לפי קובץ: תוכן/רינדור/רשימות.
דפוסים נפוצים מעוגנים לאחור בהתאם למפתחות הקיימים בקוד.
אין כאן יציאה מוקדמת על ``is_enabled``: ``delete_pattern`` מנקה גם את
הפולבק המקומי, שקיים דווקא כש-Redis כבוי. דילוג כאן היה משאיר את
הערכים הישנים בזיכרון.
"""
total = 0
try:
patterns = [
f"file_content:{file_id}*",
f"markdown_render:{file_id}*",
f"md_render:{file_id}*",
# המפתח בפועל של תצוגת ה-Markdown הוא web:md_preview:user:{uid}:{file_id}:{hash};
# בלי דפוס זה עריכת קובץ לא מבטלת את ה-cache שלו (הוא נשאר עד ה-TTL).
f"web:md_preview:user:*:{file_id}:*",
]
if user_id is not None:
uid = str(user_id)
patterns.extend(
[
f"web:files:user:{uid}:*",
f"user_files:*:{uid}:*",
f"latest_version:*:{uid}:*",
# שלוש הרשימות הבאות נושאות ``description`` ו-``tags``
# של הגרסה האחרונה, בדיוק השדות שראוט העדכון המהיר
# כותב — ולכן ניקוי שמדלג עליהן מעדכן את הרשומה
# ומשאיר את מה שהמשתמש רואה על הערך הישן.
#
# ``search_code`` הוא החמור: ``@cached`` שלו הוא 300
# שניות (``database/repository.py``,
# ``_search_code_cached``), כלומר חיפוש שהחזיר את
# התיאור הישן עוד חמש דקות אחרי שהוא שונה. שתי
# האחרות קצרות (20 שניות) ונכללות כי זו אותה מחלקה
# ולא מופע — כל רשימה שמחזירה מטא-דאטה של הגרסה
# האחרונה מתיישנת מאותה כתיבה בדיוק.
#
# ``invalidate_user_cache`` תפס אותן ממילא דרך
# ה-fallback הרחב ``*:{user_id}:*`` שיש שם ואין כאן,
# ולכן הפער היה גלוי רק למי שהשווה את שתי הרשימות.
f"search_code:*:{uid}:*",
f"regular_files:*:{uid}:*",
f"files_by_repo:*:{uid}:*",
]
)
# קריאה אחת ולא לולאה על ``delete_pattern``: תקציב זמן אחד לכל
# העשרה במקום עשרה נפרדים, ו-batch שנשטף גם כשהתקציב נגמר. ראו
# :meth:`delete_patterns` — ולמה הסריקות עצמן נשארות אחת לכל
# דפוס עם ``MATCH`` בשרת.
total += int(self.delete_patterns(patterns) or 0)
except Exception as e:
logger.warning(f"invalidate_file_related failed: {e}")
return total
def clear_stale(self, max_scan: int = 1000, ttl_seconds_threshold: int = 60) -> int:
"""מחיקת מפתחות שכבר עומדים לפוג ("stale") בצורה עדינה.
היגיון: