"""Replicated DHT value store. Two merge strategies are supported: ``lww`` (last write wins) Used for single valued keys such as ``profile/``. The newest record (by timestamp) replaces the previous one. ``grow`` (grow-only set) Used for keys below ``log/`` such as ``log/room/``. Values are JSON arrays of items carrying an ``id``; replicated copies are merged by union so that concurrent writers never lose each other's messages. This is what gives the chat log store-and-forward behaviour without a central server. """ from __future__ import annotations import json import time from dataclasses import dataclass MAX_VALUE_BYTES = 48 * 1024 MAX_GROW_ITEMS = 200 def merge_mode(key: str) -> str: return "grow" if key.startswith("log/") else "lww" @dataclass class Record: key: str value: bytes publisher: bytes timestamp: float expires_at: float @property def expired(self) -> bool: return time.time() > self.expires_at def merge_grow(existing: bytes, incoming: bytes) -> bytes: """Union two JSON encoded item lists, keeping the newest ``MAX_GROW_ITEMS``.""" items: dict[str, dict] = {} for blob in (existing, incoming): if not blob: continue try: parsed = json.loads(blob.decode("utf-8")) except (ValueError, UnicodeDecodeError): continue if not isinstance(parsed, list): continue for item in parsed: if not isinstance(item, dict): continue item_id = str(item.get("id") or "") if not item_id: continue previous = items.get(item_id) if previous is None or float(item.get("ts", 0)) > float( previous.get("ts", 0) ): items[item_id] = item ordered = sorted(items.values(), key=lambda i: float(i.get("ts", 0))) return json.dumps(ordered[-MAX_GROW_ITEMS:], separators=(",", ":")).encode("utf-8") def merge_records(key: str, blobs: list[bytes]) -> list[bytes]: """Combine records read back from several replicas into one value.""" blobs = [blob for blob in blobs if blob] if not blobs: return [] if merge_mode(key) == "grow": merged = b"" for blob in blobs: merged = merge_grow(merged, blob) return [merged] if merged else [] best = blobs[-1] best_ts = float("-inf") for blob in blobs: try: ts = float(json.loads(blob.decode("utf-8")).get("ts", 0)) except (ValueError, UnicodeDecodeError, AttributeError): ts = float("-inf") if ts >= best_ts: best_ts, best = ts, blob return [best] class ValueStore: """In-memory, TTL based value store hosted by every DHT node.""" def __init__(self, capacity: int = 4000) -> None: self.capacity = capacity self._records: dict[str, Record] = {} def __len__(self) -> int: return len(self._records) def store( self, key: str, value: bytes, publisher: bytes, ttl: float, timestamp: float | None = None, ) -> bool: """Store ``value``; returns True when the incoming copy was accepted.""" if len(value) > MAX_VALUE_BYTES: return False now = time.time() timestamp = now if timestamp is None else timestamp current = self._records.get(key) if current is not None and current.expired: current = None if merge_mode(key) == "grow": merged = merge_grow(current.value if current else b"", value) if current is not None and merged == current.value: return False record = Record(key, merged, publisher, timestamp, now + ttl) else: if current is not None: if current.publisher == publisher and current.timestamp > timestamp: return False if current.timestamp > timestamp: return False record = Record(key, value, publisher, timestamp, now + ttl) self._records[key] = record if len(self._records) > self.capacity: self._evict() return True def get(self, key: str) -> Record | None: record = self._records.get(key) if record is None: return None if record.expired: del self._records[key] return None return record def cleanup(self) -> int: expired = [k for k, r in self._records.items() if r.expired] for key in expired: del self._records[key] return len(expired) def _evict(self) -> None: # Drop expired entries first, then the oldest ones. self.cleanup() overflow = len(self._records) - self.capacity if overflow <= 0: return ordered = sorted(self._records.items(), key=lambda kv: kv[1].timestamp) for key, _ in ordered[:overflow]: del self._records[key] def stats(self) -> dict: return {"records": len(self._records), "capacity": self.capacity}