1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 11:34:18 +00:00
This commit is contained in:
Steffo 2019-10-20 18:12:12 +02:00
parent 7a0986033b
commit 074ca063fe
6 changed files with 36 additions and 44 deletions

20
royalherald/broadcast.py Normal file
View file

@ -0,0 +1,20 @@
class Broadcast:
def __init__(self, handler: str, data: dict):
super().__init__()
self.handler: str = handler
self.data: dict = data
def to_dict(self):
return self.__dict__
@classmethod
def from_dict(cls, d: dict):
return cls(**d)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.handler == other.handler and self.data == other.data
return False
def __repr__(self):
return f"{self.__class__.__qualname__}(handler={self.handler}, data={self.data})"

View file

@ -7,6 +7,7 @@ import typing
from .package import Package from .package import Package
from .request import Request from .request import Request
from .response import Response, ResponseSuccess, ResponseFailure from .response import Response, ResponseSuccess, ResponseFailure
from .broadcast import Broadcast
from .errors import ConnectionClosedError, InvalidServerResponseError from .errors import ConnectionClosedError, InvalidServerResponseError
@ -127,13 +128,21 @@ class Link:
await self.websocket.send(package.to_json_bytes()) await self.websocket.send(package.to_json_bytes())
log.debug(f"Sent package: {package}") log.debug(f"Sent package: {package}")
@requires_identification
async def broadcast(self, destination: str, broadcast: Broadcast) -> None:
package = Package(broadcast.to_dict(), source=self.nid, destination=destination)
await self.send(package)
log.debug(f"Sent broadcast: {broadcast}")
@requires_identification @requires_identification
async def request(self, destination: str, request: Request) -> Response: async def request(self, destination: str, request: Request) -> Response:
if destination.startswith("*"):
raise ValueError("requests cannot have multiple destinations")
package = Package(request.to_dict(), source=self.nid, destination=destination) package = Package(request.to_dict(), source=self.nid, destination=destination)
request = PendingRequest(loop=self._loop) request = PendingRequest(loop=self._loop)
self._pending_requests[package.source_conv_id] = request self._pending_requests[package.source_conv_id] = request
await self.send(package) await self.send(package)
log.debug(f"Sent to {destination}: {request}") log.debug(f"Sent request to {destination}: {request}")
await request.event.wait() await request.event.wait()
if request.data["type"] == "ResponseSuccess": if request.data["type"] == "ResponseSuccess":
response: Response = ResponseSuccess.from_dict(request.data) response: Response = ResponseSuccess.from_dict(request.data)

View file

@ -11,12 +11,12 @@ class Request:
def to_dict(self): def to_dict(self):
return self.__dict__ return self.__dict__
@staticmethod @classmethod
def from_dict(d: dict): def from_dict(cls, d: dict):
return Request(**d) return cls(**d)
def __eq__(self, other): def __eq__(self, other):
if isinstance(other, Request): if isinstance(other, self.__class__):
return self.handler == other.handler and self.data == other.data return self.handler == other.handler and self.data == other.data
return False return False

View file

@ -104,7 +104,7 @@ class Server:
if package.destination == "<none>": if package.destination == "<none>":
return [] return []
# Is it all possible destinations? # Is it all possible destinations?
if package.destination == "<all>": if package.destination == "*":
return self.identified_clients return self.identified_clients
# Is it a valid nid? # Is it a valid nid?
try: try:

View file

@ -5,7 +5,7 @@ with open("README.md", "r") as f:
setuptools.setup( setuptools.setup(
name="royalherald", name="royalherald",
version="5.0b8", version="5.0b9",
author="Stefano Pigozzi", author="Stefano Pigozzi",
author_email="ste.pigozzi@gmail.com", author_email="ste.pigozzi@gmail.com",
description="A websocket communication protocol", description="A websocket communication protocol",

View file

@ -1,24 +1,8 @@
import pytest import pytest
import uuid import uuid
import asyncio
import logging
import royalherald as h import royalherald as h
log = logging.root
stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
log.addHandler(stream_handler)
log.setLevel(logging.WARNING)
@pytest.fixture
def async_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
async def echo_request_handler(message): async def echo_request_handler(message):
return message return message
@ -37,24 +21,3 @@ def test_package_serialization():
def test_request_creation(): def test_request_creation():
request = h.Request("pytest", {"testing": "is fun", "bugs": "are less fun"}) request = h.Request("pytest", {"testing": "is fun", "bugs": "are less fun"})
assert request == h.Request.from_dict(request.to_dict()) assert request == h.Request.from_dict(request.to_dict())
# Broken!
#
# def test_links(async_loop: asyncio.AbstractEventLoop):
# address, port = "127.0.0.1", 1234
# master = h.Server(address, port, "test", loop=async_loop)
# async_loop.create_task(master.run())
# async_loop.run_until_complete(asyncio.sleep(5))
# # Test invalid secret
# wrong_secret_link = h.Link(f"ws://{address}:{port}", "invalid", "test", echo_request_handler, loop=async_loop)
# with pytest.raises(h.ConnectionClosedError):
# async_loop.run_until_complete(wrong_secret_link.run())
# # Test regular connection
# link1 = h.Link("ws://127.0.0.1:1235", "test", "one", echo_request_handler, loop=async_loop)
# async_loop.create_task(link1.run())
# link2 = h.Link("ws://127.0.0.1:1235", "test", "two", echo_request_handler, loop=async_loop)
# async_loop.create_task(link2.run())
# message = {"ciao": "ciao"}
# response = async_loop.run_until_complete(link1.request(message, "two"))
# assert message == response