Files
devplacepy/devplacepy/services/nodes/cache.py
T
retoorandClaude Sonnet 5.5 02ab747cd0
DevPlace CI / test (push) Failing after 44m45s
Code Farm: per-plot auto-replant pause and crop-lock check; community sync and node work
Continuous Delivery could never be turned off once a crop was planted. Add a
one-shot per-plot "stop after harvest" flag (POST /game/plot/stop, Devii tool
game_plot_stop, game_plots.stop_after_harvest), cleared by the next plant,
autoreplant claim or Refactor. Autoreplant now also respects crop locks through
the shared _crop_lock predicate. Plan and measurements in happyplanting.md.

Also includes the pending community sync, node network and related work in the
tree; the full suite passed (4999) with all of it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 02:23:43 +02:00

157 lines
4.5 KiB
Python

# retoor <retoor@molodetz.nl>
from __future__ import annotations
import base64
import hashlib
import json
import time
from datetime import datetime, timezone
from collections import OrderedDict
from dataclasses import dataclass
from typing import Callable
from devplacepy.database import nodes as store
from devplacepy.services.nodes.spec import SPEC
LIMITS = SPEC.limits
@dataclass(frozen=True)
class CachedResult:
status: int
headers: dict
body: bytes
truncated: bool
stored_at: float
def cache_key(method: str, url: str) -> str:
return hashlib.sha256(f"{method.upper()} {url}".encode()).hexdigest()
class ResultCache:
def __init__(
self,
ttl_seconds: int = LIMITS.cache_ttl_seconds,
max_bytes: int = LIMITS.cache_max_bytes,
entry_max_bytes: int = LIMITS.cache_entry_max_bytes,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.ttl_seconds = max(0, min(ttl_seconds, LIMITS.cache_ttl_seconds))
self.max_bytes = max_bytes
self.entry_max_bytes = min(entry_max_bytes, LIMITS.cache_entry_max_bytes)
self._clock = clock
self._entries: OrderedDict[str, CachedResult] = OrderedDict()
self._bytes = 0
self.hits = 0
self.misses = 0
@property
def size_bytes(self) -> int:
return self._bytes
def __len__(self) -> int:
return len(self._entries)
def _drop(self, key: str) -> None:
entry = self._entries.pop(key, None)
if entry is not None:
self._bytes -= len(entry.body)
def get(self, method: str, url: str) -> CachedResult | None:
key = cache_key(method, url)
entry = self._entries.get(key)
if entry is None:
self.misses += 1
return None
if self._clock() - entry.stored_at >= self.ttl_seconds:
self._drop(key)
self.misses += 1
return None
self._entries.move_to_end(key)
self.hits += 1
return entry
def put(
self,
method: str,
url: str,
status: int,
headers: dict,
body: bytes,
truncated: bool,
age_seconds: float = 0.0,
) -> bool:
if self.ttl_seconds <= 0 or status >= 500 or truncated:
return False
if len(body) > self.entry_max_bytes or len(body) > self.max_bytes:
return False
key = cache_key(method, url)
self._drop(key)
self._entries[key] = CachedResult(
status, dict(headers), body, truncated, self._clock() - age_seconds
)
self._bytes += len(body)
while self._bytes > self.max_bytes and self._entries:
oldest = next(iter(self._entries))
self._drop(oldest)
return True
def clear(self) -> None:
self._entries.clear()
self._bytes = 0
class SharedResultCache(ResultCache):
def get(self, method: str, url: str) -> CachedResult | None:
local = super().get(method, url)
if local is not None:
return local
row = store.cache_get(cache_key(method, url))
if row is None:
return None
try:
headers = json.loads(row["headers"] or "{}")
body = base64.b64decode(row["body"] or "")
stored = datetime.fromisoformat(row["stored_at"])
except (ValueError, TypeError):
return None
age = max(0.0, (datetime.now(timezone.utc) - stored).total_seconds())
if age >= self.ttl_seconds:
return None
super().put(method, url, int(row["status"]), headers, body, False, age_seconds=age)
entry = self._entries.get(cache_key(method, url))
if entry is not None:
self.misses -= 1
self.hits += 1
return entry
def put(
self,
method: str,
url: str,
status: int,
headers: dict,
body: bytes,
truncated: bool,
age_seconds: float = 0.0,
) -> bool:
kept = super().put(method, url, status, headers, body, truncated, age_seconds)
if kept:
store.cache_put(
cache_key(method, url),
method.upper(),
url,
status,
json.dumps(dict(headers)),
base64.b64encode(body).decode(),
len(body),
self.ttl_seconds,
)
return kept
def clear(self) -> None:
super().clear()
store.cache_clear()