Signal handlers of the host process, captured before consuming and restored afterwards. */ private array $previousSignalHandlers = []; /** Whether the host process had async signals enabled, captured before consuming and restored afterwards. */ private bool $previousAsyncSignals = false; /** @var array Partitions that have reached EOF, keyed by "topic-partition". */ private array $partitionsAtEof = []; /** * Topics used to store offsets, keyed by topic name. They are created once per topic, * as php-rdkafka never releases the topic handles created by the consumer. * * @var array */ private array $offsetStoreTopics = []; private ?Closure $whenStopConsuming; private Dispatcher $dispatcher; public function __construct(private readonly Config $config, private readonly MessageDeserializer $deserializer, ?CommitterFactory $committerFactory = null) { $this->logger = app(Logger::class); $this->messageCounter = new MessageCounter($config->getMaxMessages()); $this->retryable = new Retryable(new NativeSleeper, 6, self::TIMEOUT_ERRORS); $this->committerFactory = $committerFactory ?? new DefaultCommitterFactory($this->messageCounter); $this->dispatcher = App::make(Dispatcher::class); $this->whenStopConsuming = $this->config->getWhenStopConsumingCallback(); } /** * Consume messages from a kafka topic in loop. * * @throws Exception */ public function consume(): void { $this->cancelStopConsume(); $this->configureRestartTimer(); $stopTimer = $this->configureStopTimer(); if ($this->supportAsyncSignals()) { $this->listenForSignals(); } try { $this->consumer = app(KafkaConsumer::class, [ 'conf' => $this->setConf($this->config->getConsumerOptions()), ]); $this->offsetStoreTopics = []; // The producer is only needed to forward failed messages to the dead letter // queue, and creating one opens broker connections and background threads // of its own, so it is created only when a dead letter queue is configured. if ($this->config->shouldSendToDlq()) { $this->producer = app(KafkaProducer::class, [ 'conf' => $this->setConf($this->config->getProducerOptions()), ]); } $this->committer = $this->committerFactory->make($this->consumer, $this->config); // Calling `subscribe` overrides the assigned topic partitions, so we // should check if there are any assignment defined before calling // the subscribe method on the consumer. Partition assignment // have precedence over topic subscriptions. if ($this->config->shouldAssignTopicPartitions()) { $this->consumer->assign($this->config->getPartitionAssigment()); } else { $this->consumer->subscribe($this->config->getTopics()); } do { $this->runBeforeCallbacks(); $this->retryable->retry(fn () => $this->doConsume()); $this->runAfterConsumingCallbacks(); $this->checkForRestart(); } while (! $this->maxMessagesLimitReached() && ! $stopTimer->isTimedOut() && ! $this->stopRequested); if ($this->shouldRunStopConsumingCallback()) { $callback = $this->whenStopConsuming; $callback(...)(); } } finally { if ($this->supportAsyncSignals()) { $this->restoreSignalHandlers(); } } } /** @inheritdoc */ public function stopConsuming(): void { $this->stopRequested = true; } /** Will cancel the stopConsume request initiated by calling the stopConsume method */ public function cancelStopConsume(): void { $this->stopRequested = false; } /** Count the number of messages consumed by this consumer */ public function consumedMessagesCount(): int { return $this->messageCounter->messagesCounted(); } /** {@inheritdoc} */ public function commit(mixed $messageOrOffsets = null): void { try { $this->committer->commit($messageOrOffsets); } catch (Throwable $throwable) { if ($throwable->getCode() !== RD_KAFKA_RESP_ERR__NO_OFFSET) { $this->logCommitError($messageOrOffsets, $throwable); throw $throwable; } } } /** {@inheritdoc} */ public function commitAsync(mixed $message_or_offsets = null): void { try { $this->committer->commitAsync($message_or_offsets); } catch (Throwable $throwable) { if ($throwable->getCode() !== RD_KAFKA_RESP_ERR__NO_OFFSET) { $this->logCommitError($message_or_offsets, $throwable); throw $throwable; } } } /** Get the current partition assignment for this consumer */ public function getAssignedPartitions(): array { if (! isset($this->consumer)) { return []; } return $this->consumer->getAssignment(); } public function configureStopTimer(): Timer { $stopTimer = new Timer; if ($this->config->getMaxTime() === 0) { $stopTimer = new InfiniteTimer; } $stopTimer->start($this->config->getMaxTime() * 1000); return $stopTimer; } protected function configureRestartTimer(): void { $this->lastRestart = $this->getLastRestart(); $this->restartTimer = new Timer; $this->restartTimer->start($this->config->getRestartInterval()); } protected function checkForRestart(): void { if (! $this->restartTimer->isTimedOut()) { return; } $this->restartTimer->start($this->config->getRestartInterval()); if ($this->lastRestart !== $this->getLastRestart()) { $this->stopRequested = true; } } protected function getLastRestart(): int { return (int) Cache::driver(config('kafka.cache_driver'))->get('laravel-kafka:consumer:restart', 0); } /** * The logger contract only accepts RdKafka messages, so commits made with * a ConsumerMessage, TopicPartition[] or null are rethrown without logging. */ private function logCommitError(mixed $messageOrOffsets, Throwable $throwable): void { if ($messageOrOffsets instanceof Message) { $this->logger->error($messageOrOffsets, $throwable, 'COMMIT_ERROR'); } } private function runBeforeCallbacks(): void { foreach ($this->config->getBeforeConsumingCallbacks() as $beforeConsumingCallback) { $beforeConsumingCallback($this); } } private function runAfterConsumingCallbacks(): void { foreach ($this->config->getAfterConsumingCallbacks() as $afterConsumingCallback) { $afterConsumingCallback($this); } } private function shouldRunStopConsumingCallback(): bool { return $this->whenStopConsuming !== null; } /** * Stop consuming on termination signals without taking the signals away from the host * process: a handler that was registered before (e.g. by a Laravel queue worker running * this consumer inside a job) is still invoked, and it is restored once consuming ends. */ private function listenForSignals(): void { $this->previousAsyncSignals = pcntl_async_signals(true); foreach ([SIGQUIT, SIGTERM, SIGINT] as $signal) { $previousHandler = pcntl_signal_get_handler($signal); $this->previousSignalHandlers[$signal] = $previousHandler; pcntl_signal($signal, function (int $signal, mixed $signalInfo = null) use ($previousHandler): void { $this->stopRequested = true; if (is_callable($previousHandler)) { $previousHandler($signal, $signalInfo); } }); } } private function restoreSignalHandlers(): void { foreach ($this->previousSignalHandlers as $signal => $previousHandler) { pcntl_signal($signal, $previousHandler); } pcntl_async_signals($this->previousAsyncSignals); $this->previousSignalHandlers = []; } private function supportAsyncSignals(): bool { return extension_loaded('pcntl'); } /** * Execute the consume method on RdKafka consumer. * * @throws ConsumerException * @throws Exception|Throwable */ private function doConsume(): void { $message = $this->consumer->consume((int) config('kafka.consumer_timeout_ms', 2000)); $this->handleMessage($message); } /** Set the consumer configuration. */ private function setConf(array $options): Conf { $conf = new Conf; foreach ($options as $key => $value) { $conf->set($key, $value); } foreach ($this->config->getConfigCallbacks() as $method => $callback) { $conf->{$method}($callback); } return $conf; } /** * Tries to handle the message received. * * @throws Throwable */ private function executeMessage(Message $message): void { try { $consumedMessage = $this->getConsumerMessage($message); // Here we will dispatch an event to inform possible interested listeners that a message // was received and will be consumed as soon as a consumer is available to process it. $this->dispatcher->dispatch(new StartedConsumingMessage($consumedMessage)); $consumedMessage = $this->deserializer->deserialize($consumedMessage); // The handler is called again while it fails and has retries left, waiting for the backoff // between attempts. Retries stop early when the consumer is asked to stop consuming, or // when the exception does not match the retry condition given to the consumer builder. retry( $this->config->getFailedMessageRetries() + 1, fn () => $this->config->getConsumer()->handle($consumedMessage, $this), $this->config->getFailedMessageRetryBackoff(), function (Throwable $throwable) use ($message): bool { if ($this->stopRequested || ! $this->config->shouldRetryFailedMessage($throwable)) { return false; } $this->logger->error($message, $throwable, 'RETRY'); return true; }, ); $success = true; // Dispatch an event informing that a message was consumed. $this->dispatcher->dispatch(new MessageConsumed($consumedMessage)); } catch (Throwable $throwable) { $this->logger->error($message, $throwable); $success = $this->handleException($throwable, $message); // Without a dead letter queue, the offset of the failed message is left uncommitted, // so it is consumed again once a consumer resumes from this partition. Closing the // consumer commits the offsets stored so far and leaves the group right away. if (! $success && $this->config->shouldStopOnFailure($throwable)) { $this->consumer->close(); throw ConsumerException::stoppedOnFailure($message, $throwable); } } if ($success) { $this->storeOffsetIfRequired($message); } $this->autoCommitIfEnabled($message, $success); } /** Handle exceptions while consuming messages. */ private function handleException(Throwable $exception, Message|ConsumerMessage $message): bool { try { // If the message consumption fails, we first try to reprocess the message // using the fallback provided by the consumer. Message will be sent to // a dead letter queue only if the failed method throws an exception. $this->config->getConsumer()->failed( $message->payload ?? '', $this->config->getTopics()[0], $exception ); } catch (Throwable $throwable) { if ($exception !== $throwable) { $this->logger->error($message, $throwable, 'HANDLER_EXCEPTION'); } report($throwable); if ($this->config->shouldSendToDlq()) { $messageIdentifier = $message instanceof ConsumerMessage ? $message->getMessageIdentifier() : null; $this->sendToDlq($message, $messageIdentifier, $throwable); $this->committer->commitDlq($message); return true; } return false; } } /** Send a message to the Dead Letter Queue. */ private function sendToDlq(Message $message, ?string $messageIdentifier = null, ?Throwable $throwable = null): void { $topic = $this->producer->newTopic($this->config->getDlq()); $topic->producev( partition: RD_KAFKA_PARTITION_UA, msgflags: 0, payload: $message->payload, key: $this->config->getConsumer()->producerKey($message), headers: $this->buildHeadersForDlq($message, $throwable) ); $this->dispatcher->dispatch(new MessageSentToDLQ( $message->payload, $this->config->getConsumer()->producerKey($message), $message->headers ?? [], $throwable, $messageIdentifier )); if (method_exists($this->producer, 'flush')) { $this->producer->flush(12000); } } private function buildHeadersForDlq(Message $message, ?Throwable $throwable = null): array { if (! $throwable instanceof Throwable) { return []; } $throwableHeaders['kafka_throwable_message'] = $throwable->getMessage(); $throwableHeaders['kafka_throwable_code'] = $throwable->getCode(); $throwableHeaders['kafka_throwable_class_name'] = get_class($throwable); if ($throwable instanceof ContextAware) { $contextHeaders = $this->normalizeContext($throwable->getContext()); } return array_merge($message->headers ?? [], $throwableHeaders, $contextHeaders ?? []); } /** * Store the offset of a processed message, so it is committed by librdkafka auto commit. * * @throws Exception */ private function storeOffsetIfRequired(Message $message): void { if (! $this->config->shouldStoreOffsetsAfterProcessing()) { return; } $this->offsetStoreTopics[$message->topic_name] ??= $this->consumer->newTopic($message->topic_name); try { $this->offsetStoreTopics[$message->topic_name]->offsetStore($message->partition, $message->offset); } catch (Exception $exception) { // The partition was revoked while the message was processed. Its new // owner resumes from the last committed offset, so there is nothing to store. if ($exception->getCode() !== RD_KAFKA_RESP_ERR__STATE) { throw $exception; } } } /** @throws Throwable */ private function autoCommitIfEnabled(Message $message, bool $success): void { if (! $this->config->isAutoCommit()) { return; } try { $this->committer->commitMessage($message, $success); } catch (Throwable $throwable) { if ($throwable->getCode() !== RD_KAFKA_RESP_ERR__NO_OFFSET) { $this->logger->error($message, $throwable, 'AUTO_COMMIT'); throw $throwable; } } } /** Determine if the max message limit is reached. */ private function maxMessagesLimitReached(): bool { return $this->messageCounter->maxMessagesLimitReached(); } /** * Handle the message. * * @throws ConsumerException * @throws Throwable */ private function handleMessage(Message $message): void { if ($message->err === RD_KAFKA_RESP_ERR_NO_ERROR) { // Receiving a message from a partition that previously reached // EOF means the partition is no longer drained. unset($this->partitionsAtEof[$this->partitionKey($message->topic_name, $message->partition)]); $this->messageCounter->add(); $this->executeMessage($message); return; } if ($this->config->shouldStopAfterLastMessage() && in_array($message->err, self::CONSUME_STOP_EOF_ERRORS, true)) { if ($message->err === RD_KAFKA_RESP_ERR__PARTITION_EOF ? $this->allAssignedPartitionsReachedEof($message) : $this->hasAssignedPartitions() ) { $this->stopConsuming(); } } if (! in_array($message->err, self::IGNORABLE_CONSUMER_ERRORS, true)) { $this->logger->error($message, null, 'CONSUMER'); throw new ConsumerException($message->errstr(), $message->err); } } /** * Marks the partition which emitted the given EOF message as drained and * checks whether all partitions currently assigned to this consumer * have reached EOF, meaning there are no more messages to read. */ private function allAssignedPartitionsReachedEof(Message $message): bool { $this->partitionsAtEof[$this->partitionKey($message->topic_name, $message->partition)] = true; return collect($this->consumer->getAssignment())->every( fn (TopicPartition $partition) => isset($this->partitionsAtEof[$this->partitionKey($partition->getTopic(), $partition->getPartition())]) ); } /** * Joining a consumer group and getting partitions assigned may take longer than the * consumer timeout, so a timeout received before that only means the consumer is * not reading from any partition yet, and not that there are no messages left. */ private function hasAssignedPartitions(): bool { return $this->consumer->getAssignment() !== []; } private function partitionKey(string $topic, int $partition): string { return $topic.'-'.$partition; } private function getConsumerMessage(Message $message): ConsumerMessage { // First, we set a new unique id that allows us to identify this message. Then // we create a new consumer message instance that will be passed as an arg // to the consumer class/closure responsible for consuming this message. if (! array_key_exists(config('kafka.message_id_key'), $message->headers ?? [])) { $message->headers[config('kafka.message_id_key')] = Str::uuid()->toString(); } return app(ConsumerMessage::class, [ 'topicName' => $message->topic_name, 'partition' => $message->partition, 'headers' => $message->headers ?? [], 'body' => $message->payload, 'key' => $message->key, 'offset' => $message->offset, 'timestamp' => $message->timestamp, ]); } /** * Normalizes context array to key => value pairs for headers. * Ignores entries with empty keys and non string keys or values. */ private function normalizeContext(array $context): array { return array_filter( $context, fn (mixed $value, string $key) => $key !== '' && is_string($value), ARRAY_FILTER_USE_BOTH ); } }