| 1 |
""" |
| 2 |
Producer strategies for testing sync and async Kafka producers. |
| 3 |
|
| 4 |
This module contains strategy classes that encapsulate the different producer |
| 5 |
implementations (sync vs async) with consistent interfaces for testing. |
| 6 |
""" |
| 7 |
import time |
| 8 |
import asyncio |
| 9 |
import uuid |
| 10 |
from confluent_kafka import Producer |
| 11 |
import json |
| 12 |
from confluent_kafka.schema_registry import SchemaRegistryClient |
| 13 |
from confluent_kafka.schema_registry._sync.json_schema import JSONSerializer |
| 14 |
from confluent_kafka.schema_registry._sync.protobuf import ProtobufSerializer |
| 15 |
from confluent_kafka.schema_registry.avro import AvroSerializer |
| 16 |
from confluent_kafka.schema_registry._async.json_schema import AsyncJSONSerializer |
| 17 |
from confluent_kafka.schema_registry._async.protobuf import AsyncProtobufSerializer |
| 18 |
from confluent_kafka.schema_registry._async.avro import AsyncAvroSerializer |
| 19 |
from confluent_kafka.schema_registry.schema_registry_client import AsyncSchemaRegistryClient |
| 20 |
from confluent_kafka.serialization import MessageField, SerializationContext, StringSerializer |
| 21 |
from tests.integration.schema_registry.data.proto import PublicTestProto_pb2 |
| 22 |
import os |
| 23 |
|
| 24 |
|
| 25 |
class ProducerStrategy: |
| 26 |
"""Base class for producer strategies""" |
| 27 |
|
| 28 |
def __init__(self, bootstrap_servers, logger): |
| 29 |
self.bootstrap_servers = bootstrap_servers |
| 30 |
self.logger = logger |
| 31 |
self.metrics = None |
| 32 |
|
| 33 |
def create_producer(self): |
| 34 |
raise NotImplementedError() |
| 35 |
|
| 36 |
def produce_messages(self, topic_name, test_duration, start_time, message_formatter, |
| 37 |
delivered_container, failed_container=None, serialization_type=None): |
| 38 |
raise NotImplementedError() |
| 39 |
|
| 40 |
def _get_base_config(self): |
| 41 |
"""Get shared Kafka producer configuration optimized for low-latency, high-throughput""" |
| 42 |
return { |
| 43 |
'bootstrap.servers': self.bootstrap_servers, |
| 44 |
'queue.buffering.max.messages': 1000000, |
| 45 |
'queue.buffering.max.kbytes': 1048576, |
| 46 |
'batch.size': 65536, |
| 47 |
'batch.num.messages': 50000, |
| 48 |
'message.max.bytes': 2097152, |
| 49 |
'linger.ms': 1, |
| 50 |
'compression.type': 'lz4', |
| 51 |
'acks': 1, |
| 52 |
'retries': 3, |
| 53 |
'delivery.timeout.ms': 30000, |
| 54 |
'max.in.flight.requests.per.connection': 5 |
| 55 |
} |
| 56 |
|
| 57 |
def _log_configuration(self, config, producer_type, extra_params=None): |
| 58 |
"""Log producer configuration for validation""" |
| 59 |
separator = "=" * (len(f"{producer_type.upper()} PRODUCER CONFIGURATION") + 6) |
| 60 |
self.logger.info(f"=== {producer_type.upper()} PRODUCER CONFIGURATION ===") |
| 61 |
for key, value in config.items(): |
| 62 |
self.logger.info(f"{key}: {value}") |
| 63 |
|
| 64 |
if extra_params: |
| 65 |
for key, value in extra_params.items(): |
| 66 |
self.logger.info(f"{key}: {value}") |
| 67 |
|
| 68 |
self.logger.info(separator) |
| 69 |
|
| 70 |
def _print_timing_metrics(self, producer_type, produce_times, poll_times, flush_time): |
| 71 |
"""Print code path timing metrics""" |
| 72 |
avg_produce_time = sum(produce_times) / len(produce_times) * 1000 if produce_times else 0 |
| 73 |
avg_poll_time = sum(poll_times) / len(poll_times) * 1000 if poll_times else 0 |
| 74 |
flush_time_ms = flush_time * 1000 |
| 75 |
|
| 76 |
separator = "=" * (len(f"{producer_type.upper()} PRODUCER CODE PATH TIMING") + 6) |
| 77 |
print(f"\n=== {producer_type.upper()} PRODUCER CODE PATH TIMING ===") |
| 78 |
print(f"Time to call {'AIO' if producer_type == 'ASYNC' else ''}Producer.produce(): {avg_produce_time:.4f}ms") |
| 79 |
print(f"Time to call {'AIO' if producer_type == 'ASYNC' else ''}Producer.poll(): {avg_poll_time:.4f}ms") |
| 80 |
print(f"Time to call {'AIO' if producer_type == 'ASYNC' else ''}Producer.flush(): {flush_time_ms:.4f}ms") |
| 81 |
print(f"Total produce() calls: {len(produce_times)}") |
| 82 |
print(f"Total poll() calls: {len(poll_times)}") |
| 83 |
print(separator) |
| 84 |
|
| 85 |
def build_serializers(self, serialization_type): |
| 86 |
"""Build and return (key_serializer, value_serializer) for the given serialization_type. |
| 87 |
Returns (None, None) if serialization_type is not provided. |
| 88 |
This method should be implemented by concrete strategy classes. |
| 89 |
""" |
| 90 |
raise NotImplementedError("Subclasses must implement build_serializers") |
| 91 |
|
| 92 |
|
| 93 |
class SyncProducerStrategy(ProducerStrategy): |
| 94 |
def build_serializers(self, serialization_type): |
| 95 |
"""Build synchronous serializers for Schema Registry""" |
| 96 |
if not serialization_type: |
| 97 |
return None, None |
| 98 |
|
| 99 |
schema_registry_url = os.getenv( |
| 100 |
'SCHEMA_REGISTRY_URL', |
| 101 |
getattr(self, 'schema_registry_url', 'http://localhost:8081') |
| 102 |
) |
| 103 |
client_config = { |
| 104 |
'url': schema_registry_url, |
| 105 |
} |
| 106 |
sr_client = SchemaRegistryClient(client_config) |
| 107 |
key_serializer = StringSerializer('utf8') |
| 108 |
|
| 109 |
if serialization_type == 'avro': |
| 110 |
avro_schema = { |
| 111 |
"type": "record", |
| 112 |
"name": "TestMessage", |
| 113 |
"fields": [ |
| 114 |
{"name": "test_string", "type": "string"}, |
| 115 |
{"name": "test_bool", "type": "boolean"}, |
| 116 |
{"name": "test_bytes", "type": "bytes"}, |
| 117 |
{"name": "test_double", "type": "double"}, |
| 118 |
{"name": "test_float", "type": "float"}, |
| 119 |
{"name": "test_fixed32", "type": "int"}, |
| 120 |
{"name": "test_fixed64", "type": "long"}, |
| 121 |
{"name": "test_int32", "type": "int"}, |
| 122 |
{"name": "test_int64", "type": "long"}, |
| 123 |
{"name": "test_sfixed32", "type": "int"}, |
| 124 |
{"name": "test_sfixed64", "type": "long"}, |
| 125 |
{"name": "test_sint32", "type": "int"}, |
| 126 |
{"name": "test_sint64", "type": "long"}, |
| 127 |
{"name": "test_uint32", "type": "int"}, |
| 128 |
{"name": "test_uint64", "type": "long"} |
| 129 |
] |
| 130 |
} |
| 131 |
value_serializer = AvroSerializer( |
| 132 |
schema_registry_client=sr_client, |
| 133 |
schema_str=json.dumps(avro_schema) |
| 134 |
) |
| 135 |
elif serialization_type == 'json': |
| 136 |
json_schema = { |
| 137 |
"type": "object", |
| 138 |
"title": "TestMessage", |
| 139 |
"properties": { |
| 140 |
"test_string": {"type": "string"}, |
| 141 |
"test_bool": {"type": "boolean"}, |
| 142 |
"test_bytes": {"type": "string"}, |
| 143 |
"test_double": {"type": "number"}, |
| 144 |
"test_float": {"type": "number"}, |
| 145 |
"test_fixed32": {"type": "integer"}, |
| 146 |
"test_fixed64": {"type": "integer"}, |
| 147 |
"test_int32": {"type": "integer"}, |
| 148 |
"test_int64": {"type": "integer"}, |
| 149 |
"test_sfixed32": {"type": "integer"}, |
| 150 |
"test_sfixed64": {"type": "integer"}, |
| 151 |
"test_sint32": {"type": "integer"}, |
| 152 |
"test_sint64": {"type": "integer"}, |
| 153 |
"test_uint32": {"type": "integer"}, |
| 154 |
"test_uint64": {"type": "integer"} |
| 155 |
}, |
| 156 |
"required": [ |
| 157 |
"test_string", "test_bool", "test_bytes", "test_double", "test_float", |
| 158 |
"test_fixed32", "test_fixed64", "test_int32", "test_int64", |
| 159 |
"test_sfixed32", "test_sfixed64", "test_sint32", "test_sint64", |
| 160 |
"test_uint32", "test_uint64" |
| 161 |
] |
| 162 |
} |
| 163 |
value_serializer = JSONSerializer(json.dumps(json_schema), sr_client) |
| 164 |
elif serialization_type == 'protobuf': |
| 165 |
value_serializer = ProtobufSerializer(PublicTestProto_pb2.TestMessage, sr_client) |
| 166 |
else: |
| 167 |
raise ValueError(f"Unsupported serialization_type: {serialization_type}") |
| 168 |
|
| 169 |
return key_serializer, value_serializer |
| 170 |
|
| 171 |
def create_producer(self, config_overrides=None): |
| 172 |
config = self._get_base_config() |
| 173 |
|
| 174 |
|
| 175 |
if config_overrides: |
| 176 |
config.update(config_overrides) |
| 177 |
|
| 178 |
producer = Producer(config) |
| 179 |
|
| 180 |
|
| 181 |
self._log_configuration(config, "SYNC") |
| 182 |
|
| 183 |
return producer |
| 184 |
|
| 185 |
def create_transactional_producer(self): |
| 186 |
overrides = { |
| 187 |
'transactional.id': f'sync-tx-producer-{uuid.uuid4()}', |
| 188 |
'acks': 'all', |
| 189 |
'enable.idempotence': True |
| 190 |
} |
| 191 |
return self.create_producer(config_overrides=overrides) |
| 192 |
|
| 193 |
def produce_messages(self, topic_name, test_duration, start_time, message_formatter, |
| 194 |
delivered_container, failed_container=None, serialization_type=None, |
| 195 |
use_transaction=False): |
| 196 |
config_overrides = getattr(self, 'config_overrides', None) |
| 197 |
if use_transaction: |
| 198 |
producer = self.create_transactional_producer() |
| 199 |
producer.init_transactions() |
| 200 |
else: |
| 201 |
producer = self.create_producer(config_overrides) |
| 202 |
|
| 203 |
|
| 204 |
messages_sent = 0 |
| 205 |
send_times = {} |
| 206 |
produce_times = [] |
| 207 |
poll_times = [] |
| 208 |
flush_time = 0 |
| 209 |
|
| 210 |
|
| 211 |
key_serializer, value_serializer = self.build_serializers(serialization_type) |
| 212 |
|
| 213 |
def delivery_callback(err, msg): |
| 214 |
if err: |
| 215 |
if failed_container is not None: |
| 216 |
failed_container.append(err) |
| 217 |
if self.metrics: |
| 218 |
self.metrics.record_failed( |
| 219 |
topic=msg.topic() if msg else topic_name, |
| 220 |
partition=msg.partition() if msg else 0 |
| 221 |
) |
| 222 |
else: |
| 223 |
delivered_container.append(msg) |
| 224 |
if self.metrics: |
| 225 |
|
| 226 |
msg_key = msg.key().decode('utf-8', errors='replace') if msg.key() else 'unknown' |
| 227 |
latency_ms = 0.0 |
| 228 |
if msg_key in send_times: |
| 229 |
latency_ms = (time.time() - send_times[msg_key]) * 1000 |
| 230 |
del send_times[msg_key] |
| 231 |
|
| 232 |
self.metrics.record_delivered(latency_ms, topic=msg.topic(), partition=msg.partition()) |
| 233 |
|
| 234 |
while time.time() - start_time < test_duration: |
| 235 |
message_value, message_key = message_formatter(messages_sent) |
| 236 |
try: |
| 237 |
|
| 238 |
if use_transaction: |
| 239 |
producer.begin_transaction() |
| 240 |
|
| 241 |
if serialization_type: |
| 242 |
|
| 243 |
serialized_key = key_serializer(message_key) |
| 244 |
serialized_value = value_serializer( |
| 245 |
message_value, SerializationContext(topic_name, MessageField.VALUE) |
| 246 |
) |
| 247 |
message_size = len(serialized_key) + len(serialized_value) |
| 248 |
if self.metrics: |
| 249 |
send_times[message_key] = time.time() |
| 250 |
self.metrics.record_sent(message_size, topic=topic_name, partition=0) |
| 251 |
produce_start = time.time() |
| 252 |
producer.produce( |
| 253 |
topic=topic_name, |
| 254 |
value=serialized_value, |
| 255 |
key=serialized_key, |
| 256 |
on_delivery=delivery_callback |
| 257 |
) |
| 258 |
else: |
| 259 |
|
| 260 |
if self.metrics: |
| 261 |
send_times[message_key] = time.time() |
| 262 |
message_size = len(message_value.encode('utf-8')) + len(message_key.encode('utf-8')) |
| 263 |
self.metrics.record_sent(message_size, topic=topic_name, partition=0) |
| 264 |
|
| 265 |
produce_start = time.time() |
| 266 |
producer.produce( |
| 267 |
topic=topic_name, |
| 268 |
value=message_value, |
| 269 |
key=message_key, |
| 270 |
on_delivery=delivery_callback |
| 271 |
) |
| 272 |
|
| 273 |
if use_transaction: |
| 274 |
producer.commit_transaction() |
| 275 |
|
| 276 |
produce_times.append(time.time() - produce_start) |
| 277 |
messages_sent += 1 |
| 278 |
|
| 279 |
|
| 280 |
poll_interval = getattr(self, 'poll_interval', 50) |
| 281 |
|
| 282 |
if messages_sent % poll_interval == 0: |
| 283 |
poll_start = time.time() |
| 284 |
producer.poll(0) |
| 285 |
poll_times.append(time.time() - poll_start) |
| 286 |
if self.metrics: |
| 287 |
self.metrics.record_poll() |
| 288 |
|
| 289 |
except Exception as e: |
| 290 |
if failed_container is not None: |
| 291 |
failed_container.append(e) |
| 292 |
if self.metrics: |
| 293 |
self.metrics.record_failed(topic=topic_name, partition=0) |
| 294 |
self.logger.error(f"Failed to produce message {messages_sent}: {e}") |
| 295 |
|
| 296 |
|
| 297 |
flush_start = time.time() |
| 298 |
producer.flush(timeout=30) |
| 299 |
flush_time = time.time() - flush_start |
| 300 |
|
| 301 |
|
| 302 |
self._print_timing_metrics("SYNC", produce_times, poll_times, flush_time) |
| 303 |
|
| 304 |
return messages_sent |
| 305 |
|
| 306 |
def get_final_metrics(self): |
| 307 |
"""Return final metrics summary for the sync producer""" |
| 308 |
if self.metrics: |
| 309 |
return self.metrics |
| 310 |
return None |
| 311 |
|
| 312 |
|
| 313 |
class AsyncProducerStrategy(ProducerStrategy): |
| 314 |
def __init__(self, *args, **kwargs): |
| 315 |
super().__init__(*args, **kwargs) |
| 316 |
self._producer_instance = None |
| 317 |
|
| 318 |
async def build_serializers(self, serialization_type): |
| 319 |
"""Build asynchronous serializers for Schema Registry""" |
| 320 |
if not serialization_type: |
| 321 |
return None, None |
| 322 |
|
| 323 |
schema_registry_url = os.getenv( |
| 324 |
'SCHEMA_REGISTRY_URL', |
| 325 |
getattr(self, 'schema_registry_url', 'http://localhost:8081') |
| 326 |
) |
| 327 |
client_config = { |
| 328 |
'url': schema_registry_url, |
| 329 |
} |
| 330 |
sr_client = AsyncSchemaRegistryClient(client_config) |
| 331 |
key_serializer = StringSerializer('utf8') |
| 332 |
|
| 333 |
if serialization_type == 'avro': |
| 334 |
avro_schema = { |
| 335 |
"type": "record", |
| 336 |
"name": "TestMessage", |
| 337 |
"fields": [ |
| 338 |
{"name": "test_string", "type": "string"}, |
| 339 |
{"name": "test_bool", "type": "boolean"}, |
| 340 |
{"name": "test_bytes", "type": "bytes"}, |
| 341 |
{"name": "test_double", "type": "double"}, |
| 342 |
{"name": "test_float", "type": "float"}, |
| 343 |
{"name": "test_fixed32", "type": "int"}, |
| 344 |
{"name": "test_fixed64", "type": "long"}, |
| 345 |
{"name": "test_int32", "type": "int"}, |
| 346 |
{"name": "test_int64", "type": "long"}, |
| 347 |
{"name": "test_sfixed32", "type": "int"}, |
| 348 |
{"name": "test_sfixed64", "type": "long"}, |
| 349 |
{"name": "test_sint32", "type": "int"}, |
| 350 |
{"name": "test_sint64", "type": "long"}, |
| 351 |
{"name": "test_uint32", "type": "int"}, |
| 352 |
{"name": "test_uint64", "type": "long"} |
| 353 |
] |
| 354 |
} |
| 355 |
value_serializer = await AsyncAvroSerializer( |
| 356 |
schema_registry_client=sr_client, |
| 357 |
schema_str=json.dumps(avro_schema) |
| 358 |
) |
| 359 |
elif serialization_type == 'json': |
| 360 |
json_schema = { |
| 361 |
"type": "object", |
| 362 |
"title": "TestMessage", |
| 363 |
"properties": { |
| 364 |
"test_string": {"type": "string"}, |
| 365 |
"test_bool": {"type": "boolean"}, |
| 366 |
"test_bytes": {"type": "string"}, |
| 367 |
"test_double": {"type": "number"}, |
| 368 |
"test_float": {"type": "number"}, |
| 369 |
"test_fixed32": {"type": "integer"}, |
| 370 |
"test_fixed64": {"type": "integer"}, |
| 371 |
"test_int32": {"type": "integer"}, |
| 372 |
"test_int64": {"type": "integer"}, |
| 373 |
"test_sfixed32": {"type": "integer"}, |
| 374 |
"test_sfixed64": {"type": "integer"}, |
| 375 |
"test_sint32": {"type": "integer"}, |
| 376 |
"test_sint64": {"type": "integer"}, |
| 377 |
"test_uint32": {"type": "integer"}, |
| 378 |
"test_uint64": {"type": "integer"} |
| 379 |
}, |
| 380 |
"required": [ |
| 381 |
"test_string", "test_bool", "test_bytes", "test_double", "test_float", |
| 382 |
"test_fixed32", "test_fixed64", "test_int32", "test_int64", |
| 383 |
"test_sfixed32", "test_sfixed64", "test_sint32", "test_sint64", |
| 384 |
"test_uint32", "test_uint64" |
| 385 |
] |
| 386 |
} |
| 387 |
value_serializer = await AsyncJSONSerializer(json.dumps(json_schema), sr_client) |
| 388 |
elif serialization_type == 'protobuf': |
| 389 |
value_serializer = await AsyncProtobufSerializer(PublicTestProto_pb2.TestMessage, sr_client) |
| 390 |
else: |
| 391 |
raise ValueError(f"Unsupported serialization_type: {serialization_type}") |
| 392 |
|
| 393 |
return key_serializer, value_serializer |
| 394 |
|
| 395 |
def create_producer(self, config_overrides=None): |
| 396 |
from confluent_kafka.experimental.aio import AIOProducer |
| 397 |
|
| 398 |
import logging |
| 399 |
logging.basicConfig(level=logging.INFO) |
| 400 |
|
| 401 |
config = self._get_base_config() |
| 402 |
|
| 403 |
|
| 404 |
if config_overrides: |
| 405 |
config.update(config_overrides) |
| 406 |
|
| 407 |
|
| 408 |
max_workers = getattr(self, 'max_workers', 4) |
| 409 |
batch_size = getattr(self, 'batch_size', 1000) |
| 410 |
|
| 411 |
|
| 412 |
self._producer_instance = AIOProducer(config, max_workers=max_workers, batch_size=batch_size) |
| 413 |
|
| 414 |
|
| 415 |
extra_params = {'max_workers': max_workers, 'batch_size': batch_size} |
| 416 |
self._log_configuration(config, "ASYNC", extra_params) |
| 417 |
|
| 418 |
return self._producer_instance |
| 419 |
|
| 420 |
def create_transactional_producer(self): |
| 421 |
overrides = { |
| 422 |
'transactional.id': f'async-tx-producer-{uuid.uuid4()}', |
| 423 |
'acks': 'all', |
| 424 |
'enable.idempotence': True |
| 425 |
} |
| 426 |
return self.create_producer(config_overrides=overrides) |
| 427 |
|
| 428 |
def produce_messages(self, topic_name, test_duration, start_time, message_formatter, |
| 429 |
delivered_container, failed_container=None, serialization_type=None, |
| 430 |
use_transaction=False): |
| 431 |
|
| 432 |
async def async_produce(): |
| 433 |
config_overrides = getattr(self, 'config_overrides', None) |
| 434 |
|
| 435 |
if use_transaction: |
| 436 |
producer = self.create_transactional_producer() |
| 437 |
await producer.init_transactions() |
| 438 |
else: |
| 439 |
producer = self.create_producer(config_overrides) |
| 440 |
|
| 441 |
|
| 442 |
messages_sent = 0 |
| 443 |
produce_times = [] |
| 444 |
poll_times = [] |
| 445 |
flush_time = 0 |
| 446 |
pending_futures = [] |
| 447 |
send_times = {} |
| 448 |
|
| 449 |
|
| 450 |
if serialization_type: |
| 451 |
key_serializer, value_serializer = await self.build_serializers(serialization_type) |
| 452 |
|
| 453 |
|
| 454 |
if self.metrics: |
| 455 |
def shared_metrics_callback(err, msg): |
| 456 |
if not err: |
| 457 |
|
| 458 |
msg_key = msg.key().decode('utf-8', errors='replace') if msg.key() else 'unknown' |
| 459 |
latency_ms = 0.0 |
| 460 |
if msg_key in send_times: |
| 461 |
latency_ms = (time.time() - send_times[msg_key]) * 1000 |
| 462 |
del send_times[msg_key] |
| 463 |
self.metrics.record_delivered(latency_ms, topic=msg.topic(), partition=msg.partition()) |
| 464 |
if not err: |
| 465 |
delivered_container.append(msg) |
| 466 |
|
| 467 |
while time.time() - start_time < test_duration: |
| 468 |
message_value, message_key = message_formatter(messages_sent) |
| 469 |
try: |
| 470 |
|
| 471 |
if use_transaction: |
| 472 |
await producer.begin_transaction() |
| 473 |
|
| 474 |
|
| 475 |
if serialization_type: |
| 476 |
serialized_key = key_serializer(message_key) |
| 477 |
|
| 478 |
serialized_value = await value_serializer( |
| 479 |
message_value, SerializationContext(topic_name, MessageField.VALUE) |
| 480 |
) |
| 481 |
message_size = len(serialized_key) + len(serialized_value) |
| 482 |
produce_value = serialized_value |
| 483 |
produce_key = serialized_key |
| 484 |
else: |
| 485 |
|
| 486 |
message_size = len(message_value.encode('utf-8')) + len(message_key.encode('utf-8')) |
| 487 |
produce_value = message_value |
| 488 |
produce_key = message_key |
| 489 |
|
| 490 |
|
| 491 |
if self.metrics: |
| 492 |
self.metrics.record_sent(message_size, topic=topic_name, partition=0) |
| 493 |
send_times[message_key] = time.time() |
| 494 |
|
| 495 |
|
| 496 |
produce_start = time.time() |
| 497 |
delivery_future = await producer.produce( |
| 498 |
topic=topic_name, |
| 499 |
value=produce_value, |
| 500 |
key=produce_key, |
| 501 |
on_delivery=shared_metrics_callback |
| 502 |
) |
| 503 |
|
| 504 |
|
| 505 |
if use_transaction: |
| 506 |
await producer.commit_transaction() |
| 507 |
|
| 508 |
produce_times.append(time.time() - produce_start) |
| 509 |
pending_futures.append((delivery_future, message_key)) |
| 510 |
messages_sent += 1 |
| 511 |
|
| 512 |
|
| 513 |
poll_interval = getattr(self, 'poll_interval', 50) |
| 514 |
|
| 515 |
if messages_sent % poll_interval == 0: |
| 516 |
poll_start = time.time() |
| 517 |
await producer.poll(0) |
| 518 |
poll_times.append(time.time() - poll_start) |
| 519 |
if self.metrics: |
| 520 |
self.metrics.record_poll() |
| 521 |
|
| 522 |
except Exception as e: |
| 523 |
if failed_container is not None: |
| 524 |
failed_container.append(e) |
| 525 |
if self.metrics: |
| 526 |
self.metrics.record_failed(topic=topic_name, partition=0) |
| 527 |
self.logger.error(f"Failed to produce message {messages_sent}: {e}") |
| 528 |
|
| 529 |
|
| 530 |
flush_start = time.time() |
| 531 |
await producer.flush(timeout=30) |
| 532 |
flush_time = time.time() - flush_start |
| 533 |
|
| 534 |
|
| 535 |
for delivery_future, message_key in pending_futures: |
| 536 |
try: |
| 537 |
msg = await delivery_future |
| 538 |
delivered_container.append(msg) |
| 539 |
|
| 540 |
|
| 541 |
if self.metrics: |
| 542 |
|
| 543 |
latency_ms = 0.0 |
| 544 |
if message_key in send_times: |
| 545 |
latency_ms = (time.time() - send_times[message_key]) * 1000 |
| 546 |
del send_times[message_key] |
| 547 |
|
| 548 |
self.metrics.record_delivered(latency_ms, topic=msg.topic(), partition=msg.partition()) |
| 549 |
|
| 550 |
except Exception as e: |
| 551 |
if failed_container is not None: |
| 552 |
failed_container.append(e) |
| 553 |
if self.metrics: |
| 554 |
self.metrics.record_failed(topic=topic_name, partition=0) |
| 555 |
self.logger.error(f"Failed to deliver message with key {message_key}: {e}") |
| 556 |
|
| 557 |
|
| 558 |
self._print_timing_metrics("ASYNC", produce_times, poll_times, flush_time) |
| 559 |
|
| 560 |
|
| 561 |
await producer.close() |
| 562 |
|
| 563 |
return messages_sent |
| 564 |
|
| 565 |
loop = asyncio.get_event_loop() |
| 566 |
return loop.run_until_complete(async_produce()) |
| 567 |
|
| 568 |
def get_final_metrics(self): |
| 569 |
"""Return final metrics summary for the async producer""" |
| 570 |
if self.metrics: |
| 571 |
return self.metrics |
| 572 |
return None |