|
| 1 | +from threading import Thread |
| 2 | +from typing import Any, Callable, Optional, Union, TYPE_CHECKING |
| 3 | + |
| 4 | +from .daemon_heart import DaemonHeart |
| 5 | + |
| 6 | + |
| 7 | +if TYPE_CHECKING: |
| 8 | + # TODO: Quickfix guided by https://stackoverflow.com/questions/63714223/correct-type-annotation-for-a-celery-task |
| 9 | + from celery.task import Task |
| 10 | + from celery.local import PromiseProxy |
| 11 | + |
| 12 | + CELERY_TASK_TYPE = Union[Task, PromiseProxy] |
| 13 | +else: |
| 14 | + CELERY_TASK_TYPE = Any |
| 15 | + |
| 16 | + |
| 17 | +class Daemon: |
| 18 | + |
| 19 | + @staticmethod |
| 20 | + def summon(name: str, publisher: CELERY_TASK_TYPE, **heart_configs): |
| 21 | + def decorator(worker: CELERY_TASK_TYPE): |
| 22 | + def wrapper(*args, **kwargs): |
| 23 | + # Initialize the daemon and broadcast heartbeat |
| 24 | + daemon = Daemon(name=name, publisher=publisher, **heart_configs) |
| 25 | + daemon.broadcast() |
| 26 | + # Execute the worker function |
| 27 | + output = worker.delay(*args, **kwargs) |
| 28 | + # Kill the daemon |
| 29 | + daemon.kill() |
| 30 | + return output |
| 31 | + return wrapper |
| 32 | + return decorator |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + name: str, |
| 37 | + publisher: CELERY_TASK_TYPE, |
| 38 | + **heart_configs |
| 39 | + ): |
| 40 | + self.name = name |
| 41 | + self.publisher = publisher |
| 42 | + self.broadcast_thread: Optional[Thread] = None |
| 43 | + self.heart = DaemonHeart.beat( |
| 44 | + app_name=name, |
| 45 | + **{ # type: ignore |
| 46 | + "mode": DaemonHeart.Mode.MONITOR, |
| 47 | + "enable_beat_logs": True, |
| 48 | + "enable_pulse_monitor": True, |
| 49 | + "pulse_monitor_frequency": None, |
| 50 | + "pulse_monitor_sensibility_factor": 1.5, |
| 51 | + **heart_configs |
| 52 | + } |
| 53 | + ) |
| 54 | + |
| 55 | + def kill(self): |
| 56 | + # Stop heart |
| 57 | + self.heart.stroke() |
| 58 | + self.heart.join() |
| 59 | + self.heart.close() |
| 60 | + # Stop broadcast |
| 61 | + self.broadcast_thread.join() if self.broadcast_thread is not None else None |
| 62 | + |
| 63 | + def broadcast(self): |
| 64 | + self.broadcast_thread: Thread = Thread( |
| 65 | + target=lambda: self._broadcast(), |
| 66 | + daemon=True |
| 67 | + ) |
| 68 | + self.broadcast_thread.start() |
| 69 | + |
| 70 | + def _broadcast(self): |
| 71 | + while not self.heart.no_pulse.is_set(): |
| 72 | + payload = self.heart.queue_beat_logs.get(block=True) |
| 73 | + self.publisher.delay(**payload) |
0 commit comments