Metadata-Version: 2.5
Name: replayrail
Version: 0.3.0
Summary: Durable, replayable and auditable realtime events for Python WebSockets, powered by Redis Streams.
Project-URL: Homepage, https://github.com/dopelDev/ReplayRail
Project-URL: Repository, https://github.com/dopelDev/ReplayRail
Project-URL: Issues, https://github.com/dopelDev/ReplayRail/issues
Author: ReplayRail contributors
License: MIT
License-File: LICENSE
Keywords: audit-log,events,fastapi,realtime,redis,redis-streams,replay,websockets
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.14
Provides-Extra: dev
Requires-Dist: asyncpg==0.32.0; extra == 'dev'
Requires-Dist: build==1.6.1; extra == 'dev'
Requires-Dist: httpx2==2.16.2; extra == 'dev'
Requires-Dist: mypy==2.4.1; extra == 'dev'
Requires-Dist: pytest-asyncio==1.5.0; extra == 'dev'
Requires-Dist: pytest==9.2.0; extra == 'dev'
Requires-Dist: ruff==0.17.6; extra == 'dev'
Requires-Dist: twine==7.0.0; extra == 'dev'
Requires-Dist: uvicorn==0.54.0; extra == 'dev'
Requires-Dist: websockets==17.4; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100; extra == 'fastapi'
Requires-Dist: starlette>=0.27; extra == 'fastapi'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.32; extra == 'postgres'
Provides-Extra: redis
Requires-Dist: redis>=5; extra == 'redis'
Description-Content-Type: text/markdown

# ReplayRail

Durable, replayable and auditable realtime events for Python WebSockets, powered by Redis Streams.

ReplayRail is a Python library for building WebSocket systems where realtime events are persisted, assigned cursors, replayable after reconnect, and traceable through audit metadata.

## Installation

ReplayRail requires Python 3.14 or later.

```bash
pip install replayrail
pip install "replayrail[redis,fastapi]"
pip install "replayrail[postgres,fastapi]"  # PostgreSQL instead of Redis
```

For local development:

```bash
pip install -e ".[redis,fastapi,postgres,dev]"
```

## Quickstart With Redis

```python
import redis.asyncio as redis

from replayrail import ReplayRail, ReplayRailConfig
from replayrail.stores.redis import RedisStreamStore

redis_client = redis.from_url("redis://localhost:6379", decode_responses=True)

rail = ReplayRail(
    store=RedisStreamStore(redis_client),
    config=ReplayRailConfig(
        stream_prefix="rr",
        default_replay_limit=100,
        max_stream_length=10_000,
    ),
)

event = await rail.publish(
    channel="restaurant:123:orders",
    event_type="order.created",
    payload={"order_id": "ord_123"},
    actor={"type": "waiter", "id": "usr_123"},
    metadata={"correlation_id": "req_abc123"},
)

missed_events = await rail.replay(
    channel="restaurant:123:orders",
    after=event.id,
)
```

## Quickstart With FastAPI WebSockets

```python
from fastapi import FastAPI, WebSocket

from replayrail.integrations.fastapi import ReplayRailWebSocket

app = FastAPI()
ws = ReplayRailWebSocket(rail)


@app.websocket("/ws/{channel}")
async def websocket_endpoint(websocket: WebSocket, channel: str):
    await ws.subscribe(websocket, channel=channel)
```

Run the example app:

```bash
docker compose up -d redis
uvicorn examples.fastapi_app:app --reload
```

uvicorn needs a WebSocket library to serve WebSockets. The `dev` extra includes `websockets`; in your own application, install `uvicorn[standard]`, or install `websockets` or `wsproto`. Without one, uvicorn answers the WebSocket handshake with 404 and logs "No supported WebSocket library detected".

Publish a test event:

```bash
curl -X POST http://localhost:8000/events/restaurant:123:orders \
  -H "content-type: application/json" \
  -d '{"type":"order.created","payload":{"order_id":"ord_123"}}'
```

Subscribe:

```txt
ws://localhost:8000/ws/restaurant:123:orders?last_event_id=0-0
```

## `last_event_id`

Every event has a stream cursor in `event.id`. A client should store the latest cursor it has processed. When it reconnects, it can pass that cursor as `?last_event_id=<id>`, and ReplayRail replays events after that ID.

Every event also has a logical `event_id`. Use `event_id` for tracing, deduplication, retries, external outbox integration, and client-side duplicate handling. Do not use `event_id` as the replay cursor.

If `last_event_id` is missing, `ReplayRailConfig.default_start_position` controls startup:

- `latest`: send only events published after the client connects.
- `earliest`: replay from the beginning of the channel.

Replay cursors use Redis Stream ID format:

```txt
<milliseconds>-<sequence>
```

The live-only cursor `$` is accepted for blocking reads and WebSocket startup. If a replay cursor is invalid, ReplayRail raises `InvalidCursorError`. If a store can determine that a valid cursor is older than retained history, ReplayRail raises `ReplayWindowExpiredError`. Over a WebSocket, these errors close the connection with a code instead; see [WebSocket Close Codes](#websocket-close-codes).

For `latest`, and for `last_event_id=$`, the WebSocket integration looks up the newest event ID once with `ReplayRail.latest_cursor()`, before it accepts the connection, and reads after it, so no event published once the client sees the connection open is skipped. Custom stores should implement an async `latest_cursor(channel)` that returns the newest stream ID, or `0-0` for an empty channel. Without it, `latest_cursor()` returns `$`, which a store resolves again on every read, so events published between two reads can be missed.

Each live WebSocket read waits up to `ReplayRailConfig.websocket_read_block_ms` for new events (5000 by default); `0` waits until an event arrives. Custom stores should give the `block_ms` argument of `read()` the meaning Redis `XREAD` gives it: `None` returns at once, `0` waits until an event arrives, and a positive value waits at most that many milliseconds.

The repository's `tests/test_store_contract.py` checks the behaviors that every store shares against the memory, Redis and PostgreSQL stores. To check a custom store, add a factory for it to the suite's `new_store` fixture.

## Retention

`ReplayRailConfig.max_stream_length` is passed to stores as the stream `maxlen` retention setting. The Redis backend forwards it to `XADD`; the memory backend applies the same observable trimming behavior for tests and local development.

Clients should treat `last_event_id` as a recovery cursor within the configured retention window, not as a permanent archive pointer. If the cursor falls outside retained history and the backend can identify that condition, replay raises `ReplayWindowExpiredError`.

The check is conservative: a cursor that is exactly the last trimmed event also counts as expired, even though no later event was lost, because the retained history alone cannot tell the two cases apart. While a WebSocket client catches up, the Redis backend checks retention whenever a read returns a full batch. That catches every trimmed cursor as long as `max_stream_length` is at least `websocket_batch_size`, which holds for the defaults (10 000 and 100).

## WebSocket Close Codes

`ReplayRailWebSocket.subscribe()` accepts the connection first. When a subscription cannot continue, it closes the connection with one of these codes and a short reason:

| Code | Reason | Cause | What the client should do |
|---|---|---|---|
| `4400` | `invalid_channel`, `invalid_cursor` | The channel name or `last_event_id` is not valid. | Fix the request; retrying it unchanged fails again. |
| `4403` | `forbidden` | The application's `authorize` hook denied the subscription. | Do not retry with the same credentials. |
| `4410` | `replay_window_expired` | `last_event_id` is older than retained history, at connection time or while catching up. | Reload the current state from your API, then reconnect without `last_event_id`. |
| `4429` | `slow_consumer` | The client fell too far behind its channel's shared read loop; see [Shared Reads Per Channel](#shared-reads-per-channel). | Reconnect with the last processed `event.id`. |
| `1011` | `store_error`, `internal_error` | The store failed, or another server error happened. | Reconnect with the last processed `event.id`. |

With 4400, 4403, 4410 and 4429, `subscribe()` returns normally. With 1011 it also raises `WebSocketDeliveryError`, so the server logs the failure. The codes are available as `CLOSE_INVALID_REQUEST`, `CLOSE_FORBIDDEN`, `CLOSE_REPLAY_WINDOW_EXPIRED`, `CLOSE_SLOW_CONSUMER` and `CLOSE_INTERNAL_ERROR` in `replayrail.integrations.fastapi`.

A browser client can react to them like this:

```js
let lastEventId = localStorage.getItem("lastEventId");

function connect() {
  const query = lastEventId ? `?last_event_id=${lastEventId}` : "";
  const socket = new WebSocket(`ws://localhost:8000/ws/restaurant:123:orders${query}`);

  socket.onmessage = (message) => {
    const event = JSON.parse(message.data);
    // Handle the event, then remember its cursor.
    lastEventId = event.id;
    localStorage.setItem("lastEventId", lastEventId);
  };

  socket.onclose = (close) => {
    if (close.code === 4400 || close.code === 4403) {
      return; // Invalid or forbidden: fix the request or the credentials instead of retrying.
    }
    if (close.code === 4410) {
      // Cursor too old: reload the current state from your API, then start live.
      lastEventId = null;
      localStorage.removeItem("lastEventId");
    }
    setTimeout(connect, 1000); // 1011, 4429 or a dropped connection: retry with the cursor.
  };
}

connect();
```

`subscribe()` also watches the WebSocket's `receive()` for the client's disconnect and stops reading as soon as it arrives, so a client that leaves an idle channel does not leave a read loop behind. Messages from the client are ignored. A custom WebSocket object without `receive()` is only noticed when a send fails.

## Shared Reads Per Channel

`ReplayRailWebSocket` reads each channel once, however many clients subscribe to it. The first subscriber of a channel starts a read loop at the newest event, the others join it, and the loop stops when the last one leaves. A subscriber that reconnects with a cursor first catches up on its own with `replay()`, then follows the loop through a queue of its own, so it still receives every event after its cursor, once and in order.

- Create the adapter once, as in the quickstart. The loops belong to the adapter: an adapter created per connection shares nothing, and each process has its own loops.
- A subscriber with more than `ReplayRailConfig.websocket_fanout_queue_size` events waiting in its queue is closed with 4429 `slow_consumer`, so that it cannot hold back the others. The default is 1000, and a value below `websocket_batch_size` counts as `websocket_batch_size`. The client reconnects with its cursor and catches up from the stream.
- `ReplayRailWebSocket(rail, fanout=False)` keeps one read loop per subscription. A store without `latest_cursor()` always does.
- Each catch-up batch is a `replay()`, so an observer receives one `replayed` per batch.

See [docs/design/fanout.md](docs/design/fanout.md).

## WebSocket Control Messages

A client can ask for control messages by connecting with `?control=1`. The application can also force the choice with `subscribe(..., control_messages=True)` or `False`. Without them, the connection carries only events, as before.

A control message is a JSON object with a `control` key, which no event has:

- `{"control": "replay_complete", "cursor": "1719367320123-0"}` arrives once. It comes after every event that was in the channel when the client connected, and before any newer event. On a live start it arrives right after the connection opens. `cursor` is the position reached; on a live start with a store that cannot look up the newest event, it is `null`.
- `{"control": "closing", "code": 4410, "reason": "replay_window_expired"}` arrives right before ReplayRail closes the connection, with the same code and reason as the close frame.

```js
socket.onmessage = (message) => {
  const data = JSON.parse(message.data);
  if (data.control === "replay_complete") {
    // The client has caught up: switch the UI from "syncing" to "live".
  } else if (data.control === undefined) {
    // An event.
  }
};
```

See [docs/design/websocket-protocol.md](docs/design/websocket-protocol.md) for the exact rules.

## Authorizing Subscriptions

Pass an `authorize` hook to decide, per channel, whether a client may subscribe:

```python
from fastapi import WebSocket

from replayrail.integrations.fastapi import ReplayRailWebSocket


async def authorize(websocket: WebSocket, channel: str) -> bool:
    user = await current_user(websocket)
    return user is not None and user.can_read(channel)


ws = ReplayRailWebSocket(rail, authorize=authorize)
```

The hook receives the WebSocket, so it can read headers, cookies and query parameters. It can be a plain function or a coroutine. It runs for every subscription before the connection is accepted: after the channel is validated, and before any store lookup. If it returns false, the connection closes with 4403 `forbidden`; if it raises, with 1011.

## Event Envelope

```json
{
  "id": "1719367320123-0",
  "event_id": "b6d8c2f1-7e35-4f86-9a67-8d9c8fdd1c55",
  "channel": "restaurant:123:orders",
  "type": "order.created",
  "payload": {"order_id": "ord_123"},
  "actor": {"type": "waiter", "id": "usr_123"},
  "metadata": {"correlation_id": "req_abc123"},
  "created_at": "2026-06-29T12:00:00Z"
}
```

## Reliable publishing and databases

ReplayRail is not a database transaction manager. If your app writes to a database and then publishes to ReplayRail, use an app-owned transactional outbox for critical workflows.

ReplayRail is outbox-friendly via:

- `event_id`
- `prepare_event()`
- `publish_event()`
- event serialization helpers
- optional Redis idempotency

See [docs/reliable-publishing.md](docs/reliable-publishing.md).

## Redis idempotency

`RedisStreamStore(..., idempotency=True)` can deduplicate publishes by logical `event_id` for outbox retry flows. By default, duplicate matching events return the existing stream id. With `duplicate_policy="raise"`, duplicates raise `DuplicateEventError`.

If the same `event_id` is reused for different content, ReplayRail raises `DuplicateEventConflictError`.

See [docs/idempotency.md](docs/idempotency.md).

## PostgreSQL

For applications that already run PostgreSQL, `PostgresEventStore` keeps each channel in PostgreSQL tables instead of a Redis stream. It needs the `postgres` extra, which installs asyncpg. In your startup code, for example a FastAPI `lifespan` handler:

```python
import asyncpg

from replayrail import ReplayRail
from replayrail.stores.postgres import PostgresEventStore

pool = await asyncpg.create_pool("postgresql://app@db/app")
store = PostgresEventStore(pool)
await store.create_tables()
rail = ReplayRail(store)
```

- The pool belongs to your application: `rail.close()` releases the store's own connection and leaves the pool open. While it waits for events, the store keeps one connection listening for `NOTIFY`, so the pool needs at least two.
- `create_tables()` creates `replayrail_events`, `replayrail_channels` and `replayrail_event_ids` if they do not exist. To create them in your own migrations instead, apply the SQL that `store.schema_sql()` returns. `table_prefix` changes the names.
- Publishes to one channel run one at a time, so event IDs follow commit order without gaps. Different channels publish in parallel.
- Publishing is still a write separate from your own data, so critical workflows still need an outbox, as with Redis; see [Reliable publishing and databases](#reliable-publishing-and-databases).
- Payloads, actors and metadata are stored as JSONB, which cannot hold the NUL character (`\u0000`); publishing one raises `StoreError`.
- The idempotency options work as in `RedisStreamStore`.

See [docs/design/postgresql.md](docs/design/postgresql.md).

## Observability

Pass an observer to count publishes, replays, deliveries and closes, measure delivery latency, and see store failures, with the metrics library of your choice:

```python
from replayrail import Failed, Published, ReplayRail, ReplayRailObserver


class Metrics(ReplayRailObserver):
    def published(self, published: Published) -> None:
        PUBLISHED.labels(published.event.channel).inc()

    def failed(self, failed: Failed) -> None:
        FAILURES.labels(failed.operation).inc()


rail = ReplayRail(store, observer=Metrics())
```

The methods of `ReplayRailObserver` do nothing by default; override the ones you need. Each one receives a single immutable object:

| Method | Fields | When |
|---|---|---|
| `published` | `event` | An event was stored, including a deduplicated one. |
| `replayed` | `channel`, `after`, `count` | `replay()` returned `count` events. |
| `subscribed` | `channel`, `live` | A WebSocket subscription passed its checks and was accepted. |
| `delivered` | `channel`, `event`, `latency_seconds`, `replay` | An event was sent to a WebSocket client. |
| `closed` | `channel`, `code`, `reason` | ReplayRail closed a connection with one of its codes, including rejections before delivery. |
| `unsubscribed` | `channel` | A subscription reported by `subscribed` ended, for any reason. |
| `failed` | `operation`, `channel`, `error` | `publish()`, `replay()` or `read()` raised `StoreError` or an unexpected exception. |

`subscribed` and `unsubscribed` always come in pairs, so their difference is the number of active subscriptions. `latency_seconds` runs from the event's `created_at` to the send, on the server's clock. `replay` is true for events the client missed while away, and false for events published after it subscribed. To tell them apart, a subscription that starts with a replay looks up the newest event once more when an observer is configured.

Invalid input, expired cursors and duplicate events are not reported as failures. Other errors inside the WebSocket integration appear as `closed` with code 1011. Observer methods run synchronously and should only record values. If one raises, ReplayRail logs the exception under the `replayrail` logger and the operation continues. See [docs/design/observability.md](docs/design/observability.md).

## RestaurantHUB Example

ReplayRail core stays generic. RestaurantHUB can model application-specific behavior with channels and event types:

```python
await rail.publish(
    channel=f"restaurant:{restaurant_id}:kitchen",
    event_type="order.ready",
    payload={
        "order_id": order_id,
        "table_id": table_id,
    },
    actor={
        "type": "kitchen_staff",
        "id": staff_id,
    },
    metadata={
        "source": "restauranthub-api",
        "correlation_id": request_id,
    },
)
```

Suggested channels:

- `restaurant:{restaurant_id}:orders`
- `restaurant:{restaurant_id}:kitchen`
- `restaurant:{restaurant_id}:tables`
- `restaurant:{restaurant_id}:reservations`
- `restaurant:{restaurant_id}:admin`
- `order:{order_id}`
- `user:{user_id}:notifications`

Suggested events:

- `order.created`
- `order.confirmed`
- `order.preparing`
- `order.ready`
- `order.delivered`
- `order.cancelled`
- `kitchen.ticket.created`
- `kitchen.ticket.updated`
- `table.occupied`
- `table.released`
- `reservation.created`
- `reservation.cancelled`
- `payment.failed`
- `inventory.low`

## Why Not Just `redis.asyncio`?

You can use `redis.asyncio` directly. ReplayRail adds reusable application semantics on top of Redis Streams:

- event envelopes;
- channel validation;
- JSON serialization boundaries;
- cursor-based replay;
- reconnect recovery through `last_event_id`;
- retention configuration;
- WebSocket delivery;
- pluggable stores for tests and future backends.

`redis.asyncio` gives you Redis commands. ReplayRail gives your WebSocket application a durable realtime event contract.

## Included

- Python package named `replayrail`.
- Core event models and validation.
- Config object.
- Event store protocol.
- Redis Streams backend using `redis.asyncio`.
- PostgreSQL backend using asyncpg, as the `postgres` extra.
- In-memory backend for tests and local development.
- `ReplayRail.publish(...)`, `ReplayRail.replay(...)`, and `ReplayRail.read(...)`.
- FastAPI / Starlette WebSocket integration.
- Cursor-based recovery with `last_event_id`.
- WebSocket close codes for invalid requests (4400), expired cursors (4410) and server errors (1011).
- Opt-in WebSocket control messages: `replay_complete` and `closing`.
- An `authorize` hook per channel, with close code 4403.
- One read loop per channel, shared by its WebSocket subscribers, with close code 4429 for a subscriber that falls too far behind.
- Observability hooks through `ReplayRailObserver`.
- `ReplayRail.latest_cursor()` for live reads that do not skip events.
- Basic stream retention through `maxlen`.
- JSON serialization.
- Logical `event_id` for tracing and deduplication.
- `ReplayRail.prepare_event(...)` and `ReplayRail.publish_event(...)`.
- Stable event dict serialization helpers.
- Optional Redis and memory-store idempotency by `event_id`.
- Optional healthcheck support.
- Reliable publishing documentation for app-owned outbox patterns.
- Minimal FastAPI example.

## Development Verification

The reproducible local verification path uses Docker:

```bash
docker compose run --rm test
docker compose down
```

The test service uses Python 3.14 by default, installs `.[redis,fastapi,postgres,dev]` with the versions pinned in `constraints-dev.txt`, builds with the backend versions pinned in `constraints-build.txt`, runs Redis and PostgreSQL through Compose, sets `REDIS_URL=redis://redis:6379` and `POSTGRES_URL=postgresql://postgres@postgres:5432/replayrail`, and executes:

```bash
pytest -p no:cacheprovider
ruff check .
ruff format --check .
mypy src/replayrail
python -m build --dependency-constraints-txt constraints-build.txt
twine check dist/*
```

`pyproject.toml` only sets a minimum `hatchling` version in `[build-system]`, so other builders can use newer ones.

## Intentionally Not Included

- database sessions, commits, or rollbacks;
- SQLAlchemy models;
- outbox tables;
- migrations;
- background outbox workers;
- advanced client ACK protocol, delivery tracking, retries, or dead-letter streams;
- Redis consumer groups;
- distributed fanout optimization;
- long-term compliance archive;
- complex auth framework;
- admin UI;
- CLI.

Metrics exporters, dashboards, more backends (NATS JetStream, Kafka/Redpanda) and a frontend client are planned; see `ROADMAP.md` in the repository.

## Known Limitation

ReplayRail prioritizes correctness and simplicity.

- Shared reads are local to one adapter in one process: with several workers, each one reads every channel that its clients subscribe to.
- Replay recovery is bounded by stream retention. ReplayRail can signal expired windows only when the backend can determine that a cursor is older than retained history. Over a WebSocket, an expired cursor closes the connection with 4410.
- `actor` and `metadata` are preserved and delivered as audit context, but ReplayRail does not provide a compliance archive or authorization framework.

Planned work is listed in `ROADMAP.md` in the repository.
