"""Bounded v2 mapping of existing raw-first LiveIngressEvent semantics. This IPC candidate carries binary payloads, not base64/PNG/archive uploads. It is not the selected/authenticated network transport. A trusted controller binds one acquisition session to StreamStart; hashes provide integrity, NOT authentication. No peer-supplied paths, commands, models or calibration loading. """ from __future__ import annotations import json import re import struct from collections.abc import Iterator from hashlib import sha256 from typing import Any, Final from k1link.compute.live_perception import LiveIngressEvent from .realtime_contract import StreamStart SCHEMA: Final = "missioncore.live-perception-wire/v2" MAGIC: Final = b"MCI2" PREFIX: Final = struct.Struct("!4sBI") OPEN, FRAGMENT, END, CANCEL, GAP = range(1, 6) MAX_HEADER: Final = 64 * 1024 MAX_FRAGMENT: Final = 1024 * 1024 PAYLOAD_LIMITS: Final = { "camera-init": MAX_FRAGMENT, "camera-frame": MAX_FRAGMENT, "lidar": 2 * MAX_FRAGMENT, "pose": 2 * MAX_FRAGMENT, } EVENT_FIELDS: Final = frozenset( ( "ingress_sequence", "session_id", "session_generation", "modality", "source_id", "source_sequence", "captured_at_epoch_ns", "received_monotonic_ns", ) ) INTEGER_FIELDS: Final = EVENT_FIELDS - {"session_id", "modality", "source_id"} _DECIMAL: Final = re.compile(r"^(0|[1-9][0-9]{0,19})$") _DIGEST: Final = re.compile(r"^[a-f0-9]{64}$") class StreamWireError(ValueError): """Malformed, stale, oversized or incomplete transport input.""" def uint64(value: object) -> int: if not isinstance(value, str) or not _DECIMAL.fullmatch(value): raise StreamWireError("wire uint64 must be a canonical decimal string") result = int(value) if result > (1 << 64) - 1: raise StreamWireError("wire uint64 overflow") return result def decimal(value: object) -> str: if type(value) is not int or not 0 <= value < 1 << 64: raise StreamWireError("invalid uint64") return str(value) def identifier(value: object) -> str: if not isinstance(value, str) or not 1 <= len(value) <= 160: raise StreamWireError("invalid bounded source identity") if not value.isascii() or any(ord(c) < 33 or ord(c) > 126 for c in value): raise StreamWireError("invalid bounded source identity") return value def digest(value: object) -> str: if not isinstance(value, str) or not _DIGEST.fullmatch(value): raise StreamWireError("invalid payload digest") return value def canonical(value: dict[str, Any]) -> bytes: return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() def start_document(start: StreamStart) -> dict[str, Any]: result = start.to_dict() result["lease_generation"] = decimal(start.lease_generation) return result def binding(start: StreamStart) -> str: return sha256(canonical(start_document(start))).hexdigest() def _unique_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in pairs: if key in result: raise StreamWireError("duplicate metadata field") result[key] = value return result def parse_header(raw: bytearray) -> dict[str, Any]: def reject_constant(value: str) -> Any: raise StreamWireError("non-finite JSON metadata") try: value = json.loads(raw, object_pairs_hook=_unique_pairs, parse_constant=reject_constant) except (ValueError, UnicodeError, RecursionError) as exc: raise StreamWireError("invalid bounded metadata") from exc if not isinstance(value, dict): raise StreamWireError("metadata must be an object") return value def packet(kind: int, header: dict[str, Any]) -> bytes: raw = canonical(header) if kind not in (OPEN, FRAGMENT, END, CANCEL, GAP) or not 0 < len(raw) <= MAX_HEADER: raise StreamWireError("invalid frame header") return PREFIX.pack(MAGIC, kind, len(raw)) + raw def open_packet(start: StreamStart, session_id: str, session_generation: int) -> bytes: return packet( OPEN, { "schema_version": SCHEMA, "start": start_document(start), "session_id": identifier(session_id), "session_generation": decimal(session_generation), }, ) def event_metadata(event: LiveIngressEvent) -> dict[str, Any]: result = {name: getattr(event, name) for name in EVENT_FIELDS} for name in INTEGER_FIELDS: result[name] = decimal(result[name]) validate_event_metadata(result) return result def validate_event_metadata(value: object) -> dict[str, Any]: if not isinstance(value, dict) or set(value) != EVENT_FIELDS: raise StreamWireError("event fields changed") result = dict(value) for name in INTEGER_FIELDS: result[name] = uint64(value[name]) for name in ("session_id", "source_id"): identifier(value[name]) if ( not isinstance(value["modality"], str) or value["modality"] not in PAYLOAD_LIMITS or result["ingress_sequence"] < 1 or result["session_generation"] < 1 ): raise StreamWireError("invalid raw modality or generation") return result def event_packets( start: StreamStart, event: LiveIngressEvent, ) -> Iterator[tuple[bytes, memoryview]]: """Iterate one already committed raw event; never assemble a route/archive. Source adapter owns the original event bytes. Returned views borrow them; sender must finish each fragment before advancing this iterator. """ metadata = event_metadata(event) total = len(event.payload) if not 0 < total <= PAYLOAD_LIMITS[event.modality]: raise StreamWireError("raw event exceeds modality bound") whole_hash = sha256(event.payload).hexdigest() view = memoryview(event.payload) for offset in range(0, total, MAX_FRAGMENT): chunk = view[offset : offset + MAX_FRAGMENT] yield ( packet( FRAGMENT, { "binding": binding(start), "event": metadata, "total_bytes": total, "offset": offset, "fragment_bytes": len(chunk), "payload_sha256": whole_hash, "fragment_sha256": sha256(chunk).hexdigest(), }, ), chunk, ) def terminal_packet(start: StreamStart, *, cancel: bool = False) -> bytes: return packet(CANCEL if cancel else END, {"binding": binding(start)}) def gap_packet(start: StreamStart, *, modality: str, reason: str, count: int) -> bytes: if modality not in PAYLOAD_LIMITS or reason not in ("unavailable", "source-gap", "overload"): raise StreamWireError("invalid gap notice") return packet( GAP, { "binding": binding(start), "modality": modality, "reason": reason, "count": decimal(count), }, )