Skip to main content

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rtcomm-0.0.1.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rtcomm-0.0.1-py3-none-any.whl (10.8 kB view details)

Uploaded Python 3

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

Hashes for rtcomm-0.0.1.tar.gz
Algorithm Hash digest
SHA256 4c22eaa86d47b6bd8f277289d71f2d3e9cac5a599f00007ea15fa19db60b702a
MD5 690a78ee884c9958deb15812fb16147d
BLAKE2b-256 97165f7a6f506fb5623cc949061db1124f56fe21af256f6779a1687871a0e0e7

See more details on using hashes here.

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

Hashes for rtcomm-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d5bd7f0b73c3398caa6d5c0f0e4af34371fd0343d9794726908cdf914cc9ee42
MD5 6f7f5f7c9335fd1cc76efe0f4c2489f5
BLAKE2b-256 97a2ccc73bbea94ab07219ba448f9897a790e9f23c66501fef64b2ec817e668f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page