Files
NODEDC_MISSION_CORE/src/k1link/cache_budget.py
T

124 lines
4.6 KiB
Python

"""Publication budgets for local derived caches; never evicts retained data.
Existing generations, unknown files and in-flight files all count. Budget
exhaustion refuses a new disk copy; callers that can work without it may skip it.
This is a publication quota, not a filesystem quota for renderer scratch output.
"""
from __future__ import annotations
import os
import shutil
import stat
import threading
from collections.abc import Callable
from contextlib import contextmanager
from pathlib import Path
GiB = 1024**3
MiB = 1024**2
LIMITS = {
"camera-frame-cache": 256 * MiB,
"lidar-read-cache": 16 * MiB,
"camera-media-index": 64 * MiB,
"perception-overlays": GiB,
"calibrated-fusion-overlays": GiB,
"integrated-perception-overlays": 4 * GiB,
"laboratory-rerun-overlays": 4 * GiB,
"observatory-portable-replay-cache": 4 * GiB,
"editor-cache": 4 * GiB,
"urban-maps": GiB,
}
FREE_RESERVE = 2 * GiB
_LOCK = threading.RLock()
_LOCK_NAME = ".publication-budget.lock"
class CacheCapacityError(ValueError):
pass
def usage(root: Path) -> tuple[int, int]:
total = count = 0
for base, directories, files in os.walk(root, followlinks=False):
for name in directories + files:
p = Path(base) / name
s = p.lstat()
if stat.S_ISDIR(s.st_mode):
continue
if not stat.S_ISREG(s.st_mode):
raise CacheCapacityError("Cache contains an unsafe path; preserved")
if p == root / _LOCK_NAME:
continue
total += s.st_size
count += 1
if count > 100000:
raise CacheCapacityError("Cache inventory exceeds its file budget; preserved")
return total, count
@contextmanager
def cache_publication(
root: Path,
additional_bytes: int | Callable[[], int],
*,
kind=None,
limit=None,
reserve=FREE_RESERVE,
max_files=10000,
error_type=CacheCapacityError,
):
"""Lock admission through publication. Count temporary bytes already on disk.
additional_bytes includes only bytes not yet in this root; a file renamed
within it contributes zero additional bytes. Callers include sidecar overhead.
A callable computes the reservation under the publication lock, for writers
that must recheck deduplication after waiting for another publisher.
Unknown legacy contents stay in place even if already above the new limit.
"""
root = root.expanduser().absolute()
maximum = LIMITS[kind or root.name] if limit is None else limit
if maximum < 1 or (
not callable(additional_bytes)
and (type(additional_bytes) is not int or additional_bytes < 0)
):
raise ValueError("Invalid cache publication budget")
ancestor = root
while not ancestor.exists():
ancestor = ancestor.parent
if ancestor.resolve() != ancestor:
raise CacheCapacityError("Cache ancestor is not canonical")
root.mkdir(mode=0o700, parents=True, exist_ok=True)
if root.resolve() != root or not stat.S_ISDIR(root.lstat().st_mode):
raise CacheCapacityError("Cache root is not canonical")
with _LOCK:
fd = os.open(root / _LOCK_NAME, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
try:
s = os.fstat(fd)
if not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_uid != os.getuid():
raise CacheCapacityError("Unsafe cache publication lock")
# Operator cache publication is Mac/Linux owned, never the remote Worker.
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX)
reserved = additional_bytes() if callable(additional_bytes) else additional_bytes
if type(reserved) is not int or reserved < 0:
raise ValueError("Invalid cache publication budget")
current, count = usage(root)
if current + reserved > maximum or count >= max_files:
raise CacheCapacityError("Достигнут лимит кэша. Сохранённые данные не удалены.")
if shutil.disk_usage(root).free < reserved + reserve:
raise CacheCapacityError("Недостаточно свободного места для новой копии кэша.")
yield
except CacheCapacityError as exc:
if error_type is CacheCapacityError:
raise
raise error_type(str(exc)) from exc
finally:
os.close(fd)
def require_cache_room(root: Path, additional_bytes=0, **kwargs):
with cache_publication(root, additional_bytes, **kwargs):
pass