Skip to content

Commit

Permalink
Merge pull request #8 from NathanDraco22/version-0-1-7
Browse files Browse the repository at this point in the history
Version 0-2-0
  • Loading branch information
NathanDraco22 authored Dec 10, 2023
2 parents b4344d9 + be5cb1f commit a8f6bea
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 30 deletions.
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ register: EventRegister = EventRegister()
@register.on_event("hello")
async def hello_trigger(context: Context):
conn = context.connection
conn.send("hello", "HELLO FROM SERVER !!!")
await conn.send("hello", "HELLO FROM SERVER !!!")


@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
await FastApiConnector.plug_and_start(register,ws)
connector = FastApiConnector(reg, ws)
await connector.start()

```

Expand All @@ -62,7 +63,7 @@ This will creates an event named `"hello"` and it will call `hello_trigger` func
@register.on_event("hello")
async def hello_trigger(context: Context):
conn = context.connection
conn.send("hello", "HELLO FROM SERVER !!!")
await conn.send("hello", "HELLO FROM SERVER !!!")
```
> Event it is a class with name("hello") and the callback(hello_trigger)
Expand All @@ -87,11 +88,12 @@ register: EventRegister = EventRegister()
@register.on_event("hello")
async def hello_trigger(context: Context):
conn = context.connection
conn.send("hello", "HELLO FROM SERVER !!!")
await conn.send("hello", "HELLO FROM SERVER !!!")

@app.websocket("/")
async def websocket(request: Request, ws: Websocket):
await SanicConnector.plug_and_start(register, ws)
connector = SanicConnector(reg, ws)
await connector.start()

```
### Context object
Expand All @@ -115,10 +117,11 @@ async def hello_trigger(context: Context):
```python
WebSocketConnection.id # ID of connection

WebSocketConnection.send(event:str, payload:Any) #Send Event to the client
await WebSocketConnection.send(event:str, payload:Any) #Send Event to the client

WebSocketConnection.close() # Close the websocket connection
await WebSocketConnection.close() # Close the websocket connection
```
> Coroutines need to be awaited.
### Events

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ name = "zaptools"
description = "A toolkit for Event-Driven websocket management"
readme = "README.md"
authors = [{name = "Nathan Mejia", email = "[email protected]"}]
version = "0.1.6"
version = "0.2.0"
requires-python = ">=3.10"
classifiers = [
'Development Status :: 4 - Beta',
Expand Down
34 changes: 18 additions & 16 deletions tests/e2e_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,41 @@
from zaptools.connectors import FastApiConnector

app:FastAPI = FastAPI()
register: EventRegister = EventRegister()
reg: EventRegister = EventRegister()

@register.on_event("connected")
@reg.on_event("connected")
async def connected_trigger(ctx: EventContext):
ctx.connection.send("connected", "LIVE", {"myHeader": "I'm a header"})
await ctx.connection.send("connected", "LIVE", {"myHeader": "I'm a header"})

@register.on_event("disconnected")
@reg.on_event("disconnected")
async def disconnected_trigger(ctx:EventContext):
print(f"connection left -> {ctx.connection.id}")

@register.on_event("header")
@reg.on_event("header")
async def headers( ctx:EventContext):
test_header = ctx.headers["clientHeader"]
ctx.connection.send("headerTest", "headerTest", {"isOk" : test_header=="client"})
await ctx.connection.send(
"headerTest", "headerTest", {"isOk" : test_header=="client"}
)

@register.on_event("event1")
@reg.on_event("event1")
async def event1_triger(ctx: EventContext):
ctx.connection.send("event1_completed", "HELLO FROM SERVER")
await ctx.connection.send("event1_completed", "HELLO FROM SERVER")

@register.on_event("event2")
@reg.on_event("event2")
async def event2_triger(ctx: EventContext):
ctx.connection.send("event2_completed", "HELLO FROM SERVER 2")
await ctx.connection.send("event2_completed", "HELLO FROM SERVER 2")

@register.on_event("exit")
@reg.on_event("exit")
async def exit_event( ctx: EventContext ):
ctx.connection.close()
await ctx.connection.close()

@register.on_event("hb")
@reg.on_event("hb")
async def hello_and_bye(ctx:EventContext):
conn = ctx.connection
conn.send("h", "h event")
conn.close()
await conn.send("h", "h event")
await conn.close()

@app.websocket("/")
async def websocket_endpoint(ws: WebSocket):
await FastApiConnector.plug_and_start(register,ws)
await FastApiConnector.plug_and_start(reg,ws)
3 changes: 3 additions & 0 deletions zaptools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .meta_tag import MetaTag
from .tools import EventContext, EventRegister
from .room import Room
29 changes: 29 additions & 0 deletions zaptools/connectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,21 @@

class FastApiConnector:

def __init__(self, register: EventRegister, webscoket: Any):
self.register = register
self.websocket = webscoket

async def start(self):
fastapi_adapter = FastApiAdapter(self.websocket)
event_caller = EventCaller(self.register._event_book)
id_controller = IDController()
await fastapi_adapter.start_connection()
current_id = id_controller.eval()
ws_connection = WebSocketConnection(current_id, fastapi_adapter)
event_processor = EventProcessor(ws_connection, event_caller)
await event_processor.start_event_stream()


@staticmethod
async def plug(register: EventRegister, websocket: Any):
fastapi_adapter = FastApiAdapter(websocket)
Expand All @@ -34,6 +49,20 @@ async def plug_and_start(register: EventRegister, websocket: Any):

class SanicConnector:

def __init__(self, register: EventRegister, webscoket: Any):
self.register = register
self.websocket = webscoket

async def start(self):
sanic_adapter = SanicAdapter(self.websocket)
event_caller = EventCaller(self.register._event_book)
id_controller = IDController()
await sanic_adapter.start_connection()
current_id = id_controller.eval()
ws_connection = WebSocketConnection(current_id, sanic_adapter)
event_processor = EventProcessor(ws_connection, event_caller)
await event_processor.start_event_stream()

@staticmethod
async def plug(register: EventRegister, websocket: Any):
fastapi_adapter = SanicAdapter(websocket)
Expand Down
17 changes: 17 additions & 0 deletions zaptools/meta_tag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from typing import Any

class MetaTag:

def __init__(
self,
name:str,
description:str = "",
values:dict[str, Any] = {}
):
self.name = name
self.description = description
self.values = values




24 changes: 18 additions & 6 deletions zaptools/room.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import asyncio
from .tools import WebSocketConnection
from typing import Any
from .meta_tag import MetaTag

class Room:

name: str
_connections: dict[str, WebSocketConnection] = {}
_meta: dict[str, Any] = {}

def __init__(self, name:str):
self.name = name

def add(self,connection: WebSocketConnection):
def add(self,connection: WebSocketConnection,
meta_tag:MetaTag|None = None,
):
self._connections[connection.id] = connection
if meta_tag is None:
return
self._meta[connection.id] = meta_tag

def get_meta(self, connection: WebSocketConnection)-> MetaTag:
return self._meta.get(connection.id)

def remove(self, connection: WebSocketConnection):
del self._connections[connection.id]
Expand All @@ -23,11 +33,13 @@ async def send(
headers: dict|None = None,
exclude: WebSocketConnection|None = None
):
coros = []
for _, conn in self._connections.items():
if (exclude is not None and exclude.id == conn.id):
continue
coros.append(conn.send(event_name, payload,headers))
wconnections = self._connections.values()
exclude_id = "===" if exclude is None else exclude.id
coros = [
coro.send(event_name,payload,headers)
for coro in wconnections
if coro.id != exclude_id
]
await asyncio.gather(*coros)


Expand Down

0 comments on commit a8f6bea

Please sign in to comment.