Source code for fleetmesh_node.app.router

"""Declarative protocol message router for DIDComm PIURI dispatch.

Routes inbound envelopes to registered subsystem handlers based on their
PIURI (Protocol Identification URI) prefix or exact message type.
Standard library only.
"""
from __future__ import annotations

import collections
from typing import Any, Callable, Dict, List, Optional, Tuple

HandlerFunc = Callable[[Any], Optional[Tuple[Any, ...]]]


[docs]class ProtocolRouter: """DIDComm protocol router mapping message types to subsystem handlers."""
[docs] def __init__(self) -> None: self._exact_routes: Dict[str, HandlerFunc] = {} self._prefix_routes: Dict[str, HandlerFunc] = {} self._catchalls: List[HandlerFunc] = [] self._dispatch_counts: collections.Counter[str] = collections.Counter()
[docs] def register_exact(self, msg_type: str, handler: HandlerFunc) -> None: """Register a handler for an exact DIDComm message type.""" self._exact_routes[msg_type] = handler
[docs] def register(self, prefix: str, handler: HandlerFunc) -> None: """Register a handler for a PIURI prefix (e.g. 'https://fleetmesh.org/sync/1.0').""" self._prefix_routes[prefix] = handler
[docs] def register_catchall(self, handler: HandlerFunc) -> None: """Register a fallback handler invoked when no prefix matches or handler yields None.""" self._catchalls.append(handler)
[docs] def unregister(self, prefix_or_type: str) -> None: """Remove a previously registered route.""" self._exact_routes.pop(prefix_or_type, None) self._prefix_routes.pop(prefix_or_type, None)
[docs] def route_for(self, msg_type: str) -> Optional[HandlerFunc]: """Find the most specific registered handler for a message type.""" if not msg_type: return None if msg_type in self._exact_routes: return self._exact_routes[msg_type] # Match longest prefix first for prefix in sorted(self._prefix_routes.keys(), key=len, reverse=True): if msg_type.startswith(prefix): return self._prefix_routes[prefix] return None
[docs] def dispatch(self, inbound: Any) -> Optional[Tuple[Any, ...]]: """Dispatch an inbound envelope to the matching handler. Returns the handler result (typically a status tuple), or None if unhandled. """ msg = getattr(inbound, 'message', inbound) msg_type = msg.get('type', '') if isinstance(msg, dict) else '' handler = self.route_for(msg_type) if handler is not None: res = handler(inbound) if res is not None: self._dispatch_counts[msg_type] += 1 return res for catchall in self._catchalls: res = catchall(inbound) if res is not None: self._dispatch_counts[msg_type or 'catchall'] += 1 return res return None
[docs] def registered_prefixes(self) -> List[str]: """Return all registered PIURI prefixes.""" return sorted(self._prefix_routes.keys())
@property def counts(self) -> collections.Counter[str]: """Dispatch count by message type.""" return self._dispatch_counts