"""Bounded standalone WAN sample store. Does not use or write Django models.""" from __future__ import annotations import hashlib import json import math import os import re import sqlite3 import uuid from datetime import datetime, timedelta, timezone from pathlib import Path MAX_BODY_BYTES = 65536 MAX_BATCH = 60 MAX_NODES = 32 MAX_POINTS = 3600 HISTORY_SECONDS = 3600 DEFAULT_HISTORY_SECONDS = 300 MAX_RESPONSE_POINTS = 2000 MAX_RESPONSE_BYTES = 1024 * 1024 FRESHNESS_SECONDS = 15 MAX_INT = 2**63 - 1 MAX_SEQUENCE = 2**53 - 1 MAX_RATE = 10**12 INTERFACE = re.compile(r"[A-Za-z0-9_.-]{1,15}\Z") EXCLUDED = re.compile(r"(?:lo\Z|tailscale|tun|tap|utun|wg|docker|veth|virbr|br[.-])", re.I) QUALITIES = {"baseline", "ok", "reset", "gap", "interface_changed", "boot_changed"} SCHEMA = """ CREATE TABLE IF NOT EXISTS samples ( id INTEGER PRIMARY KEY, node_id INTEGER NOT NULL, counter_epoch TEXT NOT NULL, sequence INTEGER NOT NULL, boot_id TEXT NOT NULL, interface TEXT NOT NULL, observed_us INTEGER NOT NULL, monotonic_ns INTEGER NOT NULL, interval_seconds REAL NOT NULL, rx_bytes INTEGER NOT NULL, tx_bytes INTEGER NOT NULL, rx_rate INTEGER, tx_rate INTEGER, quality TEXT NOT NULL, gap_before INTEGER NOT NULL, dropped_samples_before INTEGER NOT NULL, payload_sha256 TEXT NOT NULL, received_us INTEGER NOT NULL, UNIQUE(node_id,counter_epoch,sequence) ); CREATE INDEX IF NOT EXISTS samples_node_time ON samples(node_id,observed_us,id); CREATE INDEX IF NOT EXISTS samples_time ON samples(observed_us); PRAGMA user_version=1; """ class InvalidSample(ValueError): pass def store_path(): return Path(os.environ.get("TOPLC_HOST_TRAFFIC_DB", "/var/lib/toplc-vpn-host-traffic/host-traffic.sqlite3")) def _require(value, message): if not value: raise InvalidSample(message) def _integer(value, maximum=MAX_INT): _require(type(value) is int and 0 <= value <= maximum, "invalid integer") return value def _finite(value, minimum, maximum): _require(type(value) in (int, float) and math.isfinite(value) and minimum <= value <= maximum, "invalid numeric value") return float(value) def _uuid(value): _require(isinstance(value, str) and len(value) <= 36, "invalid counter identity") try: return str(uuid.UUID(value)) except (ValueError, AttributeError) as exc: raise InvalidSample("invalid counter identity") from exc def timestamp(value): _require(isinstance(value, str) and len(value) <= 40, "invalid observation timestamp") try: parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError as exc: raise InvalidSample("invalid observation timestamp") from exc _require(parsed.tzinfo is not None, "observation timestamp requires timezone") return parsed.astimezone(timezone.utc) def microseconds(value): return int(value.timestamp() * 1_000_000) def iso_from_us(value): return datetime.fromtimestamp(value / 1_000_000, timezone.utc).isoformat() def parse_batch(body, expected_slug, now): _require(len(body) <= MAX_BODY_BYTES, "batch too large") try: payload = json.loads(body) except (ValueError, UnicodeDecodeError) as exc: raise InvalidSample("invalid JSON") from exc required = {"contract", "node_slug", "boot_id", "interface", "kind", "counter_semantics", "samples"} _require(isinstance(payload, dict) and set(payload) == required, "unexpected batch fields") _require(type(payload["contract"]) is int and payload["contract"] == 1, "invalid contract") _require(payload["node_slug"] == expected_slug, "node identity mismatch") _require(payload["kind"] == "server_host_interface" and payload["counter_semantics"] == "linux_proc_net_dev_interface_bytes", "invalid counter semantics") interface = payload["interface"] _require(isinstance(interface, str) and INTERFACE.fullmatch(interface) and not EXCLUDED.match(interface), "invalid WAN interface") boot = _uuid(payload["boot_id"]) samples = payload["samples"] _require(isinstance(samples, list) and 1 <= len(samples) <= MAX_BATCH, "invalid batch count") points = [] fields = {"sequence", "observed_at", "monotonic_ns", "counter_epoch", "interval_seconds", "rx_bytes", "tx_bytes", "rx_bytes_per_second", "tx_bytes_per_second", "quality"} optional = {"gap_before", "dropped_samples_before"} for item in samples: _require(isinstance(item, dict) and fields.issubset(item) and set(item).issubset(fields | optional), "unexpected sample fields") seq = _integer(item["sequence"], MAX_SEQUENCE) mono = _integer(item["monotonic_ns"]) _require(mono > 0, "monotonic clock must be positive") epoch = _uuid(item["counter_epoch"]) observed = timestamp(item["observed_at"]) _require(now - timedelta(seconds=HISTORY_SECONDS) <= observed <= now + timedelta(seconds=5), "observation timestamp outside window") quality = item["quality"] _require(quality in QUALITIES, "invalid sample quality") interval = _finite(item["interval_seconds"], 0, HISTORY_SECONDS) rx = _integer(item["rx_bytes"]) tx = _integer(item["tx_bytes"]) rates = [item["rx_bytes_per_second"], item["tx_bytes_per_second"]] if quality == "ok": _require(.5 <= interval <= 3, "invalid regular sample interval") rates = [_finite(value, 0, MAX_RATE) for value in rates] else: _require(rates == [None, None], "baseline/reset/gap must not claim rates") gap = item.get("gap_before", False) _require(type(gap) is bool, "invalid gap flag") dropped = _integer(item.get("dropped_samples_before", 0), 1_000_000) normalized = dict(sequence=seq, observed_at=observed.isoformat(), monotonic_ns=mono, counter_epoch=epoch, interval_seconds=interval, rx_bytes=rx, tx_bytes=tx, rx_bytes_per_second=rates[0], tx_bytes_per_second=rates[1], quality=quality, gap_before=gap, dropped_samples_before=dropped, boot_id=boot, interface=interface) normalized["payload_sha256"] = hashlib.sha256(json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()).hexdigest() normalized["observed_us"] = microseconds(observed) if points: _require(seq > points[-1]["sequence"] and observed >= timestamp(points[-1]["observed_at"]), "batch must be ordered") points.append(normalized) return points def initialize(path=None): path = Path(path) if path is not None else store_path() path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) database = sqlite3.connect(path, timeout=2) try: database.execute("PRAGMA journal_mode=WAL") database.execute("PRAGMA busy_timeout=2000") database.execute("PRAGMA journal_size_limit=8388608") database.execute("PRAGMA wal_autocheckpoint=256") database.executescript(SCHEMA) finally: database.close() try: path.chmod(0o600) except OSError: pass def _connect(path, readonly=False): path = Path(path) if not path.is_file(): raise sqlite3.OperationalError("sample store is not initialized") # mode=ro never creates a database; initialization is an explicit deploy step. mode = "ro" if readonly else "rw" connection = sqlite3.connect(path.resolve().as_uri() + "?mode=" + mode, uri=True, timeout=2) connection.row_factory = sqlite3.Row connection.execute("PRAGMA busy_timeout=2000") if readonly: connection.execute("PRAGMA query_only=ON") else: connection.execute("PRAGMA wal_autocheckpoint=256") connection.execute("PRAGMA journal_size_limit=8388608") return connection def _derived(point, previous): quality = point["quality"] gap = bool(point["gap_before"] or point["dropped_samples_before"]) rx_rate = tx_rate = None if previous is None: return None, None, quality if quality != "ok" else "gap", True same_epoch = point["counter_epoch"] == previous["counter_epoch"] if same_epoch: _require(point["boot_id"] == previous["boot_id"] and point["interface"] == previous["interface"], "identity change requires new epoch") _require(point["sequence"] > previous["sequence"] and point["monotonic_ns"] > previous["monotonic_ns"], "sequence/clock must advance") _require(point["rx_bytes"] >= previous["rx_bytes"] and point["tx_bytes"] >= previous["tx_bytes"], "counter reset requires new epoch") skipped = point["sequence"] != previous["sequence"] + 1 gap = gap or skipped if quality == "ok" and not gap: elapsed = (point["monotonic_ns"] - previous["monotonic_ns"]) / 1_000_000_000 _require(abs(elapsed - point["interval_seconds"]) <= max(.01, elapsed * .005), "interval and monotonic clock differ") computed = [(point["rx_bytes"] - previous["rx_bytes"]) / elapsed, (point["tx_bytes"] - previous["tx_bytes"]) / elapsed] for actual, claimed in zip(computed, [point["rx_bytes_per_second"], point["tx_bytes_per_second"]]): _require(math.isfinite(actual) and 0 <= actual <= MAX_RATE and abs(actual - claimed) <= max(2, actual * .005), "rate and counter delta differ") rx_rate, tx_rate = [round(value) for value in computed] elif quality == "ok": quality = "gap" else: # A sampler's bounded queue may have dropped a new epoch's baseline # while disconnected. Its first surviving observation is useful only # as a new baseline; never trust a rate that cannot be checked here. if quality == "ok": quality = "gap" gap = True return rx_rate, tx_rate, quality, gap def ingest(node_id, points, now, path=None): database = _connect(path if path is not None else store_path()) accepted = duplicates = 0 try: database.execute("BEGIN IMMEDIATE") cutoff = microseconds(now - timedelta(seconds=HISTORY_SECONDS)) database.execute("DELETE FROM samples WHERE observed_us < ?", (cutoff,)) known = database.execute("SELECT 1 FROM samples WHERE node_id=? LIMIT 1", (node_id,)).fetchone() count = database.execute("SELECT COUNT(DISTINCT node_id) FROM samples").fetchone()[0] _require(known is not None or count < MAX_NODES, "sample store node limit reached") for point in points: old = database.execute("SELECT payload_sha256 FROM samples WHERE node_id=? AND counter_epoch=? AND sequence=?", (node_id, point["counter_epoch"], point["sequence"])).fetchone() if old is not None: _require(old["payload_sha256"] == point["payload_sha256"], "conflicting repeated sample") duplicates += 1 continue previous = database.execute("SELECT * FROM samples WHERE node_id=? ORDER BY observed_us DESC,id DESC LIMIT 1", (node_id,)).fetchone() if previous is not None: _require(point["observed_us"] >= previous["observed_us"], "late unordered sample") rx_rate, tx_rate, quality, gap = _derived(point, previous) database.execute("""INSERT INTO samples (node_id,counter_epoch,sequence,boot_id,interface,observed_us,monotonic_ns,interval_seconds,rx_bytes,tx_bytes,rx_rate,tx_rate,quality,gap_before,dropped_samples_before,payload_sha256,received_us) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (node_id, point["counter_epoch"], point["sequence"], point["boot_id"], point["interface"], point["observed_us"], point["monotonic_ns"], point["interval_seconds"], point["rx_bytes"], point["tx_bytes"], rx_rate, tx_rate, quality, int(gap), point["dropped_samples_before"], point["payload_sha256"], microseconds(now))) accepted += 1 database.execute("DELETE FROM samples WHERE node_id=? AND id NOT IN (SELECT id FROM samples WHERE node_id=? ORDER BY observed_us DESC,id DESC LIMIT ?)", (node_id, node_id, MAX_POINTS)) database.commit() return {"status": "accepted", "accepted": accepted, "duplicates": duplicates} except BaseException: database.rollback() raise finally: database.close() def _history_point(row): return {"sampled_at": iso_from_us(row["observed_us"]), "interval_seconds": row["interval_seconds"], "sequence": row["sequence"], "upload_bytes_per_second": row["tx_rate"], "download_bytes_per_second": row["rx_rate"], "counter_epoch": row["counter_epoch"], "interface": row["interface"], "quality": row["quality"], "gap_before": bool(row["gap_before"]), "dropped_samples_before": row["dropped_samples_before"]} def snapshot(nodes, now, since=None, path=None): _require(len(nodes) <= MAX_NODES, "node response limit reached") cutoff = now - timedelta(seconds=HISTORY_SECONDS) incremental = since is not None since = max(cutoff, since) if incremental else now - timedelta(seconds=DEFAULT_HISTORY_SECONDS) _require(since <= now + timedelta(seconds=5), "history lower bound is in the future") point_limit = min(DEFAULT_HISTORY_SECONDS, MAX_RESPONSE_POINTS // max(1, len(nodes))) database = _connect(path if path is not None else store_path(), readonly=True) try: database.execute("BEGIN") output = [] for node in nodes: node_id = node["id"] latest = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? ORDER BY observed_us DESC,id DESC LIMIT 1", (node_id, microseconds(cutoff), microseconds(now))).fetchone() # Include newly received backfill even when its observed time predates # the previous response's generated_at cursor. Polling never loses # true one-second points from a late five-second batch. if incremental: rows = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? AND (observed_us>=? OR received_us>=?) ORDER BY observed_us DESC,id DESC LIMIT ?", (node_id, microseconds(cutoff), microseconds(now), microseconds(since), microseconds(since), point_limit + 1)).fetchall() else: rows = database.execute("SELECT * FROM samples WHERE node_id=? AND observed_us>=? AND observed_us<=? ORDER BY observed_us DESC,id DESC LIMIT ?", (node_id, microseconds(since), microseconds(now), point_limit + 1)).fetchall() truncated = len(rows) > point_limit rows = rows[:point_limit] rows.reverse() if not incremental and rows: truncated = truncated or database.execute("SELECT 1 FROM samples WHERE node_id=? AND observed_us>=? AND observed_us