|
| 1 | +import sys |
| 2 | +from contextlib import asynccontextmanager |
| 3 | +from logging import getLogger |
| 4 | +from typing import ( |
| 5 | + TYPE_CHECKING, |
| 6 | + Any, |
| 7 | + AsyncGenerator, |
| 8 | + AsyncIterator, |
| 9 | + Callable, |
| 10 | + List, |
| 11 | + Optional, |
| 12 | + Tuple, |
| 13 | + TypeVar, |
| 14 | +) |
| 15 | + |
| 16 | +from redis.asyncio import Redis, Sentinel |
| 17 | +from taskiq import AsyncResultBackend, BrokerMessage |
| 18 | +from taskiq.abc.broker import AsyncBroker |
| 19 | + |
| 20 | +if sys.version_info >= (3, 10): |
| 21 | + from typing import TypeAlias |
| 22 | +else: |
| 23 | + from typing_extensions import TypeAlias |
| 24 | + |
| 25 | +if TYPE_CHECKING: |
| 26 | + _Redis: TypeAlias = Redis[bytes] |
| 27 | +else: |
| 28 | + _Redis: TypeAlias = Redis |
| 29 | + |
| 30 | +_T = TypeVar("_T") |
| 31 | + |
| 32 | +logger = getLogger("taskiq.redis_sentinel_broker") |
| 33 | + |
| 34 | + |
| 35 | +class BaseSentinelBroker(AsyncBroker): |
| 36 | + """Base broker that works with Sentinel.""" |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + sentinels: List[Tuple[str, int]], |
| 41 | + master_name: str, |
| 42 | + result_backend: Optional[AsyncResultBackend[_T]] = None, |
| 43 | + task_id_generator: Optional[Callable[[], str]] = None, |
| 44 | + queue_name: str = "taskiq", |
| 45 | + min_other_sentinels: int = 0, |
| 46 | + sentinel_kwargs: Optional[Any] = None, |
| 47 | + **connection_kwargs: Any, |
| 48 | + ) -> None: |
| 49 | + super().__init__( |
| 50 | + result_backend=result_backend, |
| 51 | + task_id_generator=task_id_generator, |
| 52 | + ) |
| 53 | + |
| 54 | + self.sentinel = Sentinel( |
| 55 | + sentinels=sentinels, |
| 56 | + min_other_sentinels=min_other_sentinels, |
| 57 | + sentinel_kwargs=sentinel_kwargs, |
| 58 | + **connection_kwargs, |
| 59 | + ) |
| 60 | + self.master_name = master_name |
| 61 | + self.queue_name = queue_name |
| 62 | + |
| 63 | + @asynccontextmanager |
| 64 | + async def _acquire_master_conn(self) -> AsyncIterator[_Redis]: |
| 65 | + async with self.sentinel.master_for(self.master_name) as redis_conn: |
| 66 | + yield redis_conn |
| 67 | + |
| 68 | + |
| 69 | +class ListQueueSentinelBroker(BaseSentinelBroker): |
| 70 | + """Broker that works with Sentinel and distributes tasks between workers.""" |
| 71 | + |
| 72 | + async def kick(self, message: BrokerMessage) -> None: |
| 73 | + """ |
| 74 | + Put a message in a list. |
| 75 | +
|
| 76 | + This method appends a message to the list of all messages. |
| 77 | +
|
| 78 | + :param message: message to append. |
| 79 | + """ |
| 80 | + queue_name = message.labels.get("queue_name") or self.queue_name |
| 81 | + async with self._acquire_master_conn() as redis_conn: |
| 82 | + await redis_conn.lpush(queue_name, message.message) |
| 83 | + |
| 84 | + async def listen(self) -> AsyncGenerator[bytes, None]: |
| 85 | + """ |
| 86 | + Listen redis queue for new messages. |
| 87 | +
|
| 88 | + This function listens to the queue |
| 89 | + and yields new messages if they have BrokerMessage type. |
| 90 | +
|
| 91 | + :yields: broker messages. |
| 92 | + """ |
| 93 | + redis_brpop_data_position = 1 |
| 94 | + async with self._acquire_master_conn() as redis_conn: |
| 95 | + while True: |
| 96 | + yield (await redis_conn.brpop(self.queue_name))[ |
| 97 | + redis_brpop_data_position |
| 98 | + ] |
0 commit comments