Source code for fleetmesh_node.compartment.handler

"""HANDLERS: what a compartment can receive from the wire, declared where it is.

A wire compartment declares its message dispatch table as a tuple of typed
Handler entries on the class attribute HANDLERS. Like COMMANDS, WORKERS, and
CHANNELS, it is declared once, validated at class definition time by the base
Compartment, and dispatched uniformly by the base `handle(inbound)`.
"""
from __future__ import annotations

import dataclasses
import inspect
from typing import Any, Callable, Optional, Sequence

from .problem import (
    InvalidIdentifierProblem,
    Problem,
    Problems,
    ReferenceProblem,
    TypeMismatchProblem,
)


[docs]@dataclasses.dataclass(frozen=True) class Handler: """One inbound wire protocol message handler.""" kind: str run: str schema: Optional[Any] = None doc: str = '' exact: bool = False reads: tuple[str, ...] = () writes: tuple[str, ...] = ()
[docs] def __init__( self, kind: str, run: str | Callable[..., Any], *, schema: Optional[Any] = None, doc: str = '', exact: bool = False, reads: Sequence[str] = (), writes: Sequence[str] = (), ) -> None: object.__setattr__(self, 'kind', str(kind)) run_name = run if isinstance(run, str) else getattr(run, '__name__', str(run)) object.__setattr__(self, 'run', run_name) object.__setattr__(self, 'schema', schema) object.__setattr__(self, 'doc', str(doc)) is_exact = exact or (kind.startswith(('http://', 'https://')) and not exact) object.__setattr__(self, 'exact', bool(is_exact)) object.__setattr__(self, 'reads', tuple(reads)) object.__setattr__(self, 'writes', tuple(writes))
[docs] def matches(self, msg_type: str, piuris: Sequence[str] = ()) -> bool: """Check if this handler matches the given message type URI.""" if not msg_type: return False if self.kind == '*': if not piuris: return True return any(msg_type.startswith(p + '/') for p in piuris) if self.exact or self.kind.startswith(('http://', 'https://')): return msg_type == self.kind # Suffix / sub-path matching: https://fleetmesh.org/compute/1.0/quote if msg_type.endswith('/' + self.kind): if not piuris: return True prefix = msg_type.rsplit('/', 1)[0] return any(prefix == p or prefix.startswith(p) for p in piuris) return False
[docs] def problems(self, cls: type) -> list[str]: """Validate this Handler against the declaring compartment class.""" out = Problems() if not self.kind or not isinstance(self.kind, str): out.append(InvalidIdentifierProblem('HANDLERS', str(self.kind), 'Handler must specify a message kind')) if not self.run or not isinstance(self.run, str): out.append(Problem( f'Handler {self.kind} must specify a target run method', surface='HANDLERS', code='missing_run', target=self.kind, )) else: fn = getattr(cls, self.run, None) if fn is None: out.append(ReferenceProblem( 'HANDLERS', f'{cls.__name__}.{self.run}', self.run, f"handler {self.kind!r}: method {self.run!r} does not exist on {cls.__name__}" )) elif not callable(fn): out.append(TypeMismatchProblem( 'HANDLERS', 'callable', type(fn).__name__, f"handler {self.kind!r}: attribute {self.run!r} on {cls.__name__} is not callable" )) return out
[docs] def execute(self, instance: Any, inbound: Any, *args: Any, **kw: Any) -> Any: """Dispatch an inbound message to this handler on the compartment instance.""" fn = getattr(instance, self.run) sig = inspect.signature(fn) num_params = len(sig.parameters) msg = getattr(inbound, 'message', inbound) sender = getattr(inbound, 'sender', msg.get('from', '') if isinstance(msg, dict) else '') # Validate against schema if declared if self.schema is not None and isinstance(msg, dict): body = msg.get('body') if callable(self.schema): try: self.schema(body) except Exception as e: return ('refused', sender, f'invalid schema: {e}') available = (inbound, sender) + args if num_params == 0: return fn() elif num_params == 1: return fn(inbound) elif num_params == 2: return fn(inbound, sender) elif num_params <= len(available): return fn(*available[:num_params], **kw) else: return fn(inbound, sender)
__all__ = ['Handler']