Metadata-Version: 2.5
Name: kestrelmq
Version: 0.1.0
Summary: Official lightweight Python SDK for KestrelMQ
Project-URL: Homepage, https://kestrelmq.dev
Project-URL: Repository, https://github.com/dmereiauron/kestrelmq
Project-URL: Documentation, https://github.com/dmereiauron/kestrelmq/tree/main/packages/python-sdk
Author: KestrelMQ Contributors
License-Expression: MIT
Keywords: kestrelmq,notifications,queue,sdk,webhooks
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Provides-Extra: test
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# kestrelmq (Python SDK)

Official lightweight Python client for [KestrelMQ](https://github.com/dmereiauron/kestrelmq): send events and verify outbound webhook signatures.

- Python 3.10+
- One runtime dependency: [`httpx`](https://www.python-httpx.org/)
- Sync (`KestrelMQ`) and async (`AsyncKestrelMQ`) clients
- Webhook verification with the standard library (`hmac`, `hashlib`), constant-time comparison and secret rotation support
- Typed (`py.typed`)

## Install

```bash
pip install kestrelmq
```

From a checkout of this repository:

```bash
pip install -e packages/python-sdk
```

## Configure

| Argument | Environment variable | Default |
| :--- | :--- | :--- |
| `api_key` | `KESTRELMQ_API_KEY` | required (`kmq_live_...`) |
| `base_url` | `KESTRELMQ_BASE_URL` | `http://localhost:3000` |
| `timeout` | | `10.0` seconds |
| `workspace_id` | | sent as `X-Workspace-Id` when set |

`base_url` may include or omit the `/v1` suffix.

## Send events

```python
from kestrelmq import KestrelMQ, KestrelAPIError

with KestrelMQ(api_key="kmq_live_...", base_url="http://localhost:3000") as kestrel:
    try:
        receipt = kestrel.send_event(
            "order.paid",
            {"orderId": "ord_9001", "amount": 149.99},
            recipient={"email": "ada@example.com"},
            idempotency_key="order-paid-ord_9001",
        )
        print(receipt["eventId"], receipt["deliveryIds"])
    except KestrelAPIError as err:
        # RFC 9457 Problem Details
        print(err.status, err.type, err.detail, err.errors)
        if err.status == 429 and err.retry_after is not None:
            print(f"retry after {err.retry_after}s")
```

`send_event` calls `POST /v1/events` and returns the `202 Accepted` body. Arguments:

- `event`: event name, e.g. `order.paid`.
- `payload`: JSON-serializable `dict`.
- `recipient`: optional `dict` used by routing rules and templates.
- `deliver_at`: optional ISO 8601 string or `datetime` for scheduled delivery.
- `idempotency_key`: optional. Sent as the `Idempotency-Key` header and in the body. A repeated key returns the original event with `idempotentReplay: True` and creates no new deliveries.

### Async

```python
import asyncio
from kestrelmq import AsyncKestrelMQ

async def main() -> None:
    async with AsyncKestrelMQ() as kestrel:  # reads KESTRELMQ_API_KEY / KESTRELMQ_BASE_URL
        await kestrel.send_event("user.signup", {"userId": "u_1"})

asyncio.run(main())
```

Both clients accept an existing `httpx.Client` / `httpx.AsyncClient` through `http_client=` for custom transports, proxies or connection pooling. A client you pass in is not closed by the SDK.

### Errors

| Exception | When |
| :--- | :--- |
| `KestrelAPIError` | Non-2xx response. Fields: `status`, `type`, `title`, `detail`, `instance`, `errors`, `retry_after`, `request_id`. |
| `KestrelTimeoutError` | No response within `timeout`. |
| `KestrelMQError` | Base class of both. |

## Verify webhook signatures

KestrelMQ signs `"{timestamp}.{raw_body}"` with HMAC-SHA256 using your workspace signing secret and sends:

- `X-KestrelMQ-Timestamp`: Unix seconds
- `X-KestrelMQ-Signature`: `v1=<hex>`, or `v1=<new>,v1=<old>` while a secret rotation grace window is open
- `X-KestrelMQ-Delivery-Id`, `X-KestrelMQ-Event-Id`

```python
import os
from kestrelmq import verify_webhook_signature

ok = verify_webhook_signature(
    payload=raw_body,                                   # str | bytes, exactly as received
    signature_header=headers["X-KestrelMQ-Signature"],
    secrets=os.environ["KESTRELMQ_SIGNING_SECRET"],     # str | list[str]
    tolerance_seconds=300,
    timestamp=headers["X-KestrelMQ-Timestamp"],
)
```

- Returns `True` if any `v1=` entry matches any secret. Pass a list of secrets to accept both while you roll your own configuration.
- Rejects timestamps more than `tolerance_seconds` away from now in either direction (replay protection).
- `timestamp` may be omitted if the header carries it inline (`t=<unix>,v1=<hex>`). Conflicting timestamps are rejected.
- Comparisons use `hmac.compare_digest`. Malformed input returns `False` and never raises.

Always verify the raw body. Parsing and re-serializing JSON changes the bytes and breaks the signature.

### Flask

```python
import os
from flask import Flask, abort, request
from kestrelmq import verify_webhook_signature

app = Flask(__name__)

@app.post("/webhooks/kestrelmq")
def kestrelmq_webhook():
    if not verify_webhook_signature(
        request.get_data(),
        request.headers.get("X-KestrelMQ-Signature", ""),
        os.environ["KESTRELMQ_SIGNING_SECRET"],
        timestamp=request.headers.get("X-KestrelMQ-Timestamp"),
    ):
        abort(401)
    event = request.get_json()
    return "", 204
```

### FastAPI

```python
import os
from fastapi import FastAPI, HTTPException, Request
from kestrelmq import verify_webhook_signature

app = FastAPI()

@app.post("/webhooks/kestrelmq", status_code=204)
async def kestrelmq_webhook(request: Request) -> None:
    body = await request.body()
    if not verify_webhook_signature(
        body,
        request.headers.get("x-kestrelmq-signature", ""),
        os.environ["KESTRELMQ_SIGNING_SECRET"],
        timestamp=request.headers.get("x-kestrelmq-timestamp"),
    ):
        raise HTTPException(status_code=401)
```

## Development

```bash
cd packages/python-sdk
python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[test]"
pytest
```

## License

MIT
