dddramatiq 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dddramatiq/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from . import actor_middlewares, decorators, facade, middlewares
2
+
3
+ __all__ = ('actor_middlewares', 'decorators', 'facade', 'middlewares')
@@ -0,0 +1,6 @@
1
+ from .base import BaseActorMiddleware
2
+ from .log_properties_manager import LogPropertiesManagerMiddleware
3
+ from .sentry_tags import SentryTagsMiddleware
4
+ from .task_logging import TaskLoggingMiddleware
5
+
6
+ __all__ = ('BaseActorMiddleware', 'LogPropertiesManagerMiddleware', 'SentryTagsMiddleware', 'TaskLoggingMiddleware')
@@ -0,0 +1,25 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Awaitable, Callable
3
+ from functools import wraps
4
+ from typing import Any
5
+
6
+
7
+ class BaseActorMiddleware(ABC):
8
+ """
9
+ A layer around every actor of a facade: `__call__` gets the next callable, the actor itself or the middleware
10
+ below, and the arguments the actor was sent. Listed in `BaseDramatiqFacade.actor_middlewares`, the first one
11
+ is the outermost.
12
+ """
13
+
14
+ @abstractmethod
15
+ async def __call__(self, call_next: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> Any: ...
16
+
17
+ def wrap(self, func: Callable[..., Awaitable[Any]]) -> Callable[..., Awaitable[Any]]:
18
+ @wraps(func)
19
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
20
+ return await self(func, *args, **kwargs)
21
+
22
+ return wrapper
23
+
24
+
25
+ __all__ = ('BaseActorMiddleware',)
@@ -0,0 +1,23 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from typing import Any
3
+
4
+ from ddutils.scoped_registry import ScopedRegistry
5
+
6
+ from dddramatiq.actor_middlewares.base import BaseActorMiddleware
7
+
8
+
9
+ class LogPropertiesManagerMiddleware(BaseActorMiddleware):
10
+ """
11
+ Enters the scope of the log properties registry for the run of an actor: the properties are created on enter
12
+ and removed when the run is over, so every log record of the run carries the same ones.
13
+ """
14
+
15
+ def __init__(self, log_properties_registry: ScopedRegistry) -> None:
16
+ self.log_properties_registry = log_properties_registry
17
+
18
+ async def __call__(self, call_next: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> Any:
19
+ async with self.log_properties_registry.scope():
20
+ return await call_next(*args, **kwargs)
21
+
22
+
23
+ __all__ = ('LogPropertiesManagerMiddleware',)
@@ -0,0 +1,33 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from typing import Any
3
+
4
+ import sentry_sdk
5
+ from dddesign.utils.base_model import flatten_model_dump
6
+ from ddutils.annotation_helpers import is_subclass
7
+ from ddutils.scoped_registry import ScopedRegistry
8
+ from pydantic import BaseModel
9
+
10
+ from dddramatiq.actor_middlewares.base import BaseActorMiddleware
11
+
12
+
13
+ class SentryTagsMiddleware(BaseActorMiddleware):
14
+ """
15
+ Tags the Sentry scope of an actor run with the log properties of the run: every field of the model, nested
16
+ ones flattened with dots, `None` left out. List it after `LogPropertiesManagerMiddleware`, which creates them.
17
+ """
18
+
19
+ def __init__(self, log_properties_registry: ScopedRegistry) -> None:
20
+ if not is_subclass(log_properties_registry.generic_type, BaseModel):
21
+ raise TypeError(f'Expected ScopedRegistry[BaseModel], got ScopedRegistry[{log_properties_registry.generic_type}]')
22
+ self.log_properties_registry = log_properties_registry
23
+
24
+ async def __call__(self, call_next: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> Any:
25
+ log_properties = self.log_properties_registry.get()
26
+ if log_properties:
27
+ sentry_scope = sentry_sdk.get_current_scope()
28
+ for key, value in flatten_model_dump(log_properties, mode='json', exclude_none=True).items():
29
+ sentry_scope.set_tag(key, value)
30
+ return await call_next(*args, **kwargs)
31
+
32
+
33
+ __all__ = ('SentryTagsMiddleware',)
@@ -0,0 +1,66 @@
1
+ import inspect
2
+ import logging
3
+ from collections.abc import Awaitable, Callable
4
+ from typing import Any
5
+
6
+ from dramatiq import Retry
7
+
8
+ from dddramatiq.actor_middlewares.base import BaseActorMiddleware
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ DEFAULT_MAX_RESULT_LOG_SIZE = 1000 # characters of the result's repr
13
+
14
+ _COLLECTIONS = (list, tuple, set, dict)
15
+
16
+
17
+ def _get_filtered_params(fn: Callable, args: tuple, kwargs: dict) -> dict:
18
+ """The arguments of a run under the names of the parameters they are bound to, collections left out."""
19
+ try:
20
+ params = inspect.signature(fn).bind_partial(*args, **kwargs).arguments
21
+ return {name: value for name, value in params.items() if not isinstance(value, _COLLECTIONS)}
22
+ except Exception as e: # noqa: BLE001
23
+ logger.error({'message': 'Getting params in dramatiq task failed', 'error': str(e)})
24
+ return {}
25
+
26
+
27
+ class TaskLoggingMiddleware(BaseActorMiddleware):
28
+ """
29
+ Logs the start and the end of every actor run as a dict: `Started task <name>`, then `Finished task <name>`
30
+ with the result when there is one, or `Failed task <name>` with the error. The scalar arguments of the run
31
+ are added to each record under their names; lists, tuples, sets and dicts are left out.
32
+
33
+ A result whose repr is longer than `max_result_log_size` characters is logged by its type and that size.
34
+ A failure is a warning, without the traceback: the error itself is logged by dramatiq, with the traceback,
35
+ and a second ERROR record would be a second event for whatever collects them. A `Retry` is not a failure.
36
+ """
37
+
38
+ def __init__(self, max_result_log_size: int = DEFAULT_MAX_RESULT_LOG_SIZE) -> None:
39
+ self.max_result_log_size = max_result_log_size
40
+
41
+ async def __call__(self, call_next: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> Any:
42
+ task_name = call_next.__name__ # ty: ignore[unresolved-attribute]
43
+ params = _get_filtered_params(call_next, args, kwargs)
44
+
45
+ logger.info({'message': f'Started task {task_name}', **params})
46
+ try:
47
+ result = await call_next(*args, **kwargs)
48
+ except Retry:
49
+ raise
50
+ except Exception as e:
51
+ logger.warning({'message': f'Failed task {task_name}', 'error': repr(e), **params})
52
+ raise
53
+
54
+ logger.info({'message': f'Finished task {task_name}', **self._get_result_log(result), **params})
55
+ return result
56
+
57
+ def _get_result_log(self, result: Any) -> dict:
58
+ if result is None:
59
+ return {}
60
+ size = len(repr(result))
61
+ if size > self.max_result_log_size:
62
+ return {'result': {'type': type(result).__name__, 'size': size}}
63
+ return {'result': result}
64
+
65
+
66
+ __all__ = ('DEFAULT_MAX_RESULT_LOG_SIZE', 'TaskLoggingMiddleware')
@@ -0,0 +1,3 @@
1
+ from .cron_decorator import cron
2
+
3
+ __all__ = ('cron',)
@@ -0,0 +1,21 @@
1
+ CRONTAB_ATTRIBUTE = '__crontab__'
2
+
3
+
4
+ def cron(crontab: str):
5
+ """
6
+ Marks an actor as periodic: `BaseDramatiqFacade.get_cron_jobs()` yields it with this crontab, for a scheduler
7
+ to send it by.
8
+
9
+ @cron('*/1 * * * *')
10
+ @dramatiq.actor
11
+ async def some_cron_task(): ...
12
+ """
13
+
14
+ def decorator(func):
15
+ setattr(func, CRONTAB_ATTRIBUTE, crontab)
16
+ return func
17
+
18
+ return decorator
19
+
20
+
21
+ __all__ = ('CRONTAB_ATTRIBUTE', 'cron')
dddramatiq/facade.py ADDED
@@ -0,0 +1,228 @@
1
+ import glob
2
+ import importlib
3
+ import inspect
4
+ import os
5
+ from abc import ABC
6
+ from collections.abc import Generator
7
+ from dataclasses import dataclass
8
+ from datetime import timedelta
9
+ from json import dumps, loads
10
+ from typing import Any, ClassVar
11
+
12
+ from ddutils.convertors import convert_timedelta_to_milliseconds
13
+ from dramatiq import Broker, Message, get_broker
14
+ from dramatiq.asyncio import async_to_sync
15
+
16
+ from dddramatiq.actor_middlewares.base import BaseActorMiddleware
17
+ from dddramatiq.decorators.cron_decorator import CRONTAB_ATTRIBUTE
18
+
19
+ # Set on an actor a facade has wrapped in its middlewares, so no facade wraps it again
20
+ WRAPPED_ATTRIBUTE = '__dddramatiq_wrapped__'
21
+
22
+
23
+ @dataclass
24
+ class JsonMessageArgsSerializer:
25
+ args: tuple[Any, ...] | None = None
26
+ kwargs: dict[str, Any] | None = None
27
+
28
+ @property
29
+ def serialized_args(self) -> tuple[Any, ...]:
30
+ return tuple(loads(dumps(self.args))) if self.args else ()
31
+
32
+ @property
33
+ def serialized_kwargs(self) -> dict[str, Any]:
34
+ return loads(dumps(self.kwargs)) if self.kwargs else {}
35
+
36
+
37
+ class BaseDramatiqFacade(ABC):
38
+ """
39
+ Base facade for discovering and interacting with Dramatiq tasks.
40
+
41
+ This facade is broker-independent and uses `dramatiq.get_broker()` to get
42
+ the currently configured broker. Make sure the broker is initialized before
43
+ using this facade.
44
+
45
+ Class Attributes:
46
+ base_dir: Base directory for scanning task modules.
47
+ module_pattern: Module pattern with optional * wildcards.
48
+ Examples:
49
+ - 'app.*.infrastructure.ports.tasks' (single wildcard)
50
+ - 'app.*.*.tasks' (multiple wildcards)
51
+ - 'app.context.tasks' (no wildcards)
52
+ actor_middlewares: Tuple of BaseActorMiddleware instances to wrap each actor.
53
+ Applied in order (first middleware is outermost).
54
+
55
+ Example:
56
+ # config/entrypoints/dramatiq/config.py - declared only, so importing it pulls no task module in
57
+ from dddramatiq.facade import BaseDramatiqFacade
58
+ from config.settings import settings
59
+
60
+ class DramatiqFacade(BaseDramatiqFacade):
61
+ base_dir = settings.ROOT_DIR
62
+ module_pattern = 'app.*.infrastructure.ports.tasks'
63
+ actor_middlewares = (MyMiddleware(),)
64
+
65
+ dramatiq_facade_impl = DramatiqFacade()
66
+
67
+ # config/entrypoints/dramatiq/startup.py - what a process runs on start
68
+ from config.entrypoints.dramatiq.config import dramatiq_facade_impl
69
+ dramatiq_facade_impl.setup_tasks()
70
+
71
+ # Usage in other modules
72
+ from config.entrypoints.dramatiq.config import dramatiq_facade_impl
73
+
74
+ dramatiq_facade_impl.send_task('my_task', arg1='value')
75
+ dramatiq_facade_impl.send_task('my_task', arg1='value', delay=timedelta(minutes=5))
76
+ """
77
+
78
+ base_dir: ClassVar[str]
79
+ module_pattern: ClassVar[str]
80
+ actor_middlewares: ClassVar[tuple[BaseActorMiddleware, ...]] = ()
81
+
82
+ _is_setup: bool = False
83
+
84
+ def __init_subclass__(cls, **kwargs):
85
+ super().__init_subclass__(**kwargs)
86
+
87
+ if not getattr(cls, 'base_dir', None):
88
+ raise ValueError('`base_dir` class attribute must be set')
89
+
90
+ if not getattr(cls, 'module_pattern', None):
91
+ raise ValueError('`module_pattern` class attribute must be set')
92
+
93
+ def get_tasks_modules(self) -> Generator[str]:
94
+ """
95
+ Scan directories and yield task module paths based on the pattern.
96
+
97
+ Supports glob wildcards (*) in the pattern.
98
+ Example: 'app.*.infrastructure.ports.tasks' or 'app.context.tasks'
99
+
100
+ Yields:
101
+ Module paths match the pattern.
102
+ """
103
+ pattern_path = self.module_pattern.replace('.', os.sep)
104
+ search_pattern = os.path.join(self.base_dir, pattern_path, '__init__.py')
105
+
106
+ for init_file in glob.glob(search_pattern):
107
+ module_dir = os.path.dirname(init_file)
108
+ rel_path = os.path.relpath(module_dir, self.base_dir)
109
+ module_name = rel_path.replace(os.sep, '.')
110
+ yield module_name
111
+
112
+ def setup_tasks(self):
113
+ """
114
+ Discover, import, and prepare all task modules for execution.
115
+
116
+ This method:
117
+ 1. Scans directories for task modules based on the configured pattern
118
+ 2. Imports all found modules to register actors
119
+ 3. Wraps every actor of the broker in the actor middlewares
120
+
121
+ Actors are async functions: a sync one raises `TypeError`. An actor is wrapped once, by the facade that
122
+ set it up first; another facade on the same broker leaves it as it is.
123
+ """
124
+ if self._is_setup:
125
+ return
126
+
127
+ for module_name in self.get_tasks_modules():
128
+ importlib.import_module(module_name)
129
+
130
+ for actor in get_broker().actors.values():
131
+ if getattr(actor, WRAPPED_ATTRIBUTE, False):
132
+ continue
133
+ # dramatiq keeps the coroutine function of an async actor behind its sync wrapper
134
+ fn = getattr(actor.fn, '__wrapped__', None)
135
+ if not inspect.iscoroutinefunction(fn):
136
+ raise TypeError(f"Actor '{actor.actor_name}' must be an async function")
137
+ for middleware in reversed(self.actor_middlewares):
138
+ fn = middleware.wrap(fn)
139
+ actor.fn = async_to_sync(fn)
140
+ setattr(actor, WRAPPED_ATTRIBUTE, True)
141
+
142
+ self._is_setup = True
143
+
144
+ def send_task(self, task_name: str, *args: Any, delay: int | timedelta | None = None, **kwargs: Any) -> None:
145
+ """
146
+ Send a task to the broker queue.
147
+
148
+ Args:
149
+ task_name: Name of the registered actor/task.
150
+ *args: Positional arguments for the task.
151
+ delay: Optional delay before task execution (int in ms or timedelta). Keyword only: everything
152
+ positional after the name goes to the task.
153
+ **kwargs: Keyword arguments for the task.
154
+ """
155
+ actor = self.broker.get_actor(task_name)
156
+
157
+ if isinstance(delay, timedelta):
158
+ delay = convert_timedelta_to_milliseconds(delay)
159
+
160
+ if not delay:
161
+ delay = None
162
+
163
+ options = {}
164
+ if actor.options:
165
+ options.update(actor.options)
166
+
167
+ if actor.priority:
168
+ options['priority'] = actor.priority
169
+
170
+ serializer = JsonMessageArgsSerializer(args=args, kwargs=kwargs)
171
+
172
+ message: Message = Message(
173
+ queue_name=actor.queue_name,
174
+ actor_name=task_name,
175
+ args=serializer.serialized_args,
176
+ kwargs=serializer.serialized_kwargs,
177
+ options=options,
178
+ )
179
+ self.broker.enqueue(message=message, delay=delay)
180
+
181
+ def run_task_sync(self, task_name: str, *args: Any, **kwargs: Any) -> Any:
182
+ """
183
+ Run a task synchronously without sending to the broker.
184
+
185
+ Args:
186
+ task_name: Name of the registered actor/task.
187
+ *args: Positional arguments for the task.
188
+ **kwargs: Keyword arguments for the task.
189
+
190
+ Returns:
191
+ Task result.
192
+ """
193
+ actor = self.broker.get_actor(task_name)
194
+
195
+ serializer = JsonMessageArgsSerializer(args=args, kwargs=kwargs)
196
+
197
+ return actor(*serializer.serialized_args, **serializer.serialized_kwargs)
198
+
199
+ def get_cron_jobs(self) -> Generator[tuple[str, str, str]]:
200
+ """
201
+ Yield cron job configurations for actors with @cron decorator.
202
+
203
+ Yields:
204
+ Tuples of (job_path, crontab, job_name) for each cron actor.
205
+ """
206
+ for actor in self.broker.actors.values():
207
+ if hasattr(actor, CRONTAB_ATTRIBUTE):
208
+ crontab = getattr(actor, CRONTAB_ATTRIBUTE)
209
+ module_path = actor.fn.__module__
210
+ func_name = actor.fn.__name__ # ty: ignore[unresolved-attribute]
211
+
212
+ yield (
213
+ f'{module_path}:{func_name}.send', # job_path
214
+ crontab, # crontab expression
215
+ f'{module_path}.{func_name}', # job_name
216
+ )
217
+
218
+ @property
219
+ def broker(self) -> Broker:
220
+ # A process that never ran `setup_tasks()` (a script, a test) gets the task sweep on
221
+ # first use rather than an error: the actors have to be registered to be sent to.
222
+ if not self._is_setup:
223
+ self.setup_tasks()
224
+
225
+ return get_broker()
226
+
227
+
228
+ __all__ = ('BaseDramatiqFacade', 'JsonMessageArgsSerializer')
@@ -0,0 +1,5 @@
1
+ from .async_shutdown import AsyncShutdown
2
+ from .health_check import HealthCheck
3
+ from .prometheus import PrometheusMetrics
4
+
5
+ __all__ = ('AsyncShutdown', 'HealthCheck', 'PrometheusMetrics')
@@ -0,0 +1,31 @@
1
+ from collections.abc import Awaitable, Callable
2
+
3
+ from dramatiq.asyncio import get_event_loop_thread
4
+ from dramatiq.middleware import Middleware
5
+
6
+
7
+ class AsyncShutdown(Middleware):
8
+ """
9
+ Runs coroutines on the worker's event loop when the worker shuts down, after the actors
10
+ have finished: closing async clients that live in that loop (a Kafka producer that still
11
+ holds a buffer, a connection pool).
12
+
13
+ Place it after `AsyncIO()` in the broker's middleware list: dramatiq emits `after_worker_shutdown`
14
+ in reverse order, so this hook runs while the loop thread `AsyncIO` manages is still alive.
15
+
16
+ Example:
17
+ middleware=[AsyncIO(), ..., AsyncShutdown(kafka_producer_factory.close, redis_client_factory.close)]
18
+ """
19
+
20
+ def __init__(self, *hooks: Callable[[], Awaitable[None]]) -> None:
21
+ self.hooks = hooks
22
+
23
+ def after_worker_shutdown(self, broker, worker): # noqa: ARG002
24
+ event_loop_thread = get_event_loop_thread()
25
+ if event_loop_thread is None: # `AsyncIO` is not in the list or has already stopped the loop
26
+ raise RuntimeError('AsyncShutdown must be placed after AsyncIO in the broker middleware')
27
+ for hook in self.hooks:
28
+ event_loop_thread.run_coroutine(hook())
29
+
30
+
31
+ __all__ = ('AsyncShutdown',)
@@ -0,0 +1,173 @@
1
+ import asyncio
2
+ import contextlib
3
+ import glob
4
+ import json
5
+ import os
6
+ import tempfile
7
+ import time
8
+ from http.server import BaseHTTPRequestHandler, HTTPServer
9
+ from threading import Event, Thread
10
+
11
+ from dramatiq.asyncio import get_event_loop_thread
12
+ from dramatiq.logging import get_logger
13
+ from dramatiq.middleware import Middleware
14
+
15
+ HEALTH_DIR = os.path.join(tempfile.gettempdir(), 'dramatiq-health')
16
+ HEALTH_PORT = int(os.getenv('DRAMATIQ_HEALTH_PORT', '9192'))
17
+ HEALTH_PING_INTERVAL = int(os.getenv('DRAMATIQ_HEALTH_PING_INTERVAL', '10'))
18
+ HEALTH_STALE_THRESHOLD = int(os.getenv('DRAMATIQ_HEALTH_STALE_THRESHOLD', '60'))
19
+
20
+ _shutting_down = Event()
21
+
22
+
23
+ class HealthCheck(Middleware):
24
+ """
25
+ A liveness endpoint for a worker. Every worker process checks itself every `DRAMATIQ_HEALTH_PING_INTERVAL`
26
+ seconds (10): all its worker threads are alive and its event loop answers; a process that passes writes the
27
+ moment to a file. One more process, forked by dramatiq, serves `/livez`, `/readyz` and `/startupz` on port
28
+ `DRAMATIQ_HEALTH_PORT` (9192): 200 while every worker file is fresher than `DRAMATIQ_HEALTH_STALE_THRESHOLD`
29
+ seconds (60), 503 with the reasons otherwise.
30
+
31
+ The settings are environment variables, read on import: the server runs in a process of its own that
32
+ dramatiq starts by the import path of the function, so nothing set on the instance would reach it. The
33
+ built-in `Prometheus` middleware is configured the same way.
34
+ """
35
+
36
+ def after_worker_boot(self, broker, worker): # noqa: ARG002
37
+ os.makedirs(HEALTH_DIR, exist_ok=True)
38
+ pid = os.getpid()
39
+ thread = Thread(target=_health_pinger, args=(pid, worker), daemon=True)
40
+ thread.start()
41
+
42
+ def before_worker_shutdown(self, broker, worker): # noqa: ARG002
43
+ _shutting_down.set()
44
+
45
+ def after_worker_shutdown(self, broker, worker): # noqa: ARG002
46
+ pid = os.getpid()
47
+ path = os.path.join(HEALTH_DIR, f'worker-{pid}')
48
+ with contextlib.suppress(OSError):
49
+ os.remove(path)
50
+
51
+ @property
52
+ def forks(self):
53
+ return [_run_health_server]
54
+
55
+
56
+ async def _ping():
57
+ return True
58
+
59
+
60
+ def _health_pinger(pid: int, worker):
61
+ logger = get_logger(__name__, f'HealthPinger({pid})')
62
+ path = os.path.join(HEALTH_DIR, f'worker-{pid}')
63
+ tmp_path = os.path.join(HEALTH_DIR, f'.worker-{pid}.tmp')
64
+
65
+ # `wait` returns True when shutdown is signalled, so we exit before logging dead threads torn down by SIGTERM.
66
+ while not _shutting_down.wait(HEALTH_PING_INTERVAL):
67
+ # Check 1: all WorkerThreads alive
68
+ dead_threads = [t for t in worker.workers if not t.is_alive()]
69
+ if dead_threads:
70
+ logger.warning(f'Dead worker threads detected: {len(dead_threads)}/{len(worker.workers)} for worker {pid}')
71
+ continue
72
+
73
+ # Check 2: event loop responsive
74
+ event_loop_thread = get_event_loop_thread()
75
+ if event_loop_thread is None:
76
+ continue
77
+
78
+ try:
79
+ future = asyncio.run_coroutine_threadsafe(_ping(), event_loop_thread.loop)
80
+ future.result(timeout=HEALTH_PING_INTERVAL)
81
+ except (TimeoutError, RuntimeError):
82
+ logger.warning(f'Event loop ping failed for worker {pid}')
83
+ continue
84
+
85
+ # Both checks passed. The ping is replaced in one step: the server never reads a half-written file
86
+ with open(tmp_path, 'w') as f:
87
+ f.write(str(time.time()))
88
+ os.replace(tmp_path, path)
89
+
90
+
91
+ def _cleanup_stale_files():
92
+ """Remove stale worker files left by previously crashed containers."""
93
+ now = time.time()
94
+ removed = []
95
+ for path in glob.glob(os.path.join(HEALTH_DIR, 'worker-*')):
96
+ try:
97
+ with open(path) as f:
98
+ last_ping = float(f.read().strip())
99
+ if now - last_ping > HEALTH_STALE_THRESHOLD:
100
+ os.remove(path)
101
+ removed.append(os.path.basename(path))
102
+ except (ValueError, OSError):
103
+ os.remove(path)
104
+ removed.append(os.path.basename(path))
105
+ return removed
106
+
107
+
108
+ def _check_health():
109
+ worker_files = glob.glob(os.path.join(HEALTH_DIR, 'worker-*'))
110
+ if not worker_files:
111
+ return False, {'status': 'unhealthy', 'errors': ['no worker files found'], 'workers': {}}
112
+
113
+ now = time.time()
114
+ errors = []
115
+ workers = {}
116
+
117
+ for path in worker_files:
118
+ worker_name = os.path.basename(path)
119
+ try:
120
+ with open(path) as f:
121
+ last_ping = float(f.read().strip())
122
+ age = int(now - last_ping)
123
+ healthy = age <= HEALTH_STALE_THRESHOLD
124
+ workers[worker_name] = {'last_ping_age_s': age, 'healthy': healthy}
125
+ if not healthy:
126
+ errors.append(f'{worker_name}: stale ({age}s)')
127
+ except (ValueError, OSError):
128
+ workers[worker_name] = {'healthy': False, 'error': 'unreadable'}
129
+ errors.append(f'{worker_name}: unreadable')
130
+
131
+ status = 'healthy' if not errors else 'unhealthy'
132
+ return not errors, {'status': status, 'errors': errors, 'workers': workers}
133
+
134
+
135
+ class _HealthHandler(BaseHTTPRequestHandler):
136
+ def do_GET(self): # noqa: N802
137
+ if self.path in ('/livez', '/readyz', '/startupz'):
138
+ ok, result = _check_health()
139
+ else:
140
+ self.send_response(404)
141
+ self.end_headers()
142
+ return
143
+
144
+ status = 200 if ok else 503
145
+ body = json.dumps(result).encode()
146
+ self.send_response(status)
147
+ self.send_header('content-type', 'application/json')
148
+ self.end_headers()
149
+ self.wfile.write(body)
150
+
151
+ def log_message(self, fmt, *args): # type: ignore[invalid-method-override]
152
+ logger = get_logger(__name__, type(self))
153
+ logger.debug(fmt, *args)
154
+
155
+
156
+ def _run_health_server():
157
+ logger = get_logger(__name__, '_run_health_server')
158
+
159
+ os.makedirs(HEALTH_DIR, exist_ok=True)
160
+ removed = _cleanup_stale_files()
161
+ if removed:
162
+ logger.info(f'Cleaned up stale worker files: {removed}')
163
+
164
+ logger.info(f'Starting health check server on port {HEALTH_PORT}...')
165
+ try:
166
+ httpd = HTTPServer(('0.0.0.0', HEALTH_PORT), _HealthHandler)
167
+ httpd.serve_forever()
168
+ except KeyboardInterrupt:
169
+ httpd.shutdown()
170
+ return 0
171
+
172
+
173
+ __all__ = ('HEALTH_DIR', 'HEALTH_PING_INTERVAL', 'HEALTH_PORT', 'HEALTH_STALE_THRESHOLD', 'HealthCheck')
@@ -0,0 +1,62 @@
1
+ from dramatiq.common import current_millis
2
+ from dramatiq.middleware.prometheus import Prometheus
3
+
4
+ _QUEUE_TIME_BUCKETS = (100, 500, 1_000, 5_000, 10_000, 30_000, 60_000, 300_000, float('inf'))
5
+
6
+
7
+ class PrometheusMetrics(Prometheus):
8
+ """
9
+ Extends the built-in Dramatiq Prometheus middleware with additional metrics.
10
+
11
+ Adds:
12
+ - dramatiq_messages_enqueued_total: counter of messages enqueued (retries excluded).
13
+ - dramatiq_message_queue_time_milliseconds: histogram of time from enqueue to
14
+ processing start (retries and delayed messages excluded).
15
+ """
16
+
17
+ def after_process_boot(self, broker):
18
+ super().after_process_boot(broker)
19
+
20
+ import prometheus_client as prom
21
+
22
+ registry = prom.CollectorRegistry()
23
+
24
+ self.messages_enqueued = prom.Counter(
25
+ 'dramatiq_messages_enqueued_total',
26
+ 'Total number of messages enqueued, excluding retries.',
27
+ ['queue_name', 'actor_name'],
28
+ registry=registry,
29
+ )
30
+ self.queue_time = prom.Histogram(
31
+ 'dramatiq_message_queue_time_milliseconds',
32
+ 'Time between message enqueue and processing start in milliseconds, for first attempts only.',
33
+ ['queue_name', 'actor_name'],
34
+ buckets=_QUEUE_TIME_BUCKETS,
35
+ registry=registry,
36
+ )
37
+
38
+ def after_enqueue(self, broker, message, delay):
39
+ super().after_enqueue(broker, message, delay)
40
+
41
+ counter = getattr(self, 'messages_enqueued', None)
42
+ if counter is None:
43
+ return
44
+ if 'retries' in message.options:
45
+ return
46
+ counter.labels(queue_name=message.queue_name, actor_name=message.actor_name).inc()
47
+
48
+ def before_process_message(self, broker, message):
49
+ super().before_process_message(broker, message)
50
+
51
+ histogram = getattr(self, 'queue_time', None)
52
+ if histogram is None:
53
+ return
54
+ if 'retries' in message.options:
55
+ return
56
+ if 'eta' in message.options:
57
+ return
58
+ queue_time_ms = max(0, current_millis() - message.message_timestamp)
59
+ histogram.labels(queue_name=message.queue_name, actor_name=message.actor_name).observe(queue_time_ms)
60
+
61
+
62
+ __all__ = ('PrometheusMetrics',)
dddramatiq/py.typed ADDED
File without changes
@@ -0,0 +1,231 @@
1
+ Metadata-Version: 2.4
2
+ Name: dddramatiq
3
+ Version: 0.0.1
4
+ Summary: Dramatiq helpers: a task facade with actor middlewares, cron tasks and broker middlewares for health checks, metrics and async shutdown
5
+ Keywords: python,dddramatiq,dramatiq,asyncio,background tasks,task queue,worker,cron,health check,prometheus,middleware,sentry
6
+ Author: davyddd
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: dddesign>=2.1.2,<3
17
+ Requires-Dist: ddutils>=0.4.0,<0.5.0
18
+ Requires-Dist: dramatiq>=2.0,<2.3
19
+ Requires-Dist: prometheus-client>=0.20,<1
20
+ Requires-Dist: pydantic>=2.1,<3
21
+ Requires-Dist: sentry-sdk>=2.12,<4
22
+ Requires-Python: >=3.11, <3.16
23
+ Project-URL: Repository, https://github.com/davyddd/dddramatiq
24
+ Description-Content-Type: text/markdown
25
+
26
+ # dddramatiq
27
+
28
+ [![pypi](https://img.shields.io/pypi/v/dddramatiq.svg)](https://pypi.python.org/pypi/dddramatiq)
29
+ [![downloads](https://static.pepy.tech/badge/dddramatiq/month)](https://pepy.tech/project/dddramatiq)
30
+ [![versions](https://img.shields.io/pypi/pyversions/dddramatiq.svg)](https://github.com/davyddd/dddramatiq)
31
+ [![codecov](https://codecov.io/gh/davyddd/dddramatiq/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/dddramatiq)
32
+ [![license](https://img.shields.io/github/license/davyddd/dddramatiq.svg)](https://github.com/davyddd/dddramatiq/blob/main/LICENSE)
33
+
34
+ Dramatiq helpers: a task facade with actor middlewares, cron tasks and broker middlewares for health checks, metrics and async shutdown
35
+
36
+ ## Installation
37
+
38
+ Install the library using pip:
39
+ ```bash
40
+ pip install dddramatiq
41
+ ```
42
+
43
+ ## Development
44
+
45
+ The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:
46
+
47
+ ```bash
48
+ fab build # build the dev image
49
+ fab tests # run pytest
50
+ fab linters # run ruff (with --fix), ty and complexipy
51
+ fab shell # IPython inside the container
52
+ fab bash # bash inside the container
53
+ ```
54
+
55
+ This project was generated from [dd-lib-stub](https://github.com/davyddd/dd-lib-stub);
56
+ run `uvx copier update` to pull in template updates.
57
+
58
+ ## Compatibility
59
+
60
+ Python 3.11 to 3.15. What changed in each release, breaking changes included,
61
+ is in the [GitHub releases](https://github.com/davyddd/dddramatiq/releases).
62
+
63
+ <!-- The sections below are the library's own; copier update leaves them alone -->
64
+
65
+ Depends on `dramatiq>=2.0,<2.3`, `prometheus-client>=0.20,<1`, `sentry-sdk>=2.12,<4`, `dddesign>=2.1.2,<3`,
66
+ `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
67
+ needed.
68
+
69
+ | Package | What is in it |
70
+ |---|---|
71
+ | `dddramatiq.facade` | `BaseDramatiqFacade`: finds the task modules, wraps the actors, sends tasks, lists the cron jobs |
72
+ | `dddramatiq.actor_middlewares` | Layers around every actor: log properties, Sentry tags, start and finish logs |
73
+ | `dddramatiq.decorators` | `cron`, the mark of a periodic actor |
74
+ | `dddramatiq.middlewares` | Broker middlewares: `AsyncShutdown`, `HealthCheck`, `PrometheusMetrics` |
75
+
76
+ Actors are async functions. dramatiq runs them on one event loop per worker process, the thread its `AsyncIO`
77
+ middleware manages, so `AsyncIO()` must be in the broker's middleware list.
78
+
79
+ ## Facade
80
+
81
+ One facade per application is the door to its tasks. A subclass says where the task modules are; the instance
82
+ imports them, wraps every actor in the actor middlewares and sends tasks by name, so the code that enqueues a
83
+ task never imports the module that defines it.
84
+
85
+ ```python
86
+ import dramatiq
87
+ from dramatiq.brokers.redis import RedisBroker
88
+ from dramatiq.middleware import AsyncIO
89
+
90
+ from dddramatiq.actor_middlewares import LogPropertiesManagerMiddleware, SentryTagsMiddleware, TaskLoggingMiddleware
91
+ from dddramatiq.facade import BaseDramatiqFacade
92
+ from dddramatiq.middlewares import AsyncShutdown, HealthCheck, PrometheusMetrics
93
+
94
+ broker = RedisBroker(
95
+ url='redis://localhost/0',
96
+ middleware=[AsyncIO(), PrometheusMetrics(), HealthCheck(), AsyncShutdown(close_connections)],
97
+ )
98
+ dramatiq.set_broker(broker)
99
+
100
+
101
+ class DramatiqFacade(BaseDramatiqFacade):
102
+ base_dir = '/app/src' # where the pattern is looked up
103
+ module_pattern = 'app.*.infrastructure.ports.tasks' # dotted, `*` for one package
104
+ actor_middlewares = ( # the first one is the outermost
105
+ LogPropertiesManagerMiddleware(log_properties_registry),
106
+ SentryTagsMiddleware(log_properties_registry),
107
+ TaskLoggingMiddleware(),
108
+ )
109
+
110
+
111
+ dramatiq_facade_impl = DramatiqFacade()
112
+ ```
113
+
114
+ ```python
115
+ # app/order_context/infrastructure/ports/tasks/__init__.py
116
+ import dramatiq
117
+
118
+ from dddramatiq.decorators import cron
119
+
120
+
121
+ @dramatiq.actor(queue_name='orders', max_retries=3)
122
+ async def order_create_task(order_id: int) -> None: ...
123
+
124
+
125
+ @cron('*/5 * * * *')
126
+ @dramatiq.actor
127
+ async def order_expire_periodic_task() -> None: ...
128
+ ```
129
+
130
+ | Method | What it does |
131
+ |---|---|
132
+ | `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 |
133
+ | `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 |
134
+ | `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` |
135
+ | `get_cron_jobs()` | Yields `(job_path, crontab, job_name)` for every actor marked with `@cron` |
136
+ | `broker` | The global broker, `dramatiq.get_broker()` |
137
+
138
+ - The arguments of a task are passed through JSON before they are sent or run, so an actor always gets what a
139
+ real broker would deliver: a tuple arrives as a list, and a value JSON cannot carry raises `TypeError`.
140
+ - A process that never called `setup_tasks()`, a script or a test, gets it on the first `send_task`,
141
+ `run_task_sync` or `get_cron_jobs`.
142
+ - Actors are async functions: a sync actor on the broker makes `setup_tasks()` raise `TypeError` with its name.
143
+ An actor is wrapped once, by the facade that set it up first.
144
+ - Declare the facade in a module that imports no task: importing it costs nothing, and the tasks are imported
145
+ when the process sets them up.
146
+
147
+ ```python
148
+ dramatiq_facade_impl.send_task('order_create_task', order_id)
149
+ dramatiq_facade_impl.send_task('order_create_task', order_id=order_id, delay=timedelta(minutes=5))
150
+ ```
151
+
152
+ A scheduler turns the cron jobs into triggers. With APScheduler:
153
+
154
+ ```python
155
+ from apscheduler.schedulers.blocking import BlockingScheduler
156
+ from apscheduler.triggers.cron import CronTrigger
157
+
158
+ scheduler = BlockingScheduler()
159
+ dramatiq_facade_impl.setup_tasks()
160
+ for job_path, crontab, job_name in dramatiq_facade_impl.get_cron_jobs():
161
+ scheduler.add_job(job_path, trigger=CronTrigger.from_crontab(crontab, timezone='UTC'), name=job_name)
162
+ ```
163
+
164
+ ## Actor middlewares
165
+
166
+ A `BaseActorMiddleware` is a layer around the coroutine of every actor: `__call__(call_next, *args, **kwargs)`
167
+ gets the next layer and the arguments of the run.
168
+
169
+ ```python
170
+ from dddramatiq.actor_middlewares import BaseActorMiddleware
171
+
172
+
173
+ class TimingMiddleware(BaseActorMiddleware):
174
+ async def __call__(self, call_next, *args, **kwargs):
175
+ started = time.monotonic()
176
+ try:
177
+ return await call_next(*args, **kwargs)
178
+ finally:
179
+ logger.info({'message': 'Task took', 'seconds': time.monotonic() - started})
180
+ ```
181
+
182
+ - `LogPropertiesManagerMiddleware(log_properties_registry)` enters the scope of a `ScopedRegistry` from
183
+ [ddutils](https://github.com/davyddd/ddutils) for the run: the log properties are created on enter and removed
184
+ when the run is over, failed or not. The registry and its model are the application's.
185
+ - `SentryTagsMiddleware(log_properties_registry)` tags the Sentry scope of the run with the properties, nested
186
+ fields flattened with dots, `None` left out. The registry must hold a pydantic model. List it after the manager.
187
+ - `TaskLoggingMiddleware(max_result_log_size=1000)` logs `Started task <name>`, then `Finished task <name>` with
188
+ `result` when there is one, or `Failed task <name>` with `error`, each a dict with the scalar arguments of the
189
+ run under the names of their parameters. A result whose repr is longer than the limit is logged by its type and
190
+ size. A failure is a warning without the traceback: dramatiq logs the error itself, and a second ERROR record
191
+ would be a second event in Sentry. A `Retry` is not logged as a failure.
192
+
193
+ ## Broker middlewares
194
+
195
+ ### AsyncShutdown
196
+
197
+ Runs coroutines on the event loop of the worker when the worker shuts down, after the actors have finished:
198
+ closing the async clients that live in that loop. Place it after `AsyncIO()`; without the loop it raises
199
+ `RuntimeError`.
200
+
201
+ ```python
202
+ middleware=[AsyncIO(), ..., AsyncShutdown(kafka_producer_factory.close, redis_client_factory.close)]
203
+ ```
204
+
205
+ ### HealthCheck
206
+
207
+ A liveness endpoint for a worker. Every worker process checks itself, all its worker threads are alive and its
208
+ event loop answers, and writes the moment to a file; one more process, forked by dramatiq, serves `/livez`,
209
+ `/readyz` and `/startupz`: 200 while every worker pinged recently, 503 with the reasons otherwise.
210
+
211
+ | Environment variable | Default | Meaning |
212
+ |---|---|---|
213
+ | `DRAMATIQ_HEALTH_PORT` | `9192` | Port of the endpoint |
214
+ | `DRAMATIQ_HEALTH_PING_INTERVAL` | `10` | Seconds between the checks of a worker process |
215
+ | `DRAMATIQ_HEALTH_STALE_THRESHOLD` | `60` | Seconds after which a ping is stale and the worker unhealthy |
216
+
217
+ The settings are environment variables because the server is a process of its own that dramatiq starts by the
218
+ import path of the function; the built-in `Prometheus` middleware is configured the same way.
219
+
220
+ ### PrometheusMetrics
221
+
222
+ dramatiq's `Prometheus` middleware plus two metrics. Use it instead of the built-in one.
223
+
224
+ | Metric | Type | What it counts |
225
+ |---|---|---|
226
+ | `dramatiq_messages_enqueued_total` | Counter | Messages enqueued, retries excluded |
227
+ | `dramatiq_message_queue_time_milliseconds` | Histogram | Time from enqueue to the start of processing, first attempts only, delayed messages excluded |
228
+
229
+ The metrics exist in worker processes only, where dramatiq boots the middleware: a message enqueued by a web
230
+ server or a scheduler is not counted by `dramatiq_messages_enqueued_total`, one enqueued by an actor is. The
231
+ queue time is measured for every message, wherever it was enqueued.
@@ -0,0 +1,18 @@
1
+ dddramatiq/__init__.py,sha256=NXk5ijiO47_rZb7LNeqNKinwbRPl9VaQItxiQVhqE7Y,137
2
+ dddramatiq/actor_middlewares/__init__.py,sha256=xPnkQ0a3WtwIuzN2dTYD8kSa_b-Yed5bjdguL12Bw6M,317
3
+ dddramatiq/actor_middlewares/base.py,sha256=YvG55WaDoNmSnVZgE2Trwm7x9K_jF2gkq9PZcpSgrhQ,852
4
+ dddramatiq/actor_middlewares/log_properties_manager.py,sha256=GN9XLdzq948LxqSPkAnxY4G0Q8MhL7F1ieDJ_KK2Kpo,873
5
+ dddramatiq/actor_middlewares/sentry_tags.py,sha256=pEyPd99Wl4Kwwv31rTnFY2p5ngEplV-UF3a8hQ3oHnM,1474
6
+ dddramatiq/actor_middlewares/task_logging.py,sha256=hDjmimDHidVfhLI22pYEab7Dihh1ArojTmthXyvJYZQ,2790
7
+ dddramatiq/decorators/__init__.py,sha256=N4oRX8ddg-sugaoIPD48sGwZMT5UgJzP99fQmDnJ0VI,54
8
+ dddramatiq/decorators/cron_decorator.py,sha256=81YDx6K7a-M2H4MmbFWWQQUzPz00fn2ASmqiU2s7CKI,463
9
+ dddramatiq/facade.py,sha256=zyVUBC1K7B80eGe6ZHyUotgnQy6gXt-7TGq-E2qxpJ0,8398
10
+ dddramatiq/middlewares/__init__.py,sha256=v_gTBT4sjaSw4RQg5wPSJ755yKvY4lAOneFlBHaA_AA,187
11
+ dddramatiq/middlewares/async_shutdown.py,sha256=oa9vSGkr63O2TCcU2O_Q7VJ1krVCcEALL19eEa8JUvo,1282
12
+ dddramatiq/middlewares/health_check.py,sha256=kaTb2Kt6rXetk3nZ39_hpJfmZBTMIHDreokCXTf8DvA,6359
13
+ dddramatiq/middlewares/prometheus.py,sha256=UReg1Ff1aAjvvvY8EAmBcCzo3sXK04tPIzbYsv56i5c,2244
14
+ dddramatiq/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ dddramatiq-0.0.1.dist-info/licenses/LICENSE,sha256=_DkcY418J4TyqQWxa0QjLzg1jCl1NiR-XE_UyK-Rv6g,1070
16
+ dddramatiq-0.0.1.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
17
+ dddramatiq-0.0.1.dist-info/METADATA,sha256=H4aOw5rFmkN8j5tiLBbD9sCeWYnsnwkXjvxh-r1mEPI,10857
18
+ dddramatiq-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Artem Davydov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.