# Mongoengine Read-Write Router

A MongoDB read-write separation solution for mongoengine ODM, inspired by the [django-rw-router](https://github.com/pydtools/django-rw-router) architecture.

This library routes write operations to the primary database and read operations to replica set members, with configurable consistency strategies.

## Features

- **Automatic read-write routing** - Writes go to primary, reads go to replicas
- **Multiple consistency strategies** - random, transaction-aware, consistent hashing
- **Read-after-write consistency** - Ensures you see your own writes
- **Request context tracking** - Thread-safe context using `contextvars`
- **Web framework integration** - Middleware for FastAPI, Flask, and Django
- **Force primary reads** - Explicit control when you need fresh data
- **Write operation tracking** - Automatic context updates on writes

## Installation

```bash
pip install mongoengine-rw-router
```

## Quick Start

```python
from mongoengine import connect, Document, StringField, IntField
from mongoengine_rw_router import (
    RwDocumentMixin,
    configure,
    MongoRouterMiddleware,
)

# 1. Set up connections
connect(db="myapp", alias="default", host="mongodb://primary:27017")
connect(
    db="myapp",
    alias="replica1",
    host="mongodb://replica1:27017",
    read_preference=ReadPreference.SECONDARY_PREFERRED,
)

# 2. Configure router
configure(
    primary_alias="default",
    replica_aliases=["replica1"],
    strategy="transaction_aware",
)

# 3. Define model with routing
class User(RwDocumentMixin, Document):
    name = StringField()
    email = StringField()
    age = IntField()

    meta = {"db_alias": "default"}

# 4. Use it!
user = User.objects.first()  # Reads from replica
user.age = 25
user.save()  # Writes to primary
```

## License

MIT

## Credits

Inspired by [django-rw-router](https://github.com/pydtools/django-rw-router)
