Spaces:
Paused

File size: 4,388 Bytes
269e07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Two-tier deterministic image cache: local disk (LRU by size) then the store backend
(cache/maps/…). Rendering is serialised per key so concurrent identical requests render once.
"""

from __future__ import annotations

import logging
import os
import threading
import time
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path

from wmb.store.backend import Backend
from wmb.store.layout import image_cache_path

log = logging.getLogger(__name__)


@dataclass
class CacheResult:
    key: str
    data: bytes
    source: str          # "local" | "remote" | "render"
    elapsed_ms: int


class ImageCache:
    def __init__(self, local_dir: Path, backend: Backend | None, max_bytes: int, remote_enabled: bool = True):
        self.dir = local_dir
        self.dir.mkdir(parents=True, exist_ok=True)
        self.backend = backend if remote_enabled else None
        self.max_bytes = max_bytes
        self._locks: dict[str, threading.Lock] = {}
        self._locks_guard = threading.Lock()
        self._last_evict = 0.0

    def _path(self, key: str) -> Path:
        return self.dir / key[:2] / f"{key}.png"

    def _lock(self, key: str) -> threading.Lock:
        with self._locks_guard:
            return self._locks.setdefault(key, threading.Lock())

    def get(self, key: str) -> bytes | None:
        p = self._path(key)
        if p.is_file():
            try:
                os.utime(p, None)
                return p.read_bytes()
            except OSError:
                return None
        return None

    def get_or_render(self, key: str, render: Callable[[], bytes]) -> CacheResult:
        t0 = time.monotonic()
        data = self.get(key)
        if data is not None:
            return CacheResult(key, data, "local", int((time.monotonic() - t0) * 1000))
        with self._lock(key):
            data = self.get(key)
            if data is not None:
                return CacheResult(key, data, "local", int((time.monotonic() - t0) * 1000))
            if self.backend is not None:
                try:
                    remote = self.backend.read_bytes(image_cache_path(key))
                except Exception as e:  # remote cache must never break rendering
                    log.warning("remote cache read failed: %s", e)
                    remote = None
                if remote:
                    self._store_local(key, remote)
                    return CacheResult(key, remote, "remote", int((time.monotonic() - t0) * 1000))
            data = render()
            self._store_local(key, data)
            if self.backend is not None:
                threading.Thread(target=self._store_remote, args=(key, data), daemon=True).start()
            return CacheResult(key, data, "render", int((time.monotonic() - t0) * 1000))

    def _store_local(self, key: str, data: bytes) -> None:
        p = self._path(key)
        p.parent.mkdir(parents=True, exist_ok=True)
        tmp = p.with_suffix(f".{os.getpid()}.tmp")
        tmp.write_bytes(data)
        os.replace(tmp, p)
        if time.monotonic() - self._last_evict > 60:
            self._last_evict = time.monotonic()
            threading.Thread(target=self.evict, daemon=True).start()

    def _store_remote(self, key: str, data: bytes) -> None:
        try:
            self.backend.write_bytes(image_cache_path(key), data)  # type: ignore[union-attr]
        except Exception as e:
            log.warning("remote cache write failed: %s", e)

    def evict(self) -> int:
        files = []
        for p in self.dir.rglob("*.png"):
            try:
                st = p.stat()
                files.append((st.st_atime, st.st_size, p))
            except OSError:
                continue
        total = sum(s for _, s, _ in files)
        freed = 0
        for _, size, p in sorted(files):
            if total - freed <= self.max_bytes:
                break
            try:
                p.unlink()
                freed += size
            except OSError:
                pass
        return freed

    def stats(self) -> dict:
        n, total = 0, 0
        for p in self.dir.rglob("*.png"):
            try:
                total += p.stat().st_size
                n += 1
            except OSError:
                pass
        return {"files": n, "bytes": total, "max_bytes": self.max_bytes, "remote": self.backend is not None}