2023-11-13 12:34:43 +00:00
|
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
#
|
|
|
|
# Copyright (c) 2017 PySSB contributors (see AUTHORS for more details)
|
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
|
|
# of this software and associated documentation files (the "Software"), to deal
|
|
|
|
# in the Software without restriction, including without limitation the rights
|
|
|
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
|
|
# copies of the Software, and to permit persons to whom the Software is
|
|
|
|
# furnished to do so, subject to the following conditions:
|
|
|
|
#
|
|
|
|
# The above copyright notice and this permission notice shall be included in all
|
|
|
|
# copies or substantial portions of the Software.
|
|
|
|
#
|
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
|
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
|
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
"""MuxRPC"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
from typing import Any, AsyncIterator, Callable, Dict, 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 05:03:06 +00:00
|
|
|
"""Exception to raise on MuxRPC API errors"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
|
2023-11-01 05:03:06 +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 05:03:06 +00:00
|
|
|
"""Check message validity"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
body = msg.body
|
2023-11-01 05:03:06 +00:00
|
|
|
|
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 __aiter__(self) -> AsyncIterator[Optional[PSMessage]]:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
async def __anext__(self) -> Optional[PSMessage]:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def send(self, msg: Any, msg_type: PSMessageType = PSMessageType.JSON, end: bool = False) -> None:
|
|
|
|
"""Send a message through the stream"""
|
|
|
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
async def get_response(self) -> PSMessage:
|
|
|
|
"""Get the response for an RPC request"""
|
|
|
|
|
|
|
|
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 05:03:06 +00:00
|
|
|
"""MuxRPC handler for incoming RPC requests"""
|
|
|
|
|
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
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def get_response(self) -> PSMessage:
|
2023-11-16 04:40:08 +00:00
|
|
|
"""Get the response data"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
msg = await self.ps_handler.__anext__()
|
2023-11-16 04:40:08 +00:00
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
self.check_message(msg)
|
2023-11-16 04:40:08 +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 05:03:06 +00:00
|
|
|
"""MuxRPC handler for source-type RPC requests"""
|
|
|
|
|
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 05:03:06 +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 05:03:06 +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 05:03:06 +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 05:03:06 +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 05:03:06 +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 05:03:06 +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 05:03:06 +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 05:03:06 +00:00
|
|
|
|
|
|
|
if type_ == "sink":
|
2017-07-30 08:14:26 +00:00
|
|
|
return MuxRPCSinkHandler(connection, req)
|
2023-11-01 05:03:06 +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 05:03:06 +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 05:03:06 +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 05:03:06 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
assert isinstance(body, dict)
|
|
|
|
|
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 05:03:06 +00:00
|
|
|
return f"<MuxRPCRequest {self.name} {self.args}>"
|
2017-07-29 09:54:03 +00:00
|
|
|
|
|
|
|
|
2023-11-01 05:03:06 +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 05:03:06 +00:00
|
|
|
"""Initialise a MuxRPC message from a raw packet stream message"""
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
return cls(message.body)
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, body: Union[bytes, str, Dict[str, Any]]):
|
2017-07-30 08:14:26 +00:00
|
|
|
self.body = body
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
return f"<MuxRPCMessage {self.body!r}>"
|
2017-07-30 08:14:26 +00:00
|
|
|
|
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
class MuxRPCAPI:
|
|
|
|
"""Generic MuxRPC API"""
|
|
|
|
|
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
|
|
|
async def process_messages(self) -> None:
|
2023-11-13 12:18:12 +00:00
|
|
|
"""Continuously process incoming messages"""
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
assert self.connection
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
async for req_message in self.connection:
|
|
|
|
if req_message is None:
|
|
|
|
return
|
2023-11-13 12:18:12 +00:00
|
|
|
|
2023-11-02 05:15:17 +00:00
|
|
|
body = req_message.body
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
if isinstance(body, dict) and body.get("name"):
|
2017-07-30 08:14:26 +00:00
|
|
|
self.process(self.connection, MuxRPCRequest.from_message(req_message))
|
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 05:03:06 +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 05:03:06 +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 05:03:06 +00:00
|
|
|
"""Process an incoming request"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
handler = self.handlers.get(request.name)
|
2023-11-01 05:03:06 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
if not handler:
|
2023-11-01 05:03:06 +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 05:03:06 +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 05:03:06 +00:00
|
|
|
raise Exception("not connected") # pylint: disable=broad-exception-raised
|
|
|
|
|
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"},
|
|
|
|
)
|
2023-11-01 05:03:06 +00:00
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
return _get_appropriate_api_handler(type_, self.connection, ps_handler, old_counter)
|