|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from collections.abc import AsyncIterator, Callable, Coroutine, Mapping, Sequence |
| 5 | +from contextlib import asynccontextmanager |
| 6 | +from typing import TYPE_CHECKING, Any |
| 7 | + |
| 8 | +from aiokafka import AIOKafkaConsumer, AIOKafkaProducer |
| 9 | + |
| 10 | +from repid.connections.abc import CapabilitiesT, SentMessageT, ServerT, SubscriberT |
| 11 | +from repid.connections.kafka.subscriber import KafkaSubscriber |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from repid.asyncapi.models.common import ServerBindingsObject |
| 15 | + from repid.asyncapi.models.servers import ServerVariable |
| 16 | + from repid.connections.abc import ReceivedMessageT |
| 17 | + from repid.data import ExternalDocs, Tag |
| 18 | + |
| 19 | +logger = logging.getLogger("repid.connections.kafka") |
| 20 | + |
| 21 | + |
| 22 | +class KafkaServer(ServerT): |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + dsn: str, |
| 26 | + *, |
| 27 | + dlq_topic_strategy: Callable[[str], str] | None = lambda channel: f"repid_{channel}_dlq", |
| 28 | + title: str | None = None, |
| 29 | + summary: str | None = None, |
| 30 | + description: str | None = None, |
| 31 | + variables: Mapping[str, ServerVariable] | None = None, |
| 32 | + security: Sequence[Any] | None = None, |
| 33 | + tags: Sequence[Tag] | None = None, |
| 34 | + external_docs: ExternalDocs | None = None, |
| 35 | + bindings: ServerBindingsObject | None = None, |
| 36 | + ) -> None: |
| 37 | + self.dsn = dsn |
| 38 | + self._producer: AIOKafkaProducer | None = None # type: ignore[no-any-unimported] |
| 39 | + self._dlq_topic_strategy = dlq_topic_strategy |
| 40 | + |
| 41 | + # AsyncAPI metadata |
| 42 | + self._title = title |
| 43 | + self._summary = summary |
| 44 | + self._description = description |
| 45 | + self._variables = variables |
| 46 | + self._security = security |
| 47 | + self._tags = tags |
| 48 | + self._external_docs = external_docs |
| 49 | + self._bindings = bindings |
| 50 | + |
| 51 | + @property |
| 52 | + def host(self) -> str: |
| 53 | + return self.dsn |
| 54 | + |
| 55 | + @property |
| 56 | + def protocol(self) -> str: |
| 57 | + return "kafka" |
| 58 | + |
| 59 | + @property |
| 60 | + def pathname(self) -> str | None: |
| 61 | + return None |
| 62 | + |
| 63 | + @property |
| 64 | + def title(self) -> str | None: |
| 65 | + return self._title |
| 66 | + |
| 67 | + @property |
| 68 | + def summary(self) -> str | None: |
| 69 | + return self._summary |
| 70 | + |
| 71 | + @property |
| 72 | + def description(self) -> str | None: |
| 73 | + return self._description |
| 74 | + |
| 75 | + @property |
| 76 | + def protocol_version(self) -> str | None: |
| 77 | + return None |
| 78 | + |
| 79 | + @property |
| 80 | + def variables(self) -> Mapping[str, ServerVariable] | None: |
| 81 | + return self._variables |
| 82 | + |
| 83 | + @property |
| 84 | + def security(self) -> Sequence[Any] | None: |
| 85 | + return self._security |
| 86 | + |
| 87 | + @property |
| 88 | + def tags(self) -> Sequence[Tag] | None: |
| 89 | + return self._tags |
| 90 | + |
| 91 | + @property |
| 92 | + def external_docs(self) -> ExternalDocs | None: |
| 93 | + return self._external_docs |
| 94 | + |
| 95 | + @property |
| 96 | + def bindings(self) -> ServerBindingsObject | None: |
| 97 | + return self._bindings |
| 98 | + |
| 99 | + @property |
| 100 | + def capabilities(self) -> CapabilitiesT: |
| 101 | + return { |
| 102 | + "supports_acknowledgments": True, |
| 103 | + "supports_persistence": True, |
| 104 | + "supports_reply": True, |
| 105 | + "supports_lightweight_pause": False, |
| 106 | + } |
| 107 | + |
| 108 | + @property |
| 109 | + def is_connected(self) -> bool: |
| 110 | + return self._producer is not None |
| 111 | + |
| 112 | + async def connect(self) -> None: |
| 113 | + if self._producer is None: |
| 114 | + self._producer = AIOKafkaProducer(bootstrap_servers=self.dsn) |
| 115 | + await self._producer.start() |
| 116 | + logger.info("server.connect", extra={"host": self.dsn}) |
| 117 | + |
| 118 | + async def disconnect(self) -> None: |
| 119 | + if self._producer is not None: |
| 120 | + await self._producer.stop() |
| 121 | + self._producer = None |
| 122 | + logger.info("server.disconnect") |
| 123 | + |
| 124 | + @asynccontextmanager |
| 125 | + async def connection(self) -> AsyncIterator[KafkaServer]: |
| 126 | + await self.connect() |
| 127 | + try: |
| 128 | + yield self |
| 129 | + finally: |
| 130 | + await self.disconnect() |
| 131 | + |
| 132 | + async def publish( |
| 133 | + self, |
| 134 | + *, |
| 135 | + channel: str, |
| 136 | + message: SentMessageT, |
| 137 | + server_specific_parameters: dict[str, Any] | None = None, # noqa: ARG002 |
| 138 | + ) -> None: |
| 139 | + if self._producer is None: |
| 140 | + raise RuntimeError("Kafka producer is not connected.") |
| 141 | + |
| 142 | + logger.debug("channel.publish", extra={"channel": channel}) |
| 143 | + |
| 144 | + headers = [] |
| 145 | + if message.headers: |
| 146 | + for k, v in message.headers.items(): |
| 147 | + headers.append((k, v.encode())) |
| 148 | + if message.content_type: |
| 149 | + headers.append(("content-type", message.content_type.encode())) |
| 150 | + |
| 151 | + await self._producer.send_and_wait( |
| 152 | + topic=channel, |
| 153 | + value=message.payload, |
| 154 | + headers=headers, |
| 155 | + ) |
| 156 | + |
| 157 | + async def subscribe( |
| 158 | + self, |
| 159 | + *, |
| 160 | + channels_to_callbacks: dict[str, Callable[[ReceivedMessageT], Coroutine[None, None, None]]], |
| 161 | + concurrency_limit: int | None = None, |
| 162 | + ) -> SubscriberT: |
| 163 | + logger.debug("channel.subscribe", extra={"channels": list(channels_to_callbacks.keys())}) |
| 164 | + |
| 165 | + consumer = AIOKafkaConsumer( |
| 166 | + *channels_to_callbacks.keys(), |
| 167 | + bootstrap_servers=self.dsn, |
| 168 | + group_id="repid-group", |
| 169 | + enable_auto_commit=False, |
| 170 | + auto_offset_reset="earliest", |
| 171 | + ) |
| 172 | + await consumer.start() |
| 173 | + |
| 174 | + return KafkaSubscriber( |
| 175 | + server=self, |
| 176 | + consumer=consumer, |
| 177 | + channels_to_callbacks=channels_to_callbacks, |
| 178 | + concurrency_limit=concurrency_limit, |
| 179 | + ) |
0 commit comments