A scalable, distributed real-time communication hub using WebSockets and JSON encoding, inspired by SignalR.
Project description
# ๐ก RTComm - Real-Time Communication Hub (SignalR Style in Python)
**RTComm** is a scalable, distributed real-time communication hub built with **FastAPI**, **WebSockets**, and **JSON encoding** โ inspired by **SignalR**. Designed for production with support for full **Hub Protocol**, client/server reflection, authentication, and bi-directional messaging.
---
## โจ Features
- โ
WebSocket Hub with FastAPI
- โ
JSON Hub Protocol: Invocation, Completion, Stream, Ping, Close, Acks, etc.
- โ
Client-Side and Server-Side Reflection (`invoke(method_name)`)
- โ
Authentication with Access Token
- โ
Modular Python SDK for Clients
- โ
Built using OOP + SOLID Principles
- โ
Designed for extensibility and microservice integration
---
## ๐ Folder Structure
rtcomm_package/
โโโ src/
โ โโโ rtcomm/
โ โโโ __init__.py
โ โโโ protocol/
โ โ โโโ messages.py
โ โโโ hub/
โ โ โโโ base.py
โ โ โโโ manager.py
โ โโโ client/
โ โโโ sdk.py
โโโ README.md
โโโ pyproject.toml
---
## ๐ Installation
```bash
pip install rtcomm
Or for local development:
git clone https://github.com/your-username/rtcomm.git
cd rtcomm
pip install -e .
๐ก Usage
๐ฅ 1. Server Side
Run FastAPI App
# main.py
from fastapi import FastAPI, WebSocket
from rtcomm.hub.base import RTCommHub
from rtcomm.hub.manager import ConnectionManager
from rtcomm.protocol.messages import HubMessage, InvocationMessage
app = FastAPI()
manager = ConnectionManager()
class MyHub(RTCommHub):
async def on_connect(self, client_id: str):
print(f"{client_id} connected")
async def on_disconnect(self, client_id: str):
print(f"{client_id} disconnected")
async def handle_message(self, client_id: str, websocket: WebSocket, message: HubMessage):
print(f"Received from {client_id}: {message.to_dict()}")
if isinstance(message, InvocationMessage):
await websocket.send_text(message.to_json())
uvicorn app.main:app --reload
๐ค 2. Client Side
Basic Example
# client.py
import asyncio
from rtcomm.client.sdk import RTCommClient
from rtcomm.protocol.messages import InvocationMessage, MessageType
async def main():
client = RTCommClient(uri="ws://localhost:8000/ws", access_token="token-user123")
client.on(MessageType.INVOCATION, lambda msg: print("[Client] Got:", msg.arguments))
await client.connect()
await client.send(InvocationMessage(invocation_id="1", target="broadcast", arguments=["Hello"]))
await asyncio.sleep(5)
await client.close()
if __name__ == "__main__":
asyncio.run(main())
๐ Authentication
Add a ?access_token=your-token query string when connecting via WebSocket. You can override the token verification logic in your RTCommHub.
async def authenticate(self, token: str) -> str:
if token.startswith("token-"):
return token.split("-")[1] # return user_id
raise Exception("Unauthorized")
๐ Supported Message Types (SignalR Protocol)
| Type | Name | Description |
|---|---|---|
| 1 | Invocation | Call a method |
| 2 | Stream Item | Stream data item |
| 3 | Completion | Result or error return |
| 4 | Stream Invocation | Start a stream |
| 5 | Cancel Invocation | Cancel ongoing stream |
| 6 | Ping | Keep alive |
| 7 | Close | Graceful close |
| 8 | Acknowledgment | Confirm receipt (optional) |
| 9 | Sequence Message | Ordered message (optional) |
๐งช Testing
pytest
๐ Python Compatibility
- Python 3.8+
- Fully typed (PEP 561)
- Async-first design with
asyncio
๐ฆ Build & Publish
python -m build
twine upload dist/*
๐ License
MIT ยฉ [Your Name]
๐ค Contributing
PRs welcome! Please open issues for bugs, enhancements, or questions.
๐ฃ Roadmap
The goal of rtcomm is to offer full SignalR-like functionality in Python โ scalable, secure, and cross-platform. Here's what's planned:
โ Initial Release
- WebSocket Hub with FastAPI
- JSON-based SignalR Hub Protocol
- Client-to-server & server-to-client method invocation
- Basic authentication via access tokens
- Reflection for dynamic method execution
๐ Coming Soon
๐ฅ Group Management
-
add_to_group(client_id, group_name) -
remove_from_group(client_id, group_name) -
send_to_group(group_name, message) - In-memory and pluggable distributed store (Redis/Mongo/etc.)
๐ Persistent Connections
- Reconnection logic with exponential backoff
- Keep-alive and heartbeat support
- Resume session after disconnects
โ๏ธ Scalability
- Plug-in support for Redis pub/sub or Kafka for multi-instance scaling
- Shared message bus to coordinate state
- Distributed group and client state store
๐ Automatic Reconnects (Client SDK)
- Reconnect with backoff strategy
- Resume invocation queue
- Client state restore
๐ก Streaming Support
- Server-to-client and client-to-server streaming
- Pause/resume/cancel stream control
- StreamItemMessage + StreamInvocationMessage handling
๐ Cross-Platform Support
- Python client โ
- Node.js/TypeScript client (planned)
- REST fallbacks for non-WebSocket clients
๐ Client Libraries
- TypeScript client for web browsers
- Python CLI & SDK
- CLI:
rtcomm connect ws://... --method=foo --args=bar
๐งฉ Hub Filters (Middleware)
- Support middleware for:
- Logging
- Authentication/authorization
- Error handling
- Message transformation
๐ง Have Ideas?
Feel free to open an issue or submit a PR. Collaboration is welcome!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file rtcomm-0.0.1.tar.gz.
File metadata
- Download URL: rtcomm-0.0.1.tar.gz
- Upload date:
- Size: 11.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4c22eaa86d47b6bd8f277289d71f2d3e9cac5a599f00007ea15fa19db60b702a
|
|
| MD5 |
690a78ee884c9958deb15812fb16147d
|
|
| BLAKE2b-256 |
97165f7a6f506fb5623cc949061db1124f56fe21af256f6779a1687871a0e0e7
|
File details
Details for the file rtcomm-0.0.1-py3-none-any.whl.
File metadata
- Download URL: rtcomm-0.0.1-py3-none-any.whl
- Upload date:
- Size: 10.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d5bd7f0b73c3398caa6d5c0f0e4af34371fd0343d9794726908cdf914cc9ee42
|
|
| MD5 |
6f7f5f7c9335fd1cc76efe0f4c2489f5
|
|
| BLAKE2b-256 |
97a2ccc73bbea94ab07219ba448f9897a790e9f23c66501fef64b2ec817e668f
|