Metadata-Version: 2.4
Name: dddramatiq
Version: 0.0.1
Summary: Dramatiq helpers: a task facade with actor middlewares, cron tasks and broker middlewares for health checks, metrics and async shutdown
Keywords: python,dddramatiq,dramatiq,asyncio,background tasks,task queue,worker,cron,health check,prometheus,middleware,sentry
Author: davyddd
License-Expression: MIT
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Dist: dddesign>=2.1.2,<3
Requires-Dist: ddutils>=0.4.0,<0.5.0
Requires-Dist: dramatiq>=2.0,<2.3
Requires-Dist: prometheus-client>=0.20,<1
Requires-Dist: pydantic>=2.1,<3
Requires-Dist: sentry-sdk>=2.12,<4
Requires-Python: >=3.11, <3.16
Project-URL: Repository, https://github.com/davyddd/dddramatiq
Description-Content-Type: text/markdown

# dddramatiq

[![pypi](https://img.shields.io/pypi/v/dddramatiq.svg)](https://pypi.python.org/pypi/dddramatiq)
[![downloads](https://static.pepy.tech/badge/dddramatiq/month)](https://pepy.tech/project/dddramatiq)
[![versions](https://img.shields.io/pypi/pyversions/dddramatiq.svg)](https://github.com/davyddd/dddramatiq)
[![codecov](https://codecov.io/gh/davyddd/dddramatiq/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/dddramatiq)
[![license](https://img.shields.io/github/license/davyddd/dddramatiq.svg)](https://github.com/davyddd/dddramatiq/blob/main/LICENSE)

Dramatiq helpers: a task facade with actor middlewares, cron tasks and broker middlewares for health checks, metrics and async shutdown

## Installation

Install the library using pip:
```bash
pip install dddramatiq
```

## Development

The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:

```bash
fab build      # build the dev image
fab tests      # run pytest
fab linters    # run ruff (with --fix), ty and complexipy
fab shell      # IPython inside the container
fab bash       # bash inside the container
```

This project was generated from [dd-lib-stub](https://github.com/davyddd/dd-lib-stub);
run `uvx copier update` to pull in template updates.

## Compatibility

Python 3.11 to 3.15. What changed in each release, breaking changes included,
is in the [GitHub releases](https://github.com/davyddd/dddramatiq/releases).

<!-- The sections below are the library's own; copier update leaves them alone -->

Depends on `dramatiq>=2.0,<2.3`, `prometheus-client>=0.20,<1`, `sentry-sdk>=2.12,<4`, `dddesign>=2.1.2,<3`,
`ddutils>=0.4.0,<0.5.0` and `pydantic>=2.1,<3`. The tests run on dramatiq's stub broker, no Redis or RabbitMQ is
needed.

| Package | What is in it |
|---|---|
| `dddramatiq.facade` | `BaseDramatiqFacade`: finds the task modules, wraps the actors, sends tasks, lists the cron jobs |
| `dddramatiq.actor_middlewares` | Layers around every actor: log properties, Sentry tags, start and finish logs |
| `dddramatiq.decorators` | `cron`, the mark of a periodic actor |
| `dddramatiq.middlewares` | Broker middlewares: `AsyncShutdown`, `HealthCheck`, `PrometheusMetrics` |

Actors are async functions. dramatiq runs them on one event loop per worker process, the thread its `AsyncIO`
middleware manages, so `AsyncIO()` must be in the broker's middleware list.

## Facade

One facade per application is the door to its tasks. A subclass says where the task modules are; the instance
imports them, wraps every actor in the actor middlewares and sends tasks by name, so the code that enqueues a
task never imports the module that defines it.

```python
import dramatiq
from dramatiq.brokers.redis import RedisBroker
from dramatiq.middleware import AsyncIO

from dddramatiq.actor_middlewares import LogPropertiesManagerMiddleware, SentryTagsMiddleware, TaskLoggingMiddleware
from dddramatiq.facade import BaseDramatiqFacade
from dddramatiq.middlewares import AsyncShutdown, HealthCheck, PrometheusMetrics

broker = RedisBroker(
    url='redis://localhost/0',
    middleware=[AsyncIO(), PrometheusMetrics(), HealthCheck(), AsyncShutdown(close_connections)],
)
dramatiq.set_broker(broker)


class DramatiqFacade(BaseDramatiqFacade):
    base_dir = '/app/src'                                   # where the pattern is looked up
    module_pattern = 'app.*.infrastructure.ports.tasks'     # dotted, `*` for one package
    actor_middlewares = (                                   # the first one is the outermost
        LogPropertiesManagerMiddleware(log_properties_registry),
        SentryTagsMiddleware(log_properties_registry),
        TaskLoggingMiddleware(),
    )


dramatiq_facade_impl = DramatiqFacade()
```

```python
# app/order_context/infrastructure/ports/tasks/__init__.py
import dramatiq

from dddramatiq.decorators import cron


@dramatiq.actor(queue_name='orders', max_retries=3)
async def order_create_task(order_id: int) -> None: ...


@cron('*/5 * * * *')
@dramatiq.actor
async def order_expire_periodic_task() -> None: ...
```

| Method | What it does |
|---|---|
| `setup_tasks()` | Imports every module the pattern matches and wraps every actor of the broker in the actor middlewares. Runs once; what the worker and the scheduler call on start |
| `send_task(task_name, *args, delay=None, **kwargs)` | Enqueues a message for the actor with its queue, priority and options. `delay` is keyword only, milliseconds or a `timedelta`; everything else goes to the task |
| `run_task_sync(task_name, *args, **kwargs)` | Runs the actor in place, through the middlewares, and returns its result. Needs the event loop thread of `AsyncIO`, so it works inside a worker; elsewhere dramatiq raises `RuntimeError` |
| `get_cron_jobs()` | Yields `(job_path, crontab, job_name)` for every actor marked with `@cron` |
| `broker` | The global broker, `dramatiq.get_broker()` |

- The arguments of a task are passed through JSON before they are sent or run, so an actor always gets what a
  real broker would deliver: a tuple arrives as a list, and a value JSON cannot carry raises `TypeError`.
- A process that never called `setup_tasks()`, a script or a test, gets it on the first `send_task`,
  `run_task_sync` or `get_cron_jobs`.
- Actors are async functions: a sync actor on the broker makes `setup_tasks()` raise `TypeError` with its name.
  An actor is wrapped once, by the facade that set it up first.
- Declare the facade in a module that imports no task: importing it costs nothing, and the tasks are imported
  when the process sets them up.

```python
dramatiq_facade_impl.send_task('order_create_task', order_id)
dramatiq_facade_impl.send_task('order_create_task', order_id=order_id, delay=timedelta(minutes=5))
```

A scheduler turns the cron jobs into triggers. With APScheduler:

```python
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

scheduler = BlockingScheduler()
dramatiq_facade_impl.setup_tasks()
for job_path, crontab, job_name in dramatiq_facade_impl.get_cron_jobs():
    scheduler.add_job(job_path, trigger=CronTrigger.from_crontab(crontab, timezone='UTC'), name=job_name)
```

## Actor middlewares

A `BaseActorMiddleware` is a layer around the coroutine of every actor: `__call__(call_next, *args, **kwargs)`
gets the next layer and the arguments of the run.

```python
from dddramatiq.actor_middlewares import BaseActorMiddleware


class TimingMiddleware(BaseActorMiddleware):
    async def __call__(self, call_next, *args, **kwargs):
        started = time.monotonic()
        try:
            return await call_next(*args, **kwargs)
        finally:
            logger.info({'message': 'Task took', 'seconds': time.monotonic() - started})
```

- `LogPropertiesManagerMiddleware(log_properties_registry)` enters the scope of a `ScopedRegistry` from
  [ddutils](https://github.com/davyddd/ddutils) for the run: the log properties are created on enter and removed
  when the run is over, failed or not. The registry and its model are the application's.
- `SentryTagsMiddleware(log_properties_registry)` tags the Sentry scope of the run with the properties, nested
  fields flattened with dots, `None` left out. The registry must hold a pydantic model. List it after the manager.
- `TaskLoggingMiddleware(max_result_log_size=1000)` logs `Started task <name>`, then `Finished task <name>` with
  `result` when there is one, or `Failed task <name>` with `error`, each a dict with the scalar arguments of the
  run under the names of their parameters. A result whose repr is longer than the limit is logged by its type and
  size. A failure is a warning without the traceback: dramatiq logs the error itself, and a second ERROR record
  would be a second event in Sentry. A `Retry` is not logged as a failure.

## Broker middlewares

### AsyncShutdown

Runs coroutines on the event loop of the worker when the worker shuts down, after the actors have finished:
closing the async clients that live in that loop. Place it after `AsyncIO()`; without the loop it raises
`RuntimeError`.

```python
middleware=[AsyncIO(), ..., AsyncShutdown(kafka_producer_factory.close, redis_client_factory.close)]
```

### HealthCheck

A liveness endpoint for a worker. Every worker process checks itself, all its worker threads are alive and its
event loop answers, and writes the moment to a file; one more process, forked by dramatiq, serves `/livez`,
`/readyz` and `/startupz`: 200 while every worker pinged recently, 503 with the reasons otherwise.

| Environment variable | Default | Meaning |
|---|---|---|
| `DRAMATIQ_HEALTH_PORT` | `9192` | Port of the endpoint |
| `DRAMATIQ_HEALTH_PING_INTERVAL` | `10` | Seconds between the checks of a worker process |
| `DRAMATIQ_HEALTH_STALE_THRESHOLD` | `60` | Seconds after which a ping is stale and the worker unhealthy |

The settings are environment variables because the server is a process of its own that dramatiq starts by the
import path of the function; the built-in `Prometheus` middleware is configured the same way.

### PrometheusMetrics

dramatiq's `Prometheus` middleware plus two metrics. Use it instead of the built-in one.

| Metric | Type | What it counts |
|---|---|---|
| `dramatiq_messages_enqueued_total` | Counter | Messages enqueued, retries excluded |
| `dramatiq_message_queue_time_milliseconds` | Histogram | Time from enqueue to the start of processing, first attempts only, delayed messages excluded |

The metrics exist in worker processes only, where dramatiq boots the middleware: a message enqueued by a web
server or a scheduler is not counted by `dramatiq_messages_enqueued_total`, one enqueued by an actor is. The
queue time is measured for every message, wherever it was enqueued.
