Debian Codegraph @

tests/common/_async/producer.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2025 Confluent Inc.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18
19 from confluent_kafka.cimpl import Producer
20 import inspect
21 import asyncio
22
23 from confluent_kafka.error import KeySerializationError, ValueSerializationError
24 from confluent_kafka.serialization import MessageField, SerializationContext
25
26 ASYNC_PRODUCER_POLL_INTERVAL: int = 0.2
27
28
29 class AsyncProducer(Producer):
30 def __init__(
31 self,
32 conf: dict,
33 loop: asyncio.AbstractEventLoop = None,
34 poll_interval: int = ASYNC_PRODUCER_POLL_INTERVAL
35 ):
36 super().__init__(conf)
37
38 self._loop = loop or asyncio.get_event_loop()
39 self._poll_interval = poll_interval
40
41 self._poll_task = None
42 self._waiters: int = 0
43
44 async def produce(
45 self, topic, value=None, key=None, partition=-1,
46 on_delivery=None, timestamp=0, headers=None
47 ):
48 fut = self._loop.create_future()
49 self._waiters += 1
50 try:
51 if self._poll_task is None or self._poll_task.done():
52 self._poll_task = asyncio.create_task(self._poll_dr(self._poll_interval))
53
54 def wrapped_on_delivery(err, msg):
55 if on_delivery is not None:
56 if inspect.iscoroutinefunction(on_delivery):
57 asyncio.run_coroutine_threadsafe(
58 on_delivery(err, msg),
59 self._loop
60 )
61 else:
62 self._loop.call_soon_threadsafe(on_delivery, err, msg)
63
64 if err:
65 self._loop.call_soon_threadsafe(fut.set_exception, err)
66 else:
67 self._loop.call_soon_threadsafe(fut.set_result, msg)
68
69 super().produce(
70 topic,
71 value,
72 key,
73 headers=headers,
74 partition=partition,
75 timestamp=timestamp,
76 on_delivery=wrapped_on_delivery
77 )
78 return await fut
79 finally:
80 self._waiters -= 1
81
82 async def _poll_dr(self, interval: int):
83 """Poll delivery reports at interval seconds"""
84 while self._waiters:
85 super().poll(0)
86 await asyncio.sleep(interval)
87
88
89 class TestAsyncSerializingProducer(AsyncProducer):
90 def __init__(self, conf):
91 conf_copy = conf.copy()
92
93 self._key_serializer = conf_copy.pop('key.serializer', None)
94 self._value_serializer = conf_copy.pop('value.serializer', None)
95
96 super(TestAsyncSerializingProducer, self).__init__(conf_copy)
97
98 async def produce(
99 self, topic, key=None, value=None, partition=-1,
100 on_delivery=None, timestamp=0, headers=None):
101 ctx = SerializationContext(topic, MessageField.KEY, headers)
102 if self._key_serializer is not None:
103 try:
104 key = await self._key_serializer(key, ctx)
105 except Exception as se:
106 raise KeySerializationError(se)
107 ctx.field = MessageField.VALUE
108 if self._value_serializer is not None:
109 try:
110 value = await self._value_serializer(value, ctx)
111 except Exception as se:
112 raise ValueSerializationError(se)
113
114 return await super().produce(
115 topic, value, key,
116 headers=headers,
117 partition=partition,
118 timestamp=timestamp,
119 on_delivery=on_delivery
120 )