Coverage for faststream/kafka/helpers/admin.py: 96%

43 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1from dataclasses import dataclass 

2from typing import TYPE_CHECKING, Any 

3 

4import aiokafka.admin 

5from aiokafka.errors import TopicAlreadyExistsError, for_code 

6 

7from faststream._internal.utils.data import filter_by_dict 

8from faststream.exceptions import IncorrectState 

9from faststream.kafka.schemas.params import AdminClientConnectionParams 

10 

11if TYPE_CHECKING: 

12 from aiokafka.admin.client import AIOKafkaAdminClient 

13 

14 from faststream.kafka.schemas import Topic 

15 

16 

17@dataclass(slots=True) 

18class CreateResult: 

19 topic: str 

20 error: Exception | None 

21 

22 

23class AdminService: 

24 __slots__ = ("admin_client",) 

25 

26 def __init__(self) -> None: 

27 self.admin_client: AIOKafkaAdminClient | None = None 

28 

29 async def connect(self, **connection_kwargs: Any) -> None: 

30 if self.admin_client is not None: 30 ↛ 31line 30 didn't jump to line 31 because the condition on line 30 was never true

31 return 

32 

33 admin_options, _ = filter_by_dict( 

34 AdminClientConnectionParams, 

35 connection_kwargs, 

36 ) 

37 self.admin_client = aiokafka.admin.client.AIOKafkaAdminClient(**admin_options) 

38 await self.admin_client.start() 

39 

40 async def disconnect(self) -> None: 

41 if self.admin_client is not None: 

42 await self.admin_client.close() 

43 self.admin_client = None 

44 

45 @property 

46 def client(self) -> "AIOKafkaAdminClient": 

47 if self.admin_client is None: 

48 msg = "Admin client is not initialized. Call connect() first." 

49 raise IncorrectState(msg) 

50 return self.admin_client 

51 

52 async def create_topics(self, topics: list["Topic"]) -> list[CreateResult]: 

53 """Create topics through the admin client. 

54 

55 Already-exists is success. Any other per-topic error is collected rather 

56 than raised, so a subscriber still starts against a topic the cluster 

57 refused to create. 

58 """ 

59 if not topics: 

60 return [] 

61 

62 try: 

63 response = await self.client.create_topics( 

64 [topic.to_aiokafka() for topic in topics], 

65 ) 

66 except Exception as e: 

67 return [CreateResult(topic.name, e) for topic in topics] 

68 

69 results = [] 

70 for topic_error in response.to_object()["topic_errors"]: 

71 topic = topic_error["topic"] 

72 error_code = topic_error["error_code"] 

73 if not error_code: 

74 results.append(CreateResult(topic, None)) 

75 continue 

76 

77 error = for_code(error_code)( 

78 topic_error.get("error_message") or f"error code {error_code}", 

79 ) 

80 if isinstance(error, TopicAlreadyExistsError): 

81 results.append(CreateResult(topic, None)) 

82 else: 

83 results.append(CreateResult(topic, error)) 

84 

85 return results