-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathKafkaTransport.php
More file actions
85 lines (70 loc) · 2.45 KB
/
KafkaTransport.php
File metadata and controls
85 lines (70 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace FriendsOfOpenTelemetry\OpenTelemetryBundle\OpenTelemetry\Transport;
use OpenTelemetry\SDK\Common\Export\TransportInterface;
use OpenTelemetry\SDK\Common\Future\CancellationInterface;
use OpenTelemetry\SDK\Common\Future\CompletedFuture;
use OpenTelemetry\SDK\Common\Future\ErrorFuture;
use OpenTelemetry\SDK\Common\Future\FutureInterface;
use RdKafka\Conf;
use RdKafka\Producer;
use RdKafka\ProducerTopic;
/**
* @template-implements TransportInterface<"application/x-protobuf">
*/
final readonly class KafkaTransport implements TransportInterface
{
private const FLUSH_TIMEOUT = 10000;
private Producer $producer;
private ProducerTopic $topicHandle;
public function __construct(
Conf $configuration,
string $topic,
) {
if (!\class_exists(Conf::class)) {
throw new \RuntimeException('The PHP extension "rdkafka" is required to use the Kafka transport.');
}
$this->producer = new Producer($configuration);
$this->topicHandle = $this->producer->newTopic($topic);
}
public function contentType(): string
{
return 'application/x-protobuf';
}
/**
* @phpstan-return FutureInterface<null>
*/
public function send(string $payload, ?CancellationInterface $cancellation = null): FutureInterface
{
try {
$this->topicHandle->producev(\RD_KAFKA_PARTITION_UA, 0, $payload);
} catch (\Throwable $exception) {
return new ErrorFuture($exception);
}
return new CompletedFuture(null);
}
public function shutdown(?CancellationInterface $cancellation = null): bool
{
return $this->flushInternal();
}
public function forceFlush(?CancellationInterface $cancellation = null): bool
{
return $this->flushInternal();
}
private function flushInternal(): bool
{
// librdkafka recommends retrying the flush operation a couple of times when it returns a null result.
$timeout = self::FLUSH_TIMEOUT;
$start = \microtime(true);
do {
$res = $this->producer->flush($timeout);
if (\RD_KAFKA_RESP_ERR_NO_ERROR === $res) {
return true;
}
// reduce timeout
$elapsedMs = (int) \round((\microtime(true) - $start) * 1000);
$timeout = \max(0, self::FLUSH_TIMEOUT - $elapsedMs);
} while ($timeout > 0);
return false;
}
}