File size: 4,459 Bytes
e42eec2
 
 
657756a
e42eec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import time
import re
from config import REDIS_URL

REDIS_AVAILABLE = False
try:
    import redis
    REDIS_AVAILABLE = True
except ImportError:
    print("⚠️ WARNING: 'redis' library not installed. Caching will fall back to local in-memory dictionaries.")

# --- SMART STORAGE MEMORY NODE LAYERS ---
redis_client = None
IN_MEMORY_CACHE = {}
IN_MEMORY_EXPIRY = {}

if REDIS_AVAILABLE and REDIS_URL:
    try:
        redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
        redis_client.ping()
        print("📶 [Cache Setup] Connected securely to remote Redis server node.")
    except Exception as e:
        print(f"⚠️ [Cache Setup] Redis connection failed ({e}). Defaulting to internal memory arrays.")
        redis_client = None

def get_cache_key(product_name: str, size: str = "", mode: str = "balanced") -> str:
    """Generates a unique deterministic cache key combining name, size, and search mode"""
    clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip())
    clean_size = re.sub(r'[^a-z0-9 ]', '', size.lower().strip()) if size else "nosize"
    clean_name = clean_name.replace(" ", "_")
    clean_size = clean_size.replace(" ", "_")
    return f"tarz:cache:{clean_name}:{clean_size}:{mode}"

def get_cached_deals(product_name: str, size: str = "", mode: str = "balanced") -> list:
    """Retrieves cached pricing data array if available and unexpired"""
    key = get_cache_key(product_name, size, mode)
    if redis_client:
        try:
            data = redis_client.get(key)
            if data: return json.loads(data)
        except Exception as e:
            print(f"⚠️ [Redis Cache Error] Read failed: {e}")
    else:
        if key in IN_MEMORY_CACHE:
            if time.time() < IN_MEMORY_EXPIRY.get(key, 0):
                return IN_MEMORY_CACHE[key]
            else:
                del IN_MEMORY_CACHE[key]
                del IN_MEMORY_EXPIRY[key]
    return None

def set_cached_deals(product_name: str, size: str, mode: str, deals: list):
    """Caches product list matrix with strict 2-hour sliding validation lifetime"""
    if not deals: return
    key = get_cache_key(product_name, size, mode)
    if redis_client:
        try:
            redis_client.setex(key, 7200, json.dumps(deals))
        except Exception as e:
            print(f"⚠️ [Redis Cache Error] Write failed: {e}")
    else:
        IN_MEMORY_CACHE[key] = deals
        IN_MEMORY_EXPIRY[key] = time.time() + 7200

def get_base_price(product_name: str, size: str = "", mode: str = "balanced") -> float:
    """Retrieves the previous cycle's lowest observed stable price benchmark"""
    key = get_cache_key(product_name, size, mode).replace("tarz:cache:", "tarz:baseprice:")
    if redis_client:
        try:
            val = redis_client.get(key)
            if val: return float(val)
        except: pass
    else:
        return IN_MEMORY_CACHE.get(key)
    return None

def set_base_price(product_name: str, size: str, mode: str, price: float):
    """Saves a new lowest benchmark configuration when an active shift is confirmed"""
    key = get_cache_key(product_name, size, mode).replace("tarz:cache:", "tarz:baseprice:")
    if redis_client:
        try: redis_client.set(key, str(price))
        except: pass
    else:
        IN_MEMORY_CACHE[key] = price

def get_cached_coupons(product_name: str) -> list:
    """Retrieves isolated promotional matrices matching strict text layout structures"""
    clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")
    key = f"tarz:coupons:{clean_name}"
    if redis_client:
        try:
            data = redis_client.get(key)
            if data: return json.loads(data)
        except: pass
    else:
        if key in IN_MEMORY_CACHE:
            if time.time() < IN_MEMORY_EXPIRY.get(key, 0):
                return IN_MEMORY_CACHE[key]
    return None

def set_cached_coupons(product_name: str, coupons: list):
    """Caches discovered active promo strings (saves empty results for 15 mins to prevent loop spam)"""
    clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")
    key = f"tarz:coupons:{clean_name}"
    duration = 7200 if coupons else 900
    if redis_client:
        try: redis_client.setex(key, duration, json.dumps(coupons))
        except: pass
    else:
        IN_MEMORY_CACHE[key] = coupons
        IN_MEMORY_EXPIRY[key] = time.time() + duration