File size: 1,773 Bytes
44094a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import logging
from dataclasses import dataclass
from typing import Any, Optional

import redis

logger = logging.getLogger(__name__)


@dataclass
class CacheConfig:
    url: str = "redis://localhost:6379/0"
    prefix: str = "image_search"
    default_ttl: int = 300


class CacheClient:
    """Thin wrapper around Redis for small metadata caches."""

    def __init__(self, config: CacheConfig):
        self.config = config
        self.client: Optional[redis.Redis] = None
        self._connect()

    def _connect(self) -> None:
        try:
            self.client = redis.from_url(self.config.url, decode_responses=True)
            self.client.ping()
            logger.info("Connected to Redis cache at %s", self.config.url)
        except Exception as exc:
            logger.warning("Redis cache unavailable: %s", exc)
            self.client = None

    def get(self, key: str) -> Optional[Any]:
        if not self.client:
            return None
        namespaced = f"{self.config.prefix}:{key}"
        data = self.client.get(namespaced)
        if data is None:
            return None
        try:
            return json.loads(data)
        except json.JSONDecodeError:
            return data

    def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
        if not self.client:
            return
        namespaced = f"{self.config.prefix}:{key}"
        payload = json.dumps(value) if not isinstance(value, str) else value
        self.client.set(namespaced, payload, ex=ttl or self.config.default_ttl)

    def delete(self, key: str) -> None:
        if not self.client:
            return
        namespaced = f"{self.config.prefix}:{key}"
        self.client.delete(namespaced)