|
| 1 | +"""Celery integration. Requires the ``celery`` extra: |
| 2 | +
|
| 3 | + pip install "babelqueue[celery]" |
| 4 | +
|
| 5 | +A Celery app already configures a broker (Redis/RabbitMQ). :func:`from_celery` |
| 6 | +builds a :class:`~babelqueue.BabelQueue` runtime on that *same* broker, so a |
| 7 | +Celery-based service produces and consumes the canonical polyglot envelope |
| 8 | +alongside its Celery tasks — interoperating with the PHP/Laravel, Go, Node, ... |
| 9 | +SDKs. :func:`install_worker` runs that consumer as a Celery worker *bootstep* (a |
| 10 | +daemon thread started on ``celery worker``), so one process handles both Celery |
| 11 | +tasks and inbound polyglot messages. |
| 12 | +
|
| 13 | +``celery`` is imported lazily, so the core stays dependency-free. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import threading |
| 19 | +from typing import Any, Optional |
| 20 | + |
| 21 | +from .app import BabelQueue |
| 22 | +from .exceptions import BabelQueueError |
| 23 | + |
| 24 | + |
| 25 | +def broker_url(celery_app: Any) -> str: |
| 26 | + """Extract the broker URL from a Celery app (supports old/new config keys).""" |
| 27 | + conf = getattr(celery_app, "conf", None) |
| 28 | + url = None |
| 29 | + if conf is not None: |
| 30 | + url = getattr(conf, "broker_url", None) |
| 31 | + if not url and hasattr(conf, "get"): |
| 32 | + url = conf.get("broker_url") or conf.get("BROKER_URL") |
| 33 | + if not url: |
| 34 | + raise BabelQueueError( |
| 35 | + "The Celery app has no broker configured; set broker_url before calling from_celery()." |
| 36 | + ) |
| 37 | + return str(url) |
| 38 | + |
| 39 | + |
| 40 | +def from_celery(celery_app: Any, **kwargs: Any) -> BabelQueue: |
| 41 | + """Build a :class:`~babelqueue.BabelQueue` runtime on the Celery app's broker. |
| 42 | +
|
| 43 | + Extra keyword arguments are forwarded to ``BabelQueue`` (``queue``, |
| 44 | + ``max_attempts``, ``dead_letter``, ``on_unknown_urn``, ...). |
| 45 | + """ |
| 46 | + return BabelQueue(broker_url(celery_app), **kwargs) |
| 47 | + |
| 48 | + |
| 49 | +def install_worker( |
| 50 | + celery_app: Any, |
| 51 | + babel_app: Optional[BabelQueue] = None, |
| 52 | + *, |
| 53 | + queue: Optional[str] = None, |
| 54 | + **kwargs: Any, |
| 55 | +) -> type: |
| 56 | + """Register a Celery worker bootstep that consumes BabelQueue messages. |
| 57 | +
|
| 58 | + When a ``celery worker`` boots, the step starts a daemon thread running the |
| 59 | + BabelQueue consumer loop (URN routing, retry → dead-letter). If ``babel_app`` |
| 60 | + is omitted it is built with :func:`from_celery`. Returns the bootstep class. |
| 61 | + """ |
| 62 | + from celery import bootsteps # lazy: only needed for this integration |
| 63 | + |
| 64 | + app = babel_app if babel_app is not None else from_celery(celery_app, **kwargs) |
| 65 | + |
| 66 | + class BabelQueueConsumerStep(bootsteps.StartStopStep): |
| 67 | + """Runs the BabelQueue consumer loop alongside Celery's own consumer.""" |
| 68 | + |
| 69 | + def __init__(self, parent: Any, **options: Any) -> None: |
| 70 | + super().__init__(parent, **options) |
| 71 | + self._thread: Optional[threading.Thread] = None |
| 72 | + self._stop = threading.Event() |
| 73 | + |
| 74 | + def start(self, parent: Any) -> None: |
| 75 | + def loop() -> None: |
| 76 | + while not self._stop.is_set(): |
| 77 | + app.consume(queue, max_messages=1, timeout=1.0) |
| 78 | + |
| 79 | + self._thread = threading.Thread( |
| 80 | + target=loop, name="babelqueue-consumer", daemon=True |
| 81 | + ) |
| 82 | + self._thread.start() |
| 83 | + |
| 84 | + def stop(self, parent: Any) -> None: |
| 85 | + self._stop.set() |
| 86 | + |
| 87 | + celery_app.steps["worker"].add(BabelQueueConsumerStep) |
| 88 | + return BabelQueueConsumerStep |
0 commit comments