File size: 1,517 Bytes
b32fbe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Knowledge Universe β€” Cache Strategy
Defines TTL and eviction policy per data type.
"""
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class CacheTier(str, Enum):
    HOT   = "hot"    # Frequently accessed, short TTL
    WARM  = "warm"   # Normal requests
    COLD  = "cold"   # Rarely accessed, long TTL


@dataclass
class CachePolicy:
    tier:      CacheTier
    ttl_secs:  int
    max_size:  Optional[int] = None   # max bytes, None = unlimited


# Policies per namespace
CACHE_POLICIES = {
    "req":     CachePolicy(CacheTier.HOT,  ttl_secs=14_400),   # 4h  β€” request results
    "source":  CachePolicy(CacheTier.WARM, ttl_secs=43_200),   # 12h β€” source metadata
    "index":   CachePolicy(CacheTier.COLD, ttl_secs=86_400),   # 24h β€” index/catalog
    "decay":   CachePolicy(CacheTier.WARM, ttl_secs=21_600),   # 6h  β€” decay scores
    "ku:key":  CachePolicy(CacheTier.HOT,  ttl_secs=0),        # 0   = no expiry (API keys)
    "ku:usage":CachePolicy(CacheTier.HOT,  ttl_secs=2_678_400),# 31d β€” monthly counters
}


def get_policy(key: str) -> CachePolicy:
    """Return cache policy for a given key by matching its namespace prefix."""
    for prefix, policy in CACHE_POLICIES.items():
        if key.startswith(prefix):
            return policy
    # Default: warm tier, 4h TTL
    return CachePolicy(CacheTier.WARM, ttl_secs=14_400)


def get_ttl(key: str) -> int:
    """Convenience: return TTL seconds for a key."""
    return get_policy(key).ttl_secs