Files
devplacepy/devplacepy/services/nodes/frames.py
T
retoorandClaude Sonnet 5.5 42b81271b8 Add community node socket: devices, tickets, consent gate, kill switch
Phase 3 of plan.md. Device registration with one-time secrets, scoped single-use
socket tickets, the lock-owner WS /nodes/ws with handshake and heartbeat eviction,
a single batch ConsentGate, and NodesService which disconnects nodes within one tick
when consent, device or the nodes_enabled kill switch changes. A reconcile of 2000
sessions measured about 110 ms after replacing per-session queries with batches.
Devii may withdraw but never grant bandwidth_sharing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 09:14:53 +02:00

91 lines
2.8 KiB
Python

# retoor <retoor@molodetz.nl>
from __future__ import annotations
import json
from typing import Any
from devplacepy.services.nodes.spec import (
CLIENT_TO_SERVER,
CLOSE_FRAME_TOO_LARGE,
CLOSE_PROTOCOL,
SPEC,
)
FIELD_TYPES: dict[str, type] = {
"str": str,
"int": int,
"bool": bool,
"object": dict,
"list": list,
}
class FrameError(ValueError):
def __init__(self, code: str, reason: str, close_code: int = CLOSE_PROTOCOL):
super().__init__(reason)
self.code = code
self.reason = reason
self.close_code = close_code
def ceiling(direction: str) -> int:
return max(item.max_bytes for item in SPEC.frames if item.direction == direction)
def _matches(value: Any, type_name: str) -> bool:
expected = FIELD_TYPES[type_name]
if expected is int:
return isinstance(value, int) and not isinstance(value, bool)
return isinstance(value, expected)
def validate(frame: dict, direction: str) -> dict:
kind = frame.get("type")
spec = SPEC.frame(kind, direction) if isinstance(kind, str) else None
if spec is None:
raise FrameError("unknown_frame", f"unknown frame type {kind!r}")
unexpected = set(frame) - spec.allowed()
if unexpected:
raise FrameError("unexpected_field", f"unexpected field {sorted(unexpected)[0]}")
for item in spec.fields:
if item.name not in frame:
if item.required:
raise FrameError("missing_field", f"missing field {item.name}")
continue
if not _matches(frame[item.name], item.type):
raise FrameError("bad_field_type", f"field {item.name} must be {item.type}")
return frame
def decode(raw: str | bytes, direction: str = CLIENT_TO_SERVER) -> dict:
size = len(raw.encode()) if isinstance(raw, str) else len(raw)
if size > ceiling(direction):
raise FrameError(
"frame_too_large", "frame exceeds the size cap", CLOSE_FRAME_TOO_LARGE
)
try:
frame = json.loads(raw)
except ValueError:
raise FrameError("bad_json", "frame is not valid JSON")
if not isinstance(frame, dict):
raise FrameError("bad_json", "frame must be a JSON object")
validate(frame, direction)
limit = SPEC.frame(frame["type"], direction).max_bytes
if size > limit:
raise FrameError(
"frame_too_large", "frame exceeds its size cap", CLOSE_FRAME_TOO_LARGE
)
return frame
def encode(frame_type: str, direction: str, **fields: Any) -> str:
frame = {"type": frame_type, **fields}
validate(frame, direction)
text = json.dumps(frame, separators=(",", ":"))
if len(text.encode()) > SPEC.frame(frame_type, direction).max_bytes:
raise FrameError(
"frame_too_large", "frame exceeds its size cap", CLOSE_FRAME_TOO_LARGE
)
return text