Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/journal/0.1.x/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ One line per task, in the order of work:
- [x] [040 Metadata timer: interval and log](040-metadata-timer-details.md) — [6171caf](https://github.com/thesis-php/kafka/commit/6171caf)
- [x] [010 Varint and int64 without copies](010-varint-decoding.md) — [e3a9669](https://github.com/thesis-php/kafka/commit/e3a9669)
- [x] [011 Retriable errors and leader change](011-retriable-errors.md) — [01d14e0](https://github.com/thesis-php/kafka/commit/01d14e0)
- [ ] [012 Generator: client versions and null structs](012-generator-client-versions.md)
- [x] [012 Generator: client versions and null structs](012-generator-client-versions.md) — [9592309](https://github.com/thesis-php/kafka/commit/9592309)
- [ ] 016 Producer shutdown
- [ ] 017 Producer concurrency
- [ ] 018 Idempotent producer after a failed batch
Expand Down
77 changes: 73 additions & 4 deletions generator/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,28 @@
'records' => 1,
];

/**
* The last request version that a client may use, by API key name.
* Later versions are for brokers only. The schemas say it only in
* comments, so the numbers come from the Java client
* (LAST_CLIENT_VERSION in its request classes).
* Check this list after `make sync-schemas`.
*/
private const array LAST_CLIENT_VERSIONS = [
'AddPartitionsToTxn' => 3,
];

private TreeMapper $mapper;

/**
* @param array<non-empty-string, non-negative-int> $lastClientVersions
*/
public function __construct(
private Writer $fs,
private Generator\NamespaceGenerator $protocolNs,
private Generator\NamespaceGenerator $generatedNs,
?TreeMapper $mapper = null,
private array $lastClientVersions = self::LAST_CLIENT_VERSIONS,
) {
$this->mapper = $mapper ?? new MapperBuilder()
->allowSuperfluousKeys()
Expand Down Expand Up @@ -99,7 +114,7 @@ public function generate(SchemaSource $input): void
name: $name,
value: $message->apiKey,
min: $message->validVersions->min,
max: $message->validVersions->max,
max: $this->lastClientVersion($name, $message),
flexibleVersions: $message->flexibleVersions,
listeners: $listenersForKey,
));
Expand All @@ -115,10 +130,50 @@ public function generate(SchemaSource $input): void
}
}

foreach (array_keys($this->lastClientVersions) as $name) {
if (!array_any($apiKeys->keys, static fn(Schema\ApiKey $key) => $key->name === $name)) {
throw new \LogicException("The last client version is set for API key '{$name}', but no request schema has this API key.");
}
}

$this->generateListener(array_keys($listeners));
$this->generateApiKey($apiKeys);
}

/**
* @param non-empty-string $name
* @return non-negative-int
*/
private function lastClientVersion(string $name, Schema\Message $request): int
{
$min = $request->validVersions->min;
$max = $request->validVersions->max;
\assert($min !== null && $max !== null);

$last = $max;

// A broker does not offer an unstable version by default, and the Java client does not use it.
if ($request->latestVersionUnstable) {
if ($max <= $min) {
throw new \LogicException("API key '{$name}' has only one valid version, and it is unstable.");
}

$last = $max - 1;
}

if (isset($this->lastClientVersions[$name])) {
$lastClientVersion = $this->lastClientVersions[$name];

if ($lastClientVersion < $min || $lastClientVersion > $max) {
throw new \LogicException("The last client version {$lastClientVersion} of API key '{$name}' is outside of its valid versions {$min}-{$max}.");
}

$last = min($last, $lastClientVersion);
}

return $last;
}

private function generateRequestInterface(): void
{
$interface = new InterfaceType('Request')
Expand Down Expand Up @@ -727,6 +782,13 @@ private static function taggedFields(array $fields): array
static fn(Schema\Field $field): bool => !$field->taggedVersions->isNone(),
);

foreach ($tagged as $field) {
// Kafka uses another null marker for a struct in a tagged field. No schema needs it yet.
if (self::isStruct($field->type) && !$field->nullableVersions->intersect($field->taggedVersions)->isNone()) {
throw new \LogicException("Field '{$field->name}' is a nullable struct in a tagged field. The generator does not support it.");
}
}

usort(
$tagged,
static fn(Schema\Field $left, Schema\Field $right): int => ($left->tag ?? -1) <=> ($right->tag ?? -1),
Expand Down Expand Up @@ -1275,8 +1337,9 @@ private static function emitStructWrite(
];
}

// Kafka writes -1 before a null struct and 1 before a present one.
$nullable = static fn(Expr $v): array => [
Ast::stmt(Ast::call($ctx->writer, 'writeBool', Ast::neq($v, Ast::null()))),
Ast::stmt(Ast::call($ctx->writer, 'writeInt8', Ast::ternary(Ast::eq($v, Ast::null()), Ast::int(-1), Ast::int(1)))),
Ast::stmt(Ast::nullsafeCall($v, 'encode', $ctx->writer, Ast::var('version'))),
];

Expand Down Expand Up @@ -1465,10 +1528,11 @@ private static function emitStructRead(
$nullable = static fn(string $targetVar): array => [
Ast::assign(
Ast::var($targetVar),
// Kafka reads any negative marker as null.
Ast::ternary(
Ast::call($ctx->reader, 'readBool'),
Ast::staticCall($structRef, 'decode', $ctx->reader, Ast::var('version')),
Ast::lt(Ast::call($ctx->reader, 'readInt8'), Ast::int(0)),
Ast::null(),
Ast::staticCall($structRef, 'decode', $ctx->reader, Ast::var('version')),
),
),
];
Expand Down Expand Up @@ -1811,6 +1875,11 @@ private function usesUuidFactory(array $fields, Schema\VersionRange $containerVe
return false;
}

private static function isStruct(string $type): bool
{
return !str_starts_with($type, '[]') && !isset(self::SCALARS[$type]) && !isset(self::PREFIXED[$type]);
}

/**
* @param non-empty-string $listener
* @return non-empty-string
Expand Down
1 change: 1 addition & 0 deletions generator/Schema/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public function __construct(
public Type $type,
public string $name,
public VersionRange $validVersions = new VersionRange(),
public bool $latestVersionUnstable = false,
public VersionRange $flexibleVersions = new VersionRange(),
public ?int $apiKey = null,
public array $listeners = [],
Expand Down
8 changes: 4 additions & 4 deletions src/Protocol/Generated/ApiKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,7 @@ public function clientVersionRange(): VersionRange
self::OffsetCommit => new VersionRange(2, 10),
self::OffsetFetch => new VersionRange(1, 10),
self::FindCoordinator,
self::DescribeGroups,
self::InitProducerId => new VersionRange(0, 6),
self::DescribeGroups => new VersionRange(0, 6),
self::JoinGroup => new VersionRange(0, 9),
self::Heartbeat,
self::ApiVersions,
Expand All @@ -225,7 +224,7 @@ public function clientVersionRange(): VersionRange
self::LeaveGroup,
self::SyncGroup,
self::ListGroups,
self::AddPartitionsToTxn,
self::InitProducerId,
self::EndTxn,
self::TxnOffsetCommit => new VersionRange(0, 5),
self::SaslHandshake,
Expand Down Expand Up @@ -257,6 +256,8 @@ public function clientVersionRange(): VersionRange
self::DescribeCluster,
self::ListTransactions => new VersionRange(0, 2),
self::OffsetForLeaderEpoch => new VersionRange(2, 4),
self::AddPartitionsToTxn,
self::CreatePartitions => new VersionRange(0, 3),
self::WriteTxnMarkers,
self::AlterReplicaLogDirs,
self::RenewDelegationToken,
Expand All @@ -270,7 +271,6 @@ public function clientVersionRange(): VersionRange
self::DescribeDelegationToken => new VersionRange(1, 3),
self::DescribeConfigs,
self::DescribeLogDirs => new VersionRange(1, 4),
self::CreatePartitions => new VersionRange(0, 3),
self::ListPartitionReassignments,
self::OffsetDelete,
self::DescribeUserScramCredentials,
Expand Down
2 changes: 1 addition & 1 deletion src/Protocol/Generated/ConsumerGroupHeartbeatResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static function decode(Reader $reader, int $version): static
$memberId = $reader->readCompactNullableString();
$memberEpoch = $reader->readInt32();
$heartbeatIntervalMs = $reader->readInt32();
$assignment = $reader->readBool() ? ConsumerGroupHeartbeatResponse\Assignment::decode($reader, $version) : null;
$assignment = $reader->readInt8() < 0 ? null : ConsumerGroupHeartbeatResponse\Assignment::decode($reader, $version);
$unknownTags = $reader->readTaggedFields();
return new self($throttleTimeMs, $errorCode, $errorMessage, $memberId, $memberEpoch, $heartbeatIntervalMs, $assignment, $unknownTags);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Protocol/Generated/DescribeTopicPartitionsRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function encode(Writer $writer, int $version): void
$item->encode($writer, $version);
}
$writer->writeInt32($this->responsePartitionLimit);
$writer->writeBool($this->cursor !== null);
$writer->writeInt8($this->cursor === null ? -1 : 1);
$this->cursor?->encode($writer, $version);
$writer->writeTaggedFields($this->unknownTags);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Protocol/Generated/DescribeTopicPartitionsResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static function decode(Reader $reader, int $version): static
$item = DescribeTopicPartitionsResponse\DescribeTopicPartitionsResponseTopic::decode($reader, $version);
$topics[] = $item;
}
$nextCursor = $reader->readBool() ? DescribeTopicPartitionsResponse\Cursor::decode($reader, $version) : null;
$nextCursor = $reader->readInt8() < 0 ? null : DescribeTopicPartitionsResponse\Cursor::decode($reader, $version);
$unknownTags = $reader->readTaggedFields();
return new self($throttleTimeMs, $topics, $nextCursor, $unknownTags);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Protocol/Generated/ShareGroupHeartbeatResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static function decode(Reader $reader, int $version): static
$memberId = $reader->readCompactNullableString();
$memberEpoch = $reader->readInt32();
$heartbeatIntervalMs = $reader->readInt32();
$assignment = $reader->readBool() ? ShareGroupHeartbeatResponse\Assignment::decode($reader, $version) : null;
$assignment = $reader->readInt8() < 0 ? null : ShareGroupHeartbeatResponse\Assignment::decode($reader, $version);
$unknownTags = $reader->readTaggedFields();
return new self($throttleTimeMs, $errorCode, $errorMessage, $memberId, $memberEpoch, $heartbeatIntervalMs, $assignment, $unknownTags);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function encode(Writer $writer, int $version): void
$writer->writeCompactString($this->groupState);
$writer->writeInt32($this->groupEpoch);
$writer->writeInt32($this->assignmentEpoch);
$writer->writeBool($this->topology !== null);
$writer->writeInt8($this->topology === null ? -1 : 1);
$this->topology?->encode($writer, $version);
$writer->writeCompactArrayLength(\count($this->members));
foreach ($this->members as $item) {
Expand All @@ -69,7 +69,7 @@ public static function decode(Reader $reader, int $version): static
$groupState = $reader->readCompactString();
$groupEpoch = $reader->readInt32();
$assignmentEpoch = $reader->readInt32();
$topology = $reader->readBool() ? DescribedGroup\Topology::decode($reader, $version) : null;
$topology = $reader->readInt8() < 0 ? null : DescribedGroup\Topology::decode($reader, $version);
$membersCount = $reader->readCompactArrayLength();
$members = [];
for ($membersIndex = 0; $membersIndex < $membersCount; ++$membersIndex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function encode(Writer $writer, int $version): void
$writer->writeCompactString($this->clientHost);
$writer->writeInt32($this->topologyEpoch);
$writer->writeCompactString($this->processId);
$writer->writeBool($this->userEndpoint !== null);
$writer->writeInt8($this->userEndpoint === null ? -1 : 1);
$this->userEndpoint?->encode($writer, $version);
$writer->writeCompactArrayLength(\count($this->clientTags));
foreach ($this->clientTags as $item) {
Expand Down Expand Up @@ -99,7 +99,7 @@ public static function decode(Reader $reader, int $version): static
$clientHost = $reader->readCompactString();
$topologyEpoch = $reader->readInt32();
$processId = $reader->readCompactString();
$userEndpoint = $reader->readBool() ? Endpoint::decode($reader, $version) : null;
$userEndpoint = $reader->readInt8() < 0 ? null : Endpoint::decode($reader, $version);
$clientTagsCount = $reader->readCompactArrayLength();
$clientTags = [];
for ($clientTagsIndex = 0; $clientTagsIndex < $clientTagsCount; ++$clientTagsIndex) {
Expand Down
4 changes: 2 additions & 2 deletions src/Protocol/Generated/StreamsGroupHeartbeatRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function encode(Writer $writer, int $version): void
$writer->writeCompactNullableString($this->instanceId);
$writer->writeCompactNullableString($this->rackId);
$writer->writeInt32($this->rebalanceTimeoutMs);
$writer->writeBool($this->topology !== null);
$writer->writeInt8($this->topology === null ? -1 : 1);
$this->topology?->encode($writer, $version);
$writer->writeCompactNullableArrayLength($this->activeTasks === null ? null : \count($this->activeTasks));
if ($this->activeTasks !== null) {
Expand All @@ -98,7 +98,7 @@ public function encode(Writer $writer, int $version): void
}
}
$writer->writeCompactNullableString($this->processId);
$writer->writeBool($this->userEndpoint !== null);
$writer->writeInt8($this->userEndpoint === null ? -1 : 1);
$this->userEndpoint?->encode($writer, $version);
$writer->writeCompactNullableArrayLength($this->clientTags === null ? null : \count($this->clientTags));
if ($this->clientTags !== null) {
Expand Down
22 changes: 22 additions & 0 deletions tests/ClientVersionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Thesis\Kafka;

use Testo\Assert;
use Testo\Test;
use Thesis\Kafka\Protocol\Generated\ApiKey;
use Thesis\Kafka\Testing\Kafka;

final readonly class ClientVersionsTest
{
#[Test]
public function clientDoesNotChooseBrokerOnlyOrUnstableVersions(): void
{
Kafka::connect(...Kafka::KAFKA_4_SEEDS)->test(static function (Kafka $kafka): void {
Assert::same($kafka->negotiatedVersion(ApiKey::AddPartitionsToTxn), 3);
Assert::int($kafka->negotiatedVersion(ApiKey::InitProducerId) ?? -1)->between(0, 5);
});
}
}
Loading