|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ensi\LaravelPhpRdKafkaConsumer\Commands; |
| 4 | + |
| 5 | +use Ensi\LaravelPhpRdKafkaConsumer\HighLevelConsumer; |
| 6 | +use Illuminate\Console\Command; |
| 7 | +use RdKafka\Exception as RdKafkaException; |
| 8 | + |
| 9 | +class KafkaSetOffset extends Command |
| 10 | +{ |
| 11 | + public const EARLIEST = 'earliest'; |
| 12 | + public const LATEST = 'latest'; |
| 13 | + |
| 14 | + protected $signature = 'kafka:set-offset |
| 15 | + {--consumer= : name of consumer} |
| 16 | + {--topic= : name of topic} |
| 17 | + {--partition= : id of partition} |
| 18 | + {--offset= : desired offset, "earliest", "latest" or positive integer}'; |
| 19 | + protected $description = "Задать смещение для консюмера в топике"; |
| 20 | + |
| 21 | + public function handle() |
| 22 | + { |
| 23 | + $consumerName = $this->option('consumer'); |
| 24 | + $topicName = $this->option('topic'); |
| 25 | + $partitionId = $this->option('partition'); |
| 26 | + $offset = $this->option('offset'); |
| 27 | + |
| 28 | + if (!in_array($offset, [self::EARLIEST, self::LATEST]) && !is_numeric($offset)) { |
| 29 | + $this->getOutput()->writeln("<fg=red>Error: Invalid offset</>"); |
| 30 | + return self::INVALID; |
| 31 | + } |
| 32 | + |
| 33 | + /** @var HighLevelConsumer $consumer */ |
| 34 | + $consumer = resolve(HighLevelConsumer::class); |
| 35 | + $consumer->for($consumerName); |
| 36 | + |
| 37 | + try { |
| 38 | + $bounds = $consumer->getPartitionBounds($topicName, $partitionId); |
| 39 | + $realOffset = match($offset) { |
| 40 | + 'earliest' => $bounds[0] ?? 0, |
| 41 | + 'latest' => $bounds[1] ?? 0, |
| 42 | + default => $offset, |
| 43 | + }; |
| 44 | + |
| 45 | + if ($offset != $realOffset) { |
| 46 | + $this->getOutput()->writeln("<fg=yellow>Use {$offset} offset:</> {$realOffset}"); |
| 47 | + } |
| 48 | + |
| 49 | + $consumer->setOffset($topicName, $partitionId, $realOffset); |
| 50 | + } catch (RdKafkaException $e) { |
| 51 | + $this->getOutput()->writeln("<fg=red>Error: {$e->getMessage()}</>"); |
| 52 | + |
| 53 | + return self::INVALID; |
| 54 | + } |
| 55 | + $this->getOutput()->writeln("<fg=green>Success</>"); |
| 56 | + |
| 57 | + return self::SUCCESS; |
| 58 | + } |
| 59 | +} |
0 commit comments