"""Values crossing a kernel connection; process and reference ownership stay with callers.""" from __future__ import annotations import base64 import dataclasses import importlib import math from typing import cast import albedo_api class InvalidValue(ValueError): """A peer supplied an invalid encoded value.""" class Unencodable(Exception): """The value cannot cross the connection; it stays a live remote reference.""" def encode(value: object, depth: int = 0) -> object: """One value as connection-crossable JSON; Unencodable means a live reference. Dataclasses and list subclasses carry their class so the owner rebuilds the real object and remote results read exactly like local ones. """ if depth > 32: raise Unencodable if isinstance(value, albedo_api.OutputPage): return { "__class__": "albedo_api.OutputPage", "fields": {"text": str(value), "next_offset": value.next_offset}, } if isinstance(value, float) and not math.isfinite(value): # JSON has no NaN or infinity that every reader takes. return {"__float__": repr(value)} if isinstance(value, str) and not _utf8(value): # A lone surrogate, as a path decoded with surrogateescape holds. return { "__str__": base64.b64encode(value.encode("utf-8", "surrogatepass")).decode( "ascii" ) } if value is None or isinstance(value, (bool, int, float, str)): return value if isinstance(value, (bytes, bytearray, memoryview)): return {"__bytes__": base64.b64encode(bytes(value)).decode("ascii")} if isinstance(value, dict) and type(value) is dict: if all(isinstance(key, str) and _utf8(key) for key in value) and ( frozenset(value) not in _MARKERS ): return {key: encode(item, depth + 1) for key, item in value.items()} # Keys a JSON object cannot hold as they are, or a key set the decoder # reads as a marker: the pairs, each key encoded as a value. return { "__dict__": [ [encode(key, depth + 1), encode(item, depth + 1)] for key, item in value.items() ] } if isinstance(value, albedo_api.Record): cls = type(value) return { "__record__": cls.__module__ + "." + cls.__qualname__, "fields": { str(key): encode(item, depth + 1) for key, item in value.items() }, } if isinstance(value, (list, tuple)): if type(value) is list: return [encode(item, depth + 1) for item in value] cls = type(value) try: return { "__list__": cls.__module__ + "." + cls.__qualname__, "items": [encode(item, depth + 1) for item in value], } except (TypeError, ValueError): raise Unencodable from None if dataclasses.is_dataclass(value) and not isinstance(value, type): cls = type(value) try: return { "__class__": cls.__module__ + "." + cls.__qualname__, "fields": { field.name: encode(getattr(value, field.name), depth + 1) for field in dataclasses.fields(value) }, } except (TypeError, ValueError, AttributeError): raise Unencodable from None raise Unencodable # The key sets `decode` reads as something other than a plain dict. _MARKERS = { frozenset(keys) for keys in ( ["__bytes__"], ["__float__"], ["__str__"], ["__dict__"], ["__class__", "fields"], ["__record__", "fields"], ["__list__", "items"], ) } def _utf8(text: str) -> bool: try: text.encode("utf-8") except UnicodeEncodeError: return False return True def _load_class(marker: str) -> type[object]: """The class a wire marker names; both bundles are identical, so it exists.""" parts = marker.split(".") for end in range(len(parts) - 1, 0, -1): module = ".".join(parts[:end]) try: obj: object = importlib.import_module(module) except ModuleNotFoundError as error: missing = error.name if missing is None or not ( module == missing or module.startswith(missing + ".") ): raise else: for part in parts[end:]: obj = getattr(obj, part) break else: raise ModuleNotFoundError(marker) # Markers are expected to name classes. Preserve the constructor lookup # for existing peers, with the branch-specific fallback on call failure. return cast(type[object], obj) def decode(value: object, depth: int = 0) -> object: """Rebuild real objects from wire values, so remote results read like local ones. Nesting deeper than `encode` allows raises `InvalidValue` instead of exhausting the stack on what a peer sends. """ if depth > 32: raise InvalidValue("remote value nests too deeply") if isinstance(value, dict): if set(value) == {"__bytes__"} and isinstance(value.get("__bytes__"), str): try: return base64.b64decode(value["__bytes__"], validate=True) except ValueError as error: raise InvalidValue("invalid remote byte encoding") from error if set(value) == {"__float__"} and value.get("__float__") in ( "nan", "inf", "-inf", ): return float(value["__float__"]) if set(value) == {"__str__"} and isinstance(value.get("__str__"), str): try: return base64.b64decode(value["__str__"], validate=True).decode( "utf-8", "surrogatepass" ) except ValueError as error: raise InvalidValue("invalid remote text encoding") from error if set(value) == {"__dict__"} and isinstance(value.get("__dict__"), list): pairs = [ (decode(pair[0], depth + 1), decode(pair[1], depth + 1)) for pair in value["__dict__"] if isinstance(pair, list) and len(pair) == 2 ] if len(pairs) != len(value["__dict__"]): raise InvalidValue("invalid remote dict encoding") try: return dict(pairs) except TypeError as error: raise InvalidValue("unhashable remote dict key") from error if set(value) == {"__class__", "fields"} and isinstance( value.get("__class__"), str ): try: return _load_class(value["__class__"])( **{ key: decode(item, depth + 1) for key, item in value["fields"].items() } ) except Exception: return { key: decode(item, depth + 1) for key, item in value["fields"].items() } if set(value) == {"__record__", "fields"} and isinstance( value.get("__record__"), str ): fields = { key: decode(item, depth + 1) for key, item in value["fields"].items() } try: return _load_class(value["__record__"])(fields) except Exception: return fields if set(value) == {"__list__", "items"} and isinstance( value.get("__list__"), str ): items = [decode(item, depth + 1) for item in value["items"]] try: return _load_class(value["__list__"])(items) except Exception: return items return {key: decode(item, depth + 1) for key, item in value.items()} if isinstance(value, list): return [decode(item, depth + 1) for item in value] return value