2023-11-01 04:57:08 +00:00
|
|
|
"""MuxRPC"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
from typing import Any, AsyncIterator, Callable, Dict, Generator, List, Literal, Optional, Union
|
|
|
|
|
|
|
|
from typing_extensions import Self
|
|
|
|
|
|
|
|
from .packet_stream import PacketStream, PSMessage, PSMessageType, PSRequestHandler, PSStreamHandler
|
|
|
|
|
|
|
|
MuxRPCJSON = Dict[str, Any]
|
|
|
|
MuxRPCCallType = Literal["async", "duplex", "sink", "source", "sync"]
|
|
|
|
MuxRPCRequestHandlerType = Callable[[PacketStream, "MuxRPCRequest"], None]
|
|
|
|
MuxRPCRequestParam = Union[bytes, str, MuxRPCJSON] # pylint: disable=invalid-name
|
2017-07-30 08:14:26 +00:00
|
|
|
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
class MuxRPCAPIException(Exception):
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Exception to raise on MuxRPC API errors"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class MuxRPCHandler: # pylint: disable=too-few-public-methods
|
|
|
|
"""Base MuxRPC handler class"""
|
2017-07-30 12:08:18 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def check_message(self, msg: PSMessage) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Check message validity"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
body = msg.body
|
2023-11-01 04:04:43 +00:00
|
|
|
|
|
|
|
if isinstance(body, dict) and "name" in body and body["name"] == "Error":
|
|
|
|
raise MuxRPCAPIException(body["message"])
|
2017-07-30 12:08:18 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __await__(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def __aiter__(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
async def __anext__(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def send(self, msg: Any, msg_type: PSMessageType = PSMessageType.JSON, end: bool = False) -> None:
|
|
|
|
"""Send a message through the stream"""
|
|
|
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
class MuxRPCRequestHandler(MuxRPCHandler): # pylint: disable=abstract-method
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Base class for MuxRPC request handlers"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, ps_handler: PSRequestHandler):
|
2017-07-30 08:14:26 +00:00
|
|
|
self.ps_handler = ps_handler
|
|
|
|
|
|
|
|
def __await__(self):
|
2023-11-01 04:04:43 +00:00
|
|
|
msg = yield from self.ps_handler.__await__()
|
2017-07-30 12:08:18 +00:00
|
|
|
self.check_message(msg)
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
return msg
|
2017-07-30 08:14:26 +00:00
|
|
|
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
class MuxRPCSourceHandler(MuxRPCHandler): # pylint: disable=abstract-method
|
2023-11-01 04:57:08 +00:00
|
|
|
"""MuxRPC handler for sources"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, ps_handler: PSStreamHandler):
|
2017-07-30 08:14:26 +00:00
|
|
|
self.ps_handler = ps_handler
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __aiter__(self) -> AsyncIterator[Optional[PSMessage]]:
|
2023-11-01 05:03:06 +00:00
|
|
|
return self
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def __anext__(self) -> Optional[PSMessage]:
|
2023-11-01 05:03:06 +00:00
|
|
|
msg = await self.ps_handler.__anext__()
|
2023-11-01 06:22:29 +00:00
|
|
|
|
|
|
|
assert msg
|
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
self.check_message(msg)
|
|
|
|
|
|
|
|
return msg
|
2017-07-30 08:14:26 +00:00
|
|
|
|
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class MuxRPCSinkHandlerMixin: # pylint: disable=too-few-public-methods
|
|
|
|
"""Mixin for sink-type MuxRPC handlers"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
connection: PacketStream
|
|
|
|
req: int
|
|
|
|
|
|
|
|
def send(self, msg: Any, msg_type: PSMessageType = PSMessageType.JSON, end: bool = False) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Send a message through the stream"""
|
|
|
|
|
2017-07-30 08:52:04 +00:00
|
|
|
self.connection.send(msg, stream=True, msg_type=msg_type, req=self.req, end_err=end)
|
2017-07-30 08:14:26 +00:00
|
|
|
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
class MuxRPCDuplexHandler(MuxRPCSinkHandlerMixin, MuxRPCSourceHandler): # pylint: disable=abstract-method
|
2023-11-01 04:57:08 +00:00
|
|
|
"""MuxRPC handler for duplex streams"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, ps_handler: PSStreamHandler, connection: PacketStream, req: int):
|
2023-11-01 04:57:08 +00:00
|
|
|
super().__init__(ps_handler)
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
self.connection = connection
|
|
|
|
self.req = req
|
|
|
|
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
class MuxRPCSinkHandler(MuxRPCHandler, MuxRPCSinkHandlerMixin): # pylint: disable=abstract-method
|
2023-11-01 04:57:08 +00:00
|
|
|
"""MuxRPC handler for sinks"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, connection: PacketStream, req: int):
|
2017-07-30 08:14:26 +00:00
|
|
|
self.connection = connection
|
|
|
|
self.req = req
|
|
|
|
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def _get_appropriate_api_handler(
|
|
|
|
type_: MuxRPCCallType, connection: PacketStream, ps_handler: Union[PSRequestHandler, PSStreamHandler], req: int
|
|
|
|
) -> MuxRPCHandler:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Find the appropriate MuxRPC handler"""
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
if type_ in {"sync", "async"}:
|
2023-11-01 06:22:29 +00:00
|
|
|
assert isinstance(ps_handler, PSRequestHandler)
|
2017-07-30 08:14:26 +00:00
|
|
|
return MuxRPCRequestHandler(ps_handler)
|
2023-11-01 04:57:08 +00:00
|
|
|
|
|
|
|
if type_ == "source":
|
2023-11-01 06:22:29 +00:00
|
|
|
assert isinstance(ps_handler, PSStreamHandler)
|
2017-07-30 08:14:26 +00:00
|
|
|
return MuxRPCSourceHandler(ps_handler)
|
2023-11-01 04:57:08 +00:00
|
|
|
|
|
|
|
if type_ == "sink":
|
2017-07-30 08:14:26 +00:00
|
|
|
return MuxRPCSinkHandler(connection, req)
|
2023-11-01 04:57:08 +00:00
|
|
|
|
|
|
|
if type_ == "duplex":
|
2023-11-01 06:22:29 +00:00
|
|
|
assert isinstance(ps_handler, PSStreamHandler)
|
2017-07-30 08:14:26 +00:00
|
|
|
return MuxRPCDuplexHandler(ps_handler, connection, req)
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
raise TypeError(f"Unknown request type {type_}")
|
2023-11-01 04:57:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
class MuxRPCRequest:
|
|
|
|
"""MuxRPC request"""
|
2017-07-29 09:54:03 +00:00
|
|
|
|
|
|
|
@classmethod
|
2023-11-01 06:22:29 +00:00
|
|
|
def from_message(cls, message: PSMessage) -> Self:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Initialise a request from a raw packet stream message"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
body = message.body
|
2023-11-01 04:57:08 +00:00
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
return cls(".".join(body["name"]), body["args"])
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, name: str, args: List[MuxRPCRequestParam]):
|
2017-07-29 09:54:03 +00:00
|
|
|
self.name = name
|
|
|
|
self.args = args
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __repr__(self) -> str:
|
2023-11-01 04:57:08 +00:00
|
|
|
return f"<MuxRPCRequest {self.name} {self.args}>"
|
2017-07-29 09:54:03 +00:00
|
|
|
|
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class MuxRPCMessage:
|
|
|
|
"""MuxRPC message"""
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
@classmethod
|
2023-11-01 06:22:29 +00:00
|
|
|
def from_message(cls, message: PSMessage) -> Self:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Initialise a MuxRPC message from a raw packet stream message"""
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
return cls(message.body)
|
|
|
|
|
|
|
|
def __init__(self, body):
|
|
|
|
self.body = body
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __repr__(self) -> str:
|
2023-11-01 04:57:08 +00:00
|
|
|
return f"<MuxRPCMessage {self.body}>"
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class MuxRPCAPI:
|
|
|
|
"""Generit MuxRPC API"""
|
2017-07-30 08:14:26 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self) -> None:
|
|
|
|
self.handlers: Dict[str, MuxRPCRequestHandlerType] = {}
|
|
|
|
self.connection: Optional[PacketStream] = None
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __aiter__(self) -> AsyncIterator[None]:
|
2023-11-02 08:48:37 +00:00
|
|
|
return self
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def __anext__(self) -> None:
|
|
|
|
assert self.connection
|
|
|
|
|
2023-11-02 08:48:37 +00:00
|
|
|
req_message = await self.connection.__anext__()
|
2023-11-01 04:04:43 +00:00
|
|
|
|
2023-11-02 08:48:37 +00:00
|
|
|
if req_message is None:
|
|
|
|
raise StopAsyncIteration()
|
2023-11-02 05:15:17 +00:00
|
|
|
|
2023-11-02 08:48:37 +00:00
|
|
|
body = req_message.body
|
|
|
|
|
|
|
|
if isinstance(body, dict) and body.get("name"):
|
|
|
|
self.process(self.connection, MuxRPCRequest.from_message(req_message))
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __await__(self) -> Generator[None, None, None]:
|
2023-11-02 08:48:37 +00:00
|
|
|
yield from self.__anext__().__await__()
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def add_connection(self, connection: PacketStream) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Set the packet stream connection of this RPC API"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
self.connection = connection
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def define(self, name: str) -> Callable[[MuxRPCRequestHandlerType], MuxRPCRequestHandlerType]:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Decorator to define an RPC method handler"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def _handle(f: MuxRPCRequestHandlerType) -> MuxRPCRequestHandlerType:
|
2017-07-29 09:54:03 +00:00
|
|
|
self.handlers[name] = f
|
|
|
|
|
|
|
|
return f
|
2023-11-01 04:04:43 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
return _handle
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def process(self, connection: PacketStream, request: MuxRPCRequest) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Process an incoming request"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
handler = self.handlers.get(request.name)
|
2023-11-01 04:57:08 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
if not handler:
|
2023-11-01 04:57:08 +00:00
|
|
|
raise MuxRPCAPIException(f"Method {request.name} not found!")
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
handler(connection, request)
|
2017-07-30 08:14:26 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def call(self, name: str, args: List[MuxRPCRequestParam], type_: MuxRPCCallType = "sync") -> MuxRPCHandler:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Call an RPC method"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
assert self.connection
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
if not self.connection.is_connected:
|
2023-11-01 04:57:08 +00:00
|
|
|
raise Exception("not connected") # pylint: disable=broad-exception-raised
|
2023-11-01 04:04:43 +00:00
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
old_counter = self.connection.req_counter
|
2023-11-01 04:04:43 +00:00
|
|
|
ps_handler = self.connection.send(
|
|
|
|
{"name": name.split("."), "args": args, "type": type_},
|
|
|
|
stream=type_ in {"sink", "source", "duplex"},
|
|
|
|
)
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
return _get_appropriate_api_handler(type_, self.connection, ps_handler, old_counter)
|