Skip to main content

csrd WebSocket Library

Status: Active implementation (v0.1.0) — core manager/router primitives available.

Real-time WebSocket connection lifecycle, room broadcast, and routing primitives for the csrd ecosystem.

Overview

This package provides reusable WebSocket infrastructure for building real-time services on FastAPI. It handles connection registration, room membership, message routing, and optional policy hooks — but does not define domain-specific protocols.

Design reference

  • Design doc: ../../docs/WEBSOCKET_LIBRARY_DESIGN.md
  • Implementation plan: ../../docs/WEBSOCKET_LIBRARY_IMPLEMENTATION_PLAN.md

Current API

from csrd.realtime import (
    ConnectionContext,
    ConnectionManager,
    MessageEnvelope,
    MessageRouter,
)

Status

Current milestone includes:

  • ConnectionManager (connect/disconnect, room membership, room/global broadcast)
  • MessageRouter (event dispatch + optional policy hooks)
  • ConnectionContext and MessageEnvelope
  • Typed errors for policy/validation/connection lookup

Minimal FastAPI wiring example

from fastapi import FastAPI, WebSocket
from starlette.websockets import WebSocketDisconnect
from contextlib import suppress

from csrd.realtime import (
    ConnectionContext,
    ConnectionManager,
    ConnectionNotFoundError,
    MessageEnvelope,
    MessageRouter,
)

app = FastAPI()
manager = ConnectionManager()
router = MessageRouter()


@app.websocket("/ws")
async def ws_endpoint(ws: WebSocket):
    await ws.accept()
    connection_id = ws.query_params.get("connection_id", "anon")
    context = ConnectionContext(connection_id=connection_id)
    await manager.connect(ws, context)

    try:
        while True:
            data = await ws.receive_json()
            envelope = MessageEnvelope.model_validate(data)
            await router.dispatch(connection_id, envelope, manager)
    except WebSocketDisconnect:
        pass
    finally:
        with suppress(ConnectionNotFoundError):
            await manager.disconnect(connection_id)

Optional context adapter pattern

csrd-realtime stays standalone, but supports optional context binding around each dispatch via RealtimeContextAdapter.

Use this to bridge into csrd-context/logging contextvars without adding a hard dependency from realtime core.

from csrd.realtime import MessageRouter, RealtimeContextAdapter


def bind_ws_context(dispatch_context):
    # Example: set your contextvars and return reset token(s)
    token = some_contextvar.set(
        {
            "connection_id": dispatch_context.connection_id,
            "tenant_id": dispatch_context.connection.tenant_id,
            "event_type": dispatch_context.event_type,
            "trace_id": dispatch_context.trace_id,
        }
    )
    return token


def reset_ws_context(token):
    some_contextvar.reset(token)


router = MessageRouter(
    context_adapter=RealtimeContextAdapter(bind=bind_ws_context, reset=reset_ws_context)
)

Operational defaults (current)

  • Backpressure model: direct send_json per message (no per-connection queue in v0.1.x).
  • Failure behavior: if a send fails, ConnectionManager evicts that connection (best-effort fan-out).
  • Timeout behavior: manager applies bounded send timeout by default (send_timeout_seconds=5.0).
  • Router behavior: handler exceptions are surfaced to caller by default; set MessageRouter(raise_handler_exceptions=False) for log-and-continue mode.

Tenant and room naming guidance

Room names are consumer-defined strings. Use a namespaced format to avoid cross-tenant collisions.

Recommended patterns:

  • tenant:{tenant_id}:session:{session_id} for gameplay sessions
  • tenant:{tenant_id}:party:{party_id} for party-level channels
  • tenant:{tenant_id}:system for scoped system broadcasts

Guidance:

  • Always resolve tenant_id server-side from auth context.
  • Never trust client-provided room names without authorization checks.
  • Keep room IDs stable and deterministic so reconnect/join logic is predictable.

Metadata

Release files for csrd-realtime 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for csrd-realtime 0.6.0
File Size Uploaded
csrd_realtime-0.6.0.tar.gz 17.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for csrd-realtime 0.6.0
File Interpreter ABI Platform
csrd_realtime-0.6.0-py3-none-any.whl Python 3 none any Details

Total release size: 27.8 kB

Release files / csrd_realtime-0.6.0.tar.gz

Download URL csrd_realtime-0.6.0.tar.gz
Size 17.3 kB
Tags Source
SHA-256 checksum
How to use checksums
734d8e6499f59c9eb2370d258e66ba0b3fc53e98b2a8cf7e594ea25746112abb
BLAKE2b-256 checksum
How to use checksums
96abfa241c88372945de7bf36ff6bf036d5b5dd7a499ea1bc9e0109d1a2e4c39
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 16, 2026.

Transparency log

Release files / csrd_realtime-0.6.0-py3-none-any.whl

Download URL csrd_realtime-0.6.0-py3-none-any.whl
Size 10.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
29a17e382022ab1532d8495c1463d3d90589955062b86225838e728c429a6e34
BLAKE2b-256 checksum
How to use checksums
cf59493486379d3470f340ae05022f103da92546b512aa3520ea5cb7f9eb7167
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 16, 2026.

Transparency log

Release history Release notifications | RSS feed

0.8.0

2 release files

0.7.0

2 release files

This release

0.6.0 This release

2 release files

0.5.30

2 release files

0.5.29

2 release files

0.5.28

2 release files

0.5.27

2 release files

0.5.26

2 release files

0.5.25

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page