"""WireProtocol: base class for compartments that speak a wire protocol.
A compartment that speaks one or more PIURIs declares what it handles
(HANDLERS) and what it emits (OUTBOUND).
The base class verifies the declarations at class definition time and
binds a WireClient (`self.wire`) to manage outbound sends, requests, replies,
and correlation.
"""
from __future__ import annotations
from typing import Any, Callable, Mapping, Optional
from fleetmesh_core.wire import schema_files
from .base import Compartment
from .handler import Handler
from .problem import Problem, Problems, TypeMismatchProblem
[docs]class Outbound:
"""An outbound message kind declared by a WireProtocol.
States what message kind this compartment emits over the wire, what
reply kinds it expects in return (if an RPC request), and what documentation
explains its role.
"""
[docs] def __init__(
self,
kind: str,
reply: Optional[str | tuple[str, ...]] = None,
reads: tuple[str, ...] = (),
writes: tuple[str, ...] = (),
doc: str = '',
) -> None:
self.kind: str = str(kind)
if isinstance(reply, str):
self.reply: tuple[str, ...] = (reply,)
elif reply is None:
self.reply = ()
else:
self.reply = tuple(reply)
self.reads: tuple[str, ...] = tuple(reads)
self.writes: tuple[str, ...] = tuple(writes)
self.doc: str = str(doc)
def __repr__(self) -> str:
rep = f", reply={self.reply!r}" if self.reply else ""
return f"Outbound({self.kind!r}{rep})"
[docs]class WireClient:
"""The client adapter bound to self.wire on a WireProtocol compartment."""
[docs] def __init__(self, protocol: WireProtocol) -> None:
self._protocol: WireProtocol = protocol
@property
def transport(self) -> Any:
return getattr(self._protocol, 'transport', None)
[docs] def kind_of(self, message: Mapping[str, Any]) -> Optional[str]:
"""Extract the message kind relative to this protocol's declared PIURIs."""
t = str(message.get('type', ''))
for piuri in self._protocol.piuris:
if t.startswith(piuri + '/'):
return t[len(piuri) + 1:]
return None
[docs] def send(
self,
to_pubkey: str,
message: Mapping[str, Any],
*,
anonymous: bool = False,
stored: bool = False,
) -> Any:
"""Dispatch one message to to_pubkey over the transport ladder."""
tr = self.transport
if tr is None:
raise RuntimeError(f"{self._protocol.name}: no transport to send {message.get('type')}")
try:
return tr.send(message, to_pubkey, anonymous=anonymous, stored=stored)
except TypeError:
try:
return tr.send(message, to_pubkey, stored=stored)
except TypeError:
return tr.send(message, to_pubkey)
[docs] def request(
self,
to_pubkey: str,
message: Mapping[str, Any],
*,
timeout: float = 30.0,
anonymous: bool = False,
) -> Optional[Any]:
"""Dispatch a request message and await a correlated reply."""
tr = self.transport
if tr is None:
raise RuntimeError(f"{self._protocol.name}: no transport to request {message.get('type')}")
try:
return tr.request(message, to_pubkey, timeout=timeout, anonymous=anonymous)
except TypeError:
try:
return tr.request(message, to_pubkey, timeout=timeout)
except TypeError:
return tr.request(message, to_pubkey)
[docs] def reply(
self,
inbound: Any,
message: Any,
*,
sender: Optional[str] = None,
anonymous: bool = False,
) -> Any:
"""Reply in-band to an inbound message, carrying forward its thread id."""
m = getattr(inbound, 'message', inbound)
to_peer = sender or getattr(inbound, 'sender', None)
if to_peer is None and isinstance(m, dict):
to_peer = m.get('from')
if to_peer is None:
raise ValueError(f"{self._protocol.name}: cannot reply to inbound without sender")
thid = m.get('thid') or m.get('id') if isinstance(m, dict) else None
if thid:
message['thid'] = thid
return self.send(str(to_peer), message, anonymous=anonymous)
[docs]class WireProtocol(Compartment, abstract=True):
"""A compartment that speaks one or more DIDComm wire protocols (PIURIs)."""
piuris: tuple[str, ...] = ()
HANDLERS: tuple[Handler, ...] = ()
OUTBOUND: tuple[Outbound, ...] = ()
[docs] @classmethod
def declaration_problems(cls) -> list[str]:
out = Problems(super().declaration_problems())
if cls.abstract:
return out
# 1. piuris validation
piuris = getattr(cls, 'piuris', ())
if not piuris:
out.append(Problem(
f"{cls.__name__} must declare non-empty piuris",
surface='PIURIS',
code='missing_piuris',
target='piuris',
))
else:
for p in piuris:
if not isinstance(p, str) or not p.startswith('https://'):
out.append(Problem(
f"piuri {p!r} must be an https:// URI",
surface='PIURIS',
code='invalid_piuri',
target='piuris',
))
# 2. HANDLERS validation
handlers = getattr(cls, 'HANDLERS', ())
if not handlers:
out.append(Problem(
f"{cls.__name__} must declare HANDLERS",
surface='HANDLERS',
code='missing_handlers',
target='HANDLERS',
))
else:
for h in handlers:
if not isinstance(h, Handler):
out.append(TypeMismatchProblem('HANDLERS', 'Handler', type(h).__name__))
# 3. OUTBOUND validation
outbound = getattr(cls, 'OUTBOUND', ())
for ob in outbound:
if not isinstance(ob, Outbound):
out.append(TypeMismatchProblem('OUTBOUND', 'Outbound', type(ob).__name__))
# 4. Schema conformance check against schema/messages.json
try:
schema_protocols = schema_files.load_messages().get('protocols', {})
except Exception:
schema_protocols = {}
known_protocols = [p for p in piuris if p in schema_protocols]
if known_protocols:
allowed_msgs = set()
for p in known_protocols:
allowed_msgs.update(schema_protocols[p].get('messages', []))
for h in handlers:
if isinstance(h, Handler) and not getattr(h, 'exact', False) and h.kind != '*':
if h.kind not in allowed_msgs:
out.append(Problem(
f"handler {h.kind!r} is not declared in schema for {known_protocols}",
surface='HANDLERS',
code='schema_mismatch',
target=h.kind,
))
for ob in outbound:
if isinstance(ob, Outbound) and ob.kind not in allowed_msgs:
out.append(Problem(
f"outbound message {ob.kind!r} is not declared in schema for {known_protocols}",
surface='OUTBOUND',
code='schema_mismatch',
target=ob.kind,
))
return out
[docs] def __init__(
self,
node: Any = None,
clock: Optional[Callable[[], int]] = None,
cfg: Optional[Any] = None,
says: Optional[Any] = None,
db: Optional[Any] = None,
**kw: Any,
) -> None:
super().__init__(node=node, clock=clock, cfg=cfg, says=says, db=db, **kw)
self.wire_client: WireClient = WireClient(self)