|
| 1 | +import asyncio |
| 2 | +import contextlib |
| 3 | +import dataclasses |
| 4 | +import itertools |
| 5 | +import logging |
| 6 | +import threading |
| 7 | +import typing |
| 8 | + |
| 9 | +from faststream.kafka import TopicPartition |
| 10 | + |
| 11 | + |
| 12 | +if typing.TYPE_CHECKING: |
| 13 | + from aiokafka import AIOKafkaConsumer |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +SHUTDOWN_TIMEOUT_SEC: typing.Final = 20 |
| 20 | + |
| 21 | + |
| 22 | +class CommitterIsDeadError(Exception): ... |
| 23 | + |
| 24 | + |
| 25 | +@dataclasses.dataclass(frozen=True, kw_only=True, slots=True) |
| 26 | +class KafkaCommitTask: |
| 27 | + asyncio_task: asyncio.Task[typing.Any] |
| 28 | + topic_partition: TopicPartition |
| 29 | + offset: int |
| 30 | + consumer: typing.Any |
| 31 | + |
| 32 | + |
| 33 | +class KafkaBatchCommitter: |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + commit_batch_timeout_sec: float = 10.0, |
| 37 | + commit_batch_size: int = 10, |
| 38 | + ) -> None: |
| 39 | + self._messages_queue: asyncio.Queue[KafkaCommitTask] = asyncio.Queue() |
| 40 | + self._asyncio_commit_process_task: asyncio.Task[typing.Any] | None = None |
| 41 | + self._flush_batch_event = asyncio.Event() |
| 42 | + |
| 43 | + self._commit_batch_timeout_sec = commit_batch_timeout_sec |
| 44 | + self._commit_batch_size = commit_batch_size |
| 45 | + self._shutdown_timeout = SHUTDOWN_TIMEOUT_SEC |
| 46 | + |
| 47 | + self._spawn_lock = threading.Lock() |
| 48 | + |
| 49 | + def _check_is_commit_task_running(self) -> None: |
| 50 | + is_commit_task_running: typing.Final[bool] = bool( |
| 51 | + self._asyncio_commit_process_task |
| 52 | + and not self._asyncio_commit_process_task.cancelled() |
| 53 | + and not self._asyncio_commit_process_task.done(), |
| 54 | + ) |
| 55 | + if not is_commit_task_running: |
| 56 | + msg: typing.Final = "Committer main task is not running" |
| 57 | + raise CommitterIsDeadError(msg) |
| 58 | + |
| 59 | + def _flush_tasks_queue(self) -> list[KafkaCommitTask]: |
| 60 | + tasks_to_return: typing.Final[list[KafkaCommitTask]] = [] |
| 61 | + while not self._messages_queue.empty(): |
| 62 | + tasks_to_return.append(self._messages_queue.get_nowait()) |
| 63 | + return tasks_to_return |
| 64 | + |
| 65 | + async def _populate_commit_batch(self) -> tuple[list[KafkaCommitTask], bool]: |
| 66 | + uncommited_tasks: typing.Final[list[KafkaCommitTask]] = [] |
| 67 | + should_shutdown = False |
| 68 | + queue_get_task: asyncio.Task[typing.Any] | None = None |
| 69 | + flush_wait_task: asyncio.Task[typing.Any] | None = None |
| 70 | + timeout_task: asyncio.Task[typing.Any] | None = None |
| 71 | + try: |
| 72 | + timeout_task = asyncio.create_task(asyncio.sleep(self._commit_batch_timeout_sec)) |
| 73 | + while len(uncommited_tasks) < self._commit_batch_size: |
| 74 | + queue_get_task = asyncio.create_task(self._messages_queue.get()) |
| 75 | + flush_wait_task = asyncio.create_task(self._flush_batch_event.wait()) |
| 76 | + await asyncio.wait([queue_get_task, flush_wait_task, timeout_task], return_when=asyncio.FIRST_COMPLETED) |
| 77 | + |
| 78 | + if queue_get_task.done(): |
| 79 | + uncommited_tasks.append(queue_get_task.result()) |
| 80 | + else: |
| 81 | + queue_get_task.cancel() |
| 82 | + |
| 83 | + # commit_all is called |
| 84 | + if flush_wait_task.done(): |
| 85 | + queue_get_task.cancel() |
| 86 | + uncommited_tasks.extend(self._flush_tasks_queue()) |
| 87 | + self._flush_batch_event.clear() |
| 88 | + timeout_task.cancel() |
| 89 | + should_shutdown = True |
| 90 | + break |
| 91 | + flush_wait_task.cancel() |
| 92 | + |
| 93 | + if timeout_task.done(): |
| 94 | + logger.debug("Timeout exceeded, batch contains %s elements", len(uncommited_tasks)) |
| 95 | + break |
| 96 | + |
| 97 | + logger.debug("Batch condition reached with %s elements", len(uncommited_tasks)) |
| 98 | + except asyncio.CancelledError: |
| 99 | + should_shutdown = True |
| 100 | + uncommited_tasks.extend(self._flush_tasks_queue()) |
| 101 | + |
| 102 | + for task in (queue_get_task, flush_wait_task, timeout_task): |
| 103 | + task and task.cancel() |
| 104 | + |
| 105 | + return uncommited_tasks, should_shutdown |
| 106 | + |
| 107 | + async def _call_committer( |
| 108 | + self, tasks_batch: list[KafkaCommitTask], partitions_to_offsets: dict[TopicPartition, int] |
| 109 | + ) -> bool: |
| 110 | + if not partitions_to_offsets: |
| 111 | + return True |
| 112 | + commit_succeeded = True |
| 113 | + consumer: typing.Final[AIOKafkaConsumer] = tasks_batch[0].consumer |
| 114 | + try: |
| 115 | + await consumer.commit(partitions_to_offsets) |
| 116 | + except Exception as exc: |
| 117 | + commit_succeeded = False |
| 118 | + logger.exception("Error during commit to kafka", exc_info=exc) |
| 119 | + for task in tasks_batch: |
| 120 | + await self._messages_queue.put(task) |
| 121 | + return commit_succeeded |
| 122 | + |
| 123 | + async def _commit_tasks_batch(self, tasks_batch: list[KafkaCommitTask]) -> bool: |
| 124 | + partitions_to_tasks: typing.Final = itertools.groupby( |
| 125 | + sorted(tasks_batch, key=lambda x: x.topic_partition), lambda x: x.topic_partition |
| 126 | + ) |
| 127 | + |
| 128 | + results: typing.Final = await asyncio.gather( |
| 129 | + *[task.asyncio_task for task in tasks_batch], return_exceptions=True |
| 130 | + ) |
| 131 | + for result in results: |
| 132 | + if isinstance(result, BaseException): |
| 133 | + logger.error("Task has finished with an exception", exc_info=result) |
| 134 | + |
| 135 | + partitions_to_offsets: typing.Final[dict[TopicPartition, int]] = {} |
| 136 | + partition: TopicPartition |
| 137 | + tasks: typing.Iterator[KafkaCommitTask] |
| 138 | + for partition, tasks in partitions_to_tasks: |
| 139 | + max_message_offset: int | None = None |
| 140 | + for task in tasks: |
| 141 | + if max_message_offset is None or task.offset > max_message_offset: |
| 142 | + max_message_offset = task.offset |
| 143 | + |
| 144 | + if max_message_offset is not None: |
| 145 | + partitions_to_offsets[partition] = max_message_offset + 1 |
| 146 | + |
| 147 | + commit_succeeded: typing.Final = await self._call_committer(tasks_batch, partitions_to_offsets) |
| 148 | + for _ in tasks_batch: |
| 149 | + self._messages_queue.task_done() |
| 150 | + return commit_succeeded |
| 151 | + |
| 152 | + async def _run_commit_process(self) -> None: |
| 153 | + should_shutdown = False |
| 154 | + while not should_shutdown: |
| 155 | + commit_batch, should_shutdown = await self._populate_commit_batch() |
| 156 | + if commit_batch: |
| 157 | + await self._commit_tasks_batch(commit_batch) |
| 158 | + |
| 159 | + async def commit_all(self) -> None: |
| 160 | + """Commit all without shutting down the main process.""" |
| 161 | + self._flush_batch_event.set() |
| 162 | + await self._messages_queue.join() |
| 163 | + |
| 164 | + async def send_task(self, new_task: KafkaCommitTask) -> None: |
| 165 | + self._check_is_commit_task_running() |
| 166 | + await self._messages_queue.put( |
| 167 | + new_task, |
| 168 | + ) |
| 169 | + |
| 170 | + def spawn(self) -> None: |
| 171 | + with self._spawn_lock: |
| 172 | + if not self._asyncio_commit_process_task: |
| 173 | + self._asyncio_commit_process_task = asyncio.create_task(self._run_commit_process()) |
| 174 | + else: |
| 175 | + logger.error("Committer main task already running") |
| 176 | + |
| 177 | + async def close(self) -> None: |
| 178 | + """Close committer.""" |
| 179 | + if not self._asyncio_commit_process_task: |
| 180 | + logger.error("Committer main task is not running, cannot close committer properly") |
| 181 | + return |
| 182 | + |
| 183 | + self._flush_batch_event.set() |
| 184 | + try: |
| 185 | + await asyncio.wait_for(self._asyncio_commit_process_task, timeout=self._shutdown_timeout) |
| 186 | + except TimeoutError: |
| 187 | + logger.exception("Committer main task shutdown timed out, forcing cancellation") |
| 188 | + self._asyncio_commit_process_task.cancel() |
| 189 | + with contextlib.suppress(asyncio.CancelledError): |
| 190 | + await self._asyncio_commit_process_task |
| 191 | + except Exception as exc: |
| 192 | + logger.exception("Committer task failed during shutdown", exc_info=exc) |
| 193 | + raise |
| 194 | + |
| 195 | + @property |
| 196 | + def is_healthy(self) -> bool: |
| 197 | + return self._asyncio_commit_process_task is not None and not self._asyncio_commit_process_task.done() |
0 commit comments