You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by gk...@apache.org on 2026/10/21 19:42:35 UTC
(iggy) branch master updated: feat(gateways): serve Kafka IncrementalAlterConfigs (key 44) (#4572)
This is an automated email from the ASF dual-hosted git repository.
numinnex pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iggy.git
The following commit(s) were added to refs/heads/master by this push:
new 67e3a3c78 feat(gateways): serve Kafka IncrementalAlterConfigs (key 44) (#4572)
67e3a3c78 is described below
commit 67e3a3c7882b68ec5c5c9591c558bb291523f536
Author: Grzegorz Koszyk <11...@users.noreply.github.com>
AuthorDate: Wed Oct 21 21:42:30 2026 +0200
feat(gateways): serve Kafka IncrementalAlterConfigs (key 44) (#4572)
Closes #4509
---
.config/nextest.toml | 1 +
gateways/kafka/README.md | 58 +--
gateways/kafka/docs/CONFIGS.md | 100 ++--
gateways/kafka/docs/MANUAL_TESTING.md | 6 +-
gateways/kafka/docs/SCOPE.md | 18 +-
gateways/kafka/scripts/ci-wire-fixtures.sh | 2 +-
gateways/kafka/src/protocol/api.rs | 14 +-
gateways/kafka/src/protocol/bounds_guard.rs | 82 ++++
.../kafka/src/protocol/handlers/alter_configs.rs | 53 ++-
...ter_configs.rs => incremental_alter_configs.rs} | 216 +++++----
gateways/kafka/src/protocol/handlers/mod.rs | 14 +-
.../kafka/src/protocol/handlers/topic_config.rs | 348 +++++++++++++-
gateways/kafka/tests/common/scope.rs | 1 +
gateways/kafka/tests/common/wire.rs | 22 +-
gateways/kafka/tests/configs_handler_tests.rs | 127 +++++-
gateways/kafka/tests/configs_java_client_tests.rs | 9 +
gateways/kafka/tests/configs_real_bridge_tests.rs | 506 ++++++++++++++++++++-
gateways/kafka/tests/golden_wire_fixtures_tests.rs | 14 +-
gateways/kafka/tests/java/ConfigsProbe.java | 34 +-
gateways/kafka/tests/kafka_client_e2e_tests.rs | 92 ++++
gateways/kafka/tests/version_firewall_tests.rs | 62 ++-
gateways/kafka/tools/kafka-tool/README.md | 4 +-
gateways/kafka/tools/kafka-tool/src/main.rs | 19 +
23 files changed, 1565 insertions(+), 237 deletions(-)
diff --git a/.config/nextest.toml b/.config/nextest.toml
index 84d05f8c6..80f54f749 100644
--- a/.config/nextest.toml
+++ b/.config/nextest.toml
@@ -63,6 +63,7 @@ filter = '''
+ binary_id(iggy-gateway-kafka::fetch_real_bridge_tests)
+ binary_id(iggy-gateway-kafka::list_offsets_real_bridge_tests)
+ binary_id(iggy-gateway-kafka::produce_real_bridge_tests)
+ + binary_id(iggy-gateway-kafka::configs_real_bridge_tests)
+ binary_id(iggy-gateway-kafka::create_topics_real_bridge_tests)
+ binary_id(iggy-gateway-kafka::delete_topics_real_bridge_tests)
+ binary_id(iggy-gateway-kafka::create_partitions_real_bridge_tests)
diff --git a/gateways/kafka/README.md b/gateways/kafka/README.md
index 8f9ec2b6f..35cb7eed2 100644
--- a/gateways/kafka/README.md
+++ b/gateways/kafka/README.md
@@ -1,28 +1,29 @@
# Kafka gateway (`iggy-gateway-kafka`)
-Foundation layer for [apache/iggy#3421](https://github.com/apache/iggy/issues/3421): a TCP listener on the Kafka wire port that decodes requests and validates scoped API keys and versions. With a bridge, Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs use Iggy. InitProducerId and consumer group coordination work with or without one.
+Foundation layer for [apache/iggy#3421](https://github.com/apache/iggy/issues/3421): a TCP listener on the Kafka wire port that decodes requests and validates scoped API keys and versions. With a bridge, Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and IncrementalAlterConfigs use Iggy. InitProducerId and consumer group coordination work with or without one.
> **Stub warning:** with `IGGY_KAFKA_BRIDGE_ENABLED=true`, Produce, Fetch, ListOffsets, Metadata,
-> CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs use Iggy. With
-> the bridge off (the default), those nine are stubs: Produce, Fetch and ListOffsets answer
-> retriable `NOT_LEADER_OR_FOLLOWER` (6), CreateTopics, DeleteTopics, CreatePartitions,
-> DescribeConfigs and AlterConfigs answer `NOT_CONTROLLER` (41), and Metadata reports every
-> requested topic unknown. **CreateTopics, DeleteTopics, CreatePartitions and AlterConfigs run as
-> the bridge's own Iggy user**: with the bridge on and `IGGY_KAFKA_SASL_ENABLED` off (the
-> default), any client that can reach this port can create topics (up to 1000 partitions each),
-> grow them by up to 1000 partitions per topic per request (100 topics per request), delete
-> topics and their data, or shorten a topic's `retention.ms` low enough that the cleaner drops
-> sealed segments, deleting data. With `IGGY_KAFKA_AUTO_CREATE_TOPICS_ENABLED=true` and no
-> listener that names principals, any client that reaches this port can also create topics just
-> by naming them in a `Metadata` request. When the connection has a principal (SASL, or a client
-> certificate mapped to an Iggy user), `DeleteTopics`, `CreatePartitions`, `AlterConfigs` and
-> `Metadata` auto-creation additionally require it to hold a global `manage_topics` or
-> `manage_streams`; without it every resource of a `DeleteTopics`, `CreatePartitions` or
-> `AlterConfigs` request, and every missing topic a `Metadata` request would create, fails
-> `TOPIC_AUTHORIZATION_FAILED` (29) and nothing is written, created or deleted. `CreateTopics` has
-> no such gate yet - SASL on does not protect it. Every client reads and writes as the bridge's
-> Iggy user. Iggy's `metadata.partitions_max` defaults to 0 (unlimited), so set it before exposing
-> the gateway. See [docs/SCOPE.md](docs/SCOPE.md).
+> CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and
+> IncrementalAlterConfigs use Iggy. With the bridge off (the default), those ten are stubs:
+> Produce, Fetch and ListOffsets answer retriable `NOT_LEADER_OR_FOLLOWER` (6), CreateTopics,
+> DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and IncrementalAlterConfigs answer
+> `NOT_CONTROLLER` (41), and Metadata reports every requested topic unknown. **CreateTopics,
+> DeleteTopics, CreatePartitions and both alter APIs run as the bridge's own Iggy user**: with the
+> bridge on and `IGGY_KAFKA_SASL_ENABLED` off (the default), any client that can reach this port
+> can create topics (up to 1000 partitions each), grow them by up to 1000 partitions per topic per
+> request (100 topics per request), delete topics and their data, or shorten a topic's
+> `retention.ms` low enough that the cleaner drops sealed segments, deleting data. With
+> `IGGY_KAFKA_AUTO_CREATE_TOPICS_ENABLED=true` and no listener that names principals, any client
+> that reaches this port can also create topics just by naming them in a `Metadata` request. When
+> the connection has a principal (SASL, or a client certificate mapped to an Iggy user),
+> `DeleteTopics`, `CreatePartitions`, `AlterConfigs`, `IncrementalAlterConfigs` and `Metadata`
+> auto-creation additionally require it to hold a global `manage_topics` or `manage_streams`;
+> without it every resource of a `DeleteTopics`, `CreatePartitions`, `AlterConfigs` or
+> `IncrementalAlterConfigs` request, and every missing topic a `Metadata` request would create,
+> fails `TOPIC_AUTHORIZATION_FAILED` (29) and nothing is written, created or deleted.
+> `CreateTopics` has no such gate yet - SASL on does not protect it. Every client reads and writes
+> as the bridge's Iggy user. Iggy's `metadata.partitions_max` defaults to 0 (unlimited), so set it
+> before exposing the gateway. See [docs/SCOPE.md](docs/SCOPE.md).
>
> InitProducerId does real work too, with or without the bridge: it allocates a producer id, so a stock idempotent producer starts instead of failing at startup.
>
@@ -216,7 +217,7 @@ See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/is
- [docs/CONSUMER_GROUPS.md](docs/CONSUMER_GROUPS.md) — group membership, rebalances, and why one gateway per bootstrap endpoint
- [docs/AUTHENTICATION.md](docs/AUTHENTICATION.md) — how a Kafka client authenticates, and why PLAIN only
- [docs/ACL_MAPPING.md](docs/ACL_MAPPING.md) — how Iggy permissions are described as Kafka ACLs
-- [docs/CONFIGS.md](docs/CONFIGS.md) — DescribeConfigs and AlterConfigs for topic `retention.ms`
+- [docs/CONFIGS.md](docs/CONFIGS.md) — DescribeConfigs, AlterConfigs and IncrementalAlterConfigs for topic `retention.ms`
### Delivery guarantees
@@ -412,9 +413,9 @@ topic per call) and records by time for `ListOffsets`, probes and polls partitio
stores and reads group offsets for OffsetCommit and OffsetFetch.
Produce ([#3535](https://github.com/apache/iggy/issues/3535)), Fetch ([#3536](https://github.com/apache/iggy/issues/3536)), ListOffsets
([#3537](https://github.com/apache/iggy/issues/3537)), Metadata ([#3534](https://github.com/apache/iggy/issues/3534)), CreateTopics
-([#3538](https://github.com/apache/iggy/issues/3538)), DescribeConfigs and AlterConfigs , OffsetCommit and OffsetFetchcall it.
-Topic configuration behavior is in [docs/CONFIGS.md](docs/CONFIGS.md).
+([#3538](https://github.com/apache/iggy/issues/3538)), DescribeConfigs, AlterConfigs and IncrementalAlterConfigs, OffsetCommit and OffsetFetch
([#3542](https://github.com/apache/iggy/issues/3542)) call it.
+Topic configuration behavior is in [docs/CONFIGS.md](docs/CONFIGS.md).
Tested by `bridge`'s own unit tests, `tests/bridge_iggy_integration_tests.rs` and the
`tests/*_real_bridge_tests.rs` suites. All but the unit tests start a real `iggy-server`.
@@ -609,7 +610,7 @@ call created it." A *different* `partition_count` against an already-existing to
two concurrent callers requesting different counts for the same topic must not both see success.
Topics created this way have **no message expiry** - Iggy's own server default, not Kafka's 7-day
-default. `AlterConfigs` can set that expiry afterwards through `retention.ms`
+default. `AlterConfigs` or `IncrementalAlterConfigs` can set that expiry afterwards through `retention.ms`
([docs/CONFIGS.md](docs/CONFIGS.md)). Until a client does, messages never expire, so a Kafka app
that assumes the 7-day default will accumulate data on this bridge.
@@ -702,9 +703,10 @@ With auto-creation off, the default, nothing changes: a missing topic is answere
other closes after `IGGY_KAFKA_PRODUCE_SESSION_IDLE_SECS` (600) unused, checked every 30 s.
- 4 clients sign in at once, 80 a second at most. More wait, up to their request's deadline.
- `IGGY_KAFKA_PRODUCE_SESSIONS=0`: all producers share one client, one request at a time.
-- Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs share
- 1 more client, one Iggy request at a time. Fetch polls use 4 more, one per read slot, and a
- `ListOffsets` lookup by time borrows one of those slots for its request. Topic probes use 1
+- Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and
+ IncrementalAlterConfigs share 1 more client, one Iggy request at a time. Fetch polls use 4
+ more, one per read slot, and a `ListOffsets` lookup by time borrows one of those slots for its
+ request. Topic probes use 1
more. With auto topic creation on, creations use 1 more, opened at the first one.
Offset calls use 8 more: a commit client and a read client per offset slot.
- CreateTopics, DeleteTopics and CreatePartitions writes also take one gateway-wide lock, so a
diff --git a/gateways/kafka/docs/CONFIGS.md b/gateways/kafka/docs/CONFIGS.md
index 8dd1a3f4d..b37c1c4b1 100644
--- a/gateways/kafka/docs/CONFIGS.md
+++ b/gateways/kafka/docs/CONFIGS.md
@@ -1,25 +1,25 @@
# Topic configuration
-`DescribeConfigs` (32) and `AlterConfigs` (33) apply to Kafka topic resources only
-(resource type 2). Only the deprecated `Admin.alterConfigs` (API 33) writes
-retention. `IncrementalAlterConfigs` (44) is not in this change and is not
-advertised in `ApiVersions`. A client picks its admin API from that response, so
-a Java or librdkafka client that would otherwise send 44 raises an
-`UnsupportedVersionException` (or the librdkafka equivalent) locally and never
-sends the request - the gateway never sees it, and the connection is not
-affected. Only `AlterConfigs` (33) writes retention.
-
-With the bridge off, both APIs answer `NOT_CONTROLLER` (41) for each resource and
-do not read or write Iggy.
+`DescribeConfigs` (32), `AlterConfigs` (33) and `IncrementalAlterConfigs` (44)
+apply to Kafka topic resources only (resource type 2). Both alter APIs write the
+same single value, `retention.ms`. `kafka-configs --alter` on a topic has sent
+API 44 since Kafka 2.5. Java `Admin.incrementalAlterConfigs` (the only alter
+method left in Kafka 4.0), MirrorMaker 2's configuration sync and kafka-ui also
+send API 44. API 33 comes from Java `Admin.alterConfigs` on clients older than
+4.0 and from other clients' non-incremental alter calls, such as librdkafka's
+`rd_kafka_AlterConfigs`.
+
+With the bridge off, all three APIs answer `NOT_CONTROLLER` (41) for each resource
+and do not read or write Iggy.
## Authorization
-`AlterConfigs` requires the `manage_topics` (or `manage_streams`) Iggy permission
-on the authenticated principal when SASL is enabled. A principal without it gets
-`TOPIC_AUTHORIZATION_FAILED` (29) for every resource in the request, and
-`update_topic` is never called. With SASL disabled there is no principal to
-check, and the request is not gated here. `DescribeConfigs` performs no
-authorization check of its own.
+`AlterConfigs` and `IncrementalAlterConfigs` require the `manage_topics` (or
+`manage_streams`) Iggy permission on the authenticated principal when SASL is
+enabled. A principal without it gets `TOPIC_AUTHORIZATION_FAILED` (29) for every
+resource in the request, and `update_topic` is never called. With SASL disabled
+there is no principal to check, and the request is not gated here.
+`DescribeConfigs` performs no authorization check of its own.
## What a describe returns
@@ -90,28 +90,74 @@ resources in the same request are still processed.
`validate_only` runs the same checks, including the topic lookup, and does not
call `update_topic`.
+## What an incremental alter does
+
+`IncrementalAlterConfigs` (44) carries one operation per entry instead of a whole
+new set. The entries of one resource are applied together, and the result is the
+same single write as `AlterConfigs`: `retention.ms` onto `message_expiry`.
+
+| Operation | `retention.ms` | `cleanup.policy` | Any other key |
+| --------- | -------------- | ---------------- | ------------- |
+| `SET` (0) | Stored, with the checks listed under "What an alter stores" | `INVALID_CONFIG` (40), read-only | `INVALID_CONFIG` (40), unknown key |
+| `DELETE` (1) | Stores never expire, the value a topic has before any alter. The value sent with the delete is ignored; `kafka-configs --delete-config` sends an empty string | No-op, `NONE` (0) | No-op, `NONE` (0) |
+| `APPEND` (2), `SUBTRACT` (3) | `INVALID_CONFIG` (40), `Can't APPEND to key retention.ms because its type is not LIST.` | `INVALID_CONFIG` (40), read-only | `INVALID_CONFIG` (40), not a list |
+
+A delete of a key other than `retention.ms` succeeds without writing, because
+Kafka removes an override there and this gateway never stored one. An empty
+operation list is a no-op, not a reset, and answers `NONE` (0) once the topic
+lookup succeeds.
+
+Three request faults are answered `INVALID_REQUEST` (42) before the topic lookup
+and without any Iggy call: a config name that appears twice in one resource
+(`Error due to duplicate config keys`), a null value on anything but a `DELETE`
+(`Null value not supported for : <names>`), and an operation byte outside 0-3
+(`Unknown operations type <n>`). The first two texts are Kafka's own. The third is
+borrowed from Kafka's broker-resource check, because Kafka's topic path has no
+well-formed answer for an unknown operation. A topic named by more than one
+resource gets `INVALID_REQUEST` (42) on every occurrence, with
+`Each resource must appear at most once.`
+
+The order of checks is: authorization, the topic cap, the resource type, the
+topic name, the request faults, the topic lookup, then the config faults. A
+missing topic is `UNKNOWN_TOPIC_OR_PARTITION` (3) for an entry that would also be
+`INVALID_CONFIG`, as with `AlterConfigs`. Kafka orders these checks differently;
+see "Limitations".
+
+`validate_only` runs every check, including the topic lookup, and writes nothing.
+
## Limitations
-- `IncrementalAlterConfigs` (API 44) is not implemented and is not
- advertised. No client falls back to `AlterConfigs` (33) on its own. The Java
- client and librdkafka fail locally, as the top of this page says. Kafka 4.0
- removed `Admin.alterConfigs`, and `kafka-configs --alter` sends only API 44.
- A Java 4.x client or tool therefore cannot change `retention.ms` through this
- gateway.
-- `retention.ms` remains the only value Iggy stores.
+- `retention.ms` remains the only value Iggy stores, through either alter API.
+- A `DELETE` of `retention.ms` stores never expire instead of removing the entry.
+ Iggy marks any value a client sent as explicit, so a later describe reports
+ `-1` from `DYNAMIC_TOPIC_CONFIG` (1), where Kafka would report its broker
+ default from `DEFAULT_CONFIG` (5). A topic that was never altered is written
+ too, so its describe source flips from `DEFAULT_CONFIG` (5) to
+ `DYNAMIC_TOPIC_CONFIG` (1) although the value stays `-1`; Kafka writes nothing
+ there. `kafka-configs --delete-config retention.ms` on such a topic fails on
+ the client side before any request, as it does against Kafka, because the tool
+ first describes the topic's dynamic configs. After any alter, a repeated delete
+ always succeeds.
+- Kafka validates the configuration before it checks that the topic exists, and
+ checks duplicate names and null values before the topic name. This gateway
+ looks the topic up first, so a missing topic with a bad entry answers
+ `UNKNOWN_TOPIC_OR_PARTITION` (3) where Kafka answers `INVALID_CONFIG` (40).
+ `AlterConfigs` checks in the same order.
- `cleanup.policy` is not reported. See "What a describe returns".
## Other resource errors
| Condition | Code | Notes |
| --------- | ---- | ----- |
-| Caller lacks `manage_topics` (SASL on, `AlterConfigs` only) | `TOPIC_AUTHORIZATION_FAILED` (29) | Checked before the topic lookup. Every resource in the request |
+| Caller lacks `manage_topics` (SASL on, both alter APIs) | `TOPIC_AUTHORIZATION_FAILED` (29) | Checked before the topic lookup. Every resource in the request |
| Resource type other than topic | `INVALID_REQUEST` (42) | Message is `only topic resources are supported`. Other resources in the batch still run |
| Topic name fails the same rules as CreateTopics | `INVALID_TOPIC_EXCEPTION` (17) | The message is the validation reason and does not repeat the topic name |
| Topic does not exist | `UNKNOWN_TOPIC_OR_PARTITION` (3) | Checked before config keys, so a missing topic is not `INVALID_CONFIG` |
-| Empty `configs` list on alter | `INVALID_CONFIG` (40) | Kafka would replace the set, which is a reset. This gateway patches named keys, so an empty list is rejected and writes nothing |
+| Empty `configs` list on `AlterConfigs` | `INVALID_CONFIG` (40) | Kafka would replace the set, which is a reset. This gateway patches named keys, so an empty list is rejected and writes nothing. On `IncrementalAlterConfigs` an empty list is a no-op |
+| Duplicate config name, null value, or unknown operation on `IncrementalAlterConfigs` | `INVALID_REQUEST` (42) | Message text under "What an incremental alter does". Checked before the topic lookup, so a missing topic gets this code too |
+| `APPEND` or `SUBTRACT` on `IncrementalAlterConfigs` | `INVALID_CONFIG` (40) | `retention.ms` is not a list, and `cleanup.policy` is read-only here. Checked after the topic lookup |
| More than 100 distinct topic names | `POLICY_VIOLATION` (44) | Every resource in the request, checked before the bridge-availability check |
-| A topic name repeated across resources | `INVALID_REQUEST` (42) | Every occurrence of the duplicate, not just the second one. Same choice CreateTopics makes for a repeated topic name |
+| A topic name repeated across resources | `INVALID_REQUEST` (42) | Every occurrence of the duplicate, not just the second one. Same choice CreateTopics makes for a repeated topic name. `IncrementalAlterConfigs` adds Kafka's message, `Each resource must appear at most once.` |
Unknown tagged fields at the request, resource, or config-entry level are
ignored, not rejected: Kafka's flexible versions define them as a forward-compatible
diff --git a/gateways/kafka/docs/MANUAL_TESTING.md b/gateways/kafka/docs/MANUAL_TESTING.md
index 13cbcebcc..bc143a4ee 100644
--- a/gateways/kafka/docs/MANUAL_TESTING.md
+++ b/gateways/kafka/docs/MANUAL_TESTING.md
@@ -360,13 +360,14 @@ For each API key, test **min−1**, **min**, **max**, **max+1** using `kafka-mes
| 32 | DescribeConfigs | 1 | 4 | 0, 1, 4, 5 |
| 33 | AlterConfigs | 0 | 2 | −1, 0, 2, 3 |
| 37 | CreatePartitions | 0 | 3 | −1, 0, 3, 4 |
+| 44 | IncrementalAlterConfigs | 0 | 1 | −1, 0, 1, 2 |
| ID | Test | Expected for in-range | Expected for out-of-range |
| ---- | ------ | ---------------------- | --------------------------- |
-| B1 | ApiVersions negotiation | `error_code=0`; body lists 14 API keys with correct min/max | KIP-511 exception: still answers, `error_code=35` (UNSUPPORTED_VERSION), v0 response header regardless of the request's own encoding |
+| B1 | ApiVersions negotiation | `error_code=0`; body lists 20 API keys with correct min/max (SASL off) | KIP-511 exception: still answers, `error_code=35` (UNSUPPORTED_VERSION), v0 response header regardless of the request's own encoding |
| B2 | Metadata out-of-range | N/A | **Connection closes**, no response sent - Metadata has no top-level error field to carry a version-correct error in |
| B3 | Produce/Fetch/ListOffsets/CreateTopics/DeleteTopics/CreatePartitions/InitProducerId/OffsetCommit/OffsetFetch out-of-range | N/A | **Connection closes** for both above-max and below-min - `kafka_protocol`'s schema floor for each of these nine messages equals `SUPPORTED_RANGES`' own min, so there is no encodable error response below min either (see `SCOPE.md`'s Governance model) |
-| B4 | ApiVersions lists only scoped keys | Decode response | Contains keys 0,1,2,3,8,9,10,11,12,13,14,15,16,18,19,20,22,32,33,37 only, and no transaction keys (24, 25, 26, 28) |
+| B4 | ApiVersions lists only scoped keys | Decode response | Contains keys 0,1,2,3,8,9,10,11,12,13,14,15,16,18,19,20,22,32,33,37,44 only, and no transaction keys (24, 25, 26, 28) |
An out-of-range version only ever produces `error_code=35` on ApiVersions (B1); every other API
key's out-of-range case closes the connection - see B2/B3. InitProducerId and Produce also send
@@ -461,6 +462,7 @@ success. This category predates the bridge landing: G2/G3's "fails at metadata"
| G13 | Describe members | `kafka-consumer-groups.sh --bootstrap-server 127.0.0.1:9093 --describe --members --group g2` | Prints member ids. Assignment and protocol are filled only while the group is Stable |
| G14 | Describe state | `kafka-consumer-groups.sh --bootstrap-server 127.0.0.1:9093 --describe --state --group g2` | Prints the state string (`Stable`, `PreparingRebalance`, `CompletingRebalance`, or `Empty`). The default `--describe` (no `--members` or `--state`) calls OffsetFetch and fails, because that API is not implemented |
| G15 | Grow a topic | Bridge on and topic `orders` made as in Category I. `kafka-topics.sh --bootstrap-server 127.0.0.1:9093 --alter --topic orders --partitions 3`, then `--describe --topic orders`, then `--alter --topic orders --partitions 2` | The describe prints `PartitionCount: 3`. The second alter fails with `InvalidPartitionsException` naming the current count, and a describe still prints 3. Automated in `kafka_client_e2e_tests.rs` |
+| G16 | Alter retention with `kafka-configs.sh` | Bridged, topic `orders` as in Category I. `kafka-configs.sh --bootstrap-server 127.0.0.1:9093 --alter --entity-type topics --entity-name orders --add-config retention.ms=8000`, then the same with `--describe`, then with `--delete-config retention.ms` | Sends IncrementalAlterConfigs (44) only. Each alter prints `Completed updating config for topic orders.`; describe shows `retention.ms=8000` after the add and `retention.ms=-1` after the delete |
Record kcat version and exact error strings in your test log. G1 passing is the minimum bar for client compatibility smoke.
diff --git a/gateways/kafka/docs/SCOPE.md b/gateways/kafka/docs/SCOPE.md
index dd0cf008d..6c5ecc0c2 100644
--- a/gateways/kafka/docs/SCOPE.md
+++ b/gateways/kafka/docs/SCOPE.md
@@ -2,13 +2,13 @@
## Issue #3421 — in scope (this iteration)
-A TCP listener on the Kafka wire port. It decodes requests, validates scoped API keys, versions and wire formats, and answers them. With a bridge, Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs use Iggy.
+A TCP listener on the Kafka wire port. It decodes requests, validates scoped API keys, versions and wire formats, and answers them. With a bridge, Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and IncrementalAlterConfigs use Iggy.
**Stub semantics (important):** without a bridge, every API answers with a stub. Produce discards
the payload and answers with retriable `NOT_LEADER_OR_FOLLOWER` (6). Fetch and ListOffsets answer 6
-too. CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs answer
-`NOT_CONTROLLER` (41), so clients do not believe a topic was created, deleted or grown, or that
-configs were read or changed.
+too. CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and
+IncrementalAlterConfigs answer `NOT_CONTROLLER` (41), so clients do not believe a topic was
+created, deleted or grown, or that configs were read or changed.
OffsetCommit and OffsetFetch answer retriable `COORDINATOR_LOAD_IN_PROGRESS`
(14). Do not read `ec=0` from a stub as durable storage. Produce is the one API that stores records
once you configure a bridge ([#3535](https://github.com/apache/iggy/issues/3535)).
@@ -36,7 +36,7 @@ Expand `SUPPORTED_RANGES` only after a key/version pair is manually tested. ApiV
**Every unsupported-version case closes the connection, for every listed key** - not just above
the encoder max. `kafka_protocol`'s schema floor for each supported message happens to equal
`SUPPORTED_RANGES`' own min today (Produce 3, Fetch 4, ListOffsets 1, Metadata 0, ApiVersions 0,
-CreateTopics 2, InitProducerId 0, OffsetCommit 2, OffsetFetch 1, DescribeConfigs 1, AlterConfigs 0, DescribeCluster 0, and 0 for the five group coordination keys, DescribeGroups and ListGroups), so there is no version below an API's
+CreateTopics 2, InitProducerId 0, OffsetCommit 2, OffsetFetch 1, DescribeConfigs 1, AlterConfigs 0, CreatePartitions 0, IncrementalAlterConfigs 0, DescribeCluster 0, and 0 for the five group coordination keys, DescribeGroups and ListGroups), so there is no version below an API's
min that the crate can actually encode a response for either - `unsupported_version_response`
still tries, but the encode attempt fails and the connection closes rather than sending a
malformed body.
@@ -70,6 +70,7 @@ it knows the server supports flexible encoding.
| 22 | InitProducerId | 0 | 5 | 0, 1, 2, 3, 4, 5 | Allocate a producer id (epoch 0); a `transactional_id` gets `UNSUPPORTED_VERSION` (35); flexible encoding at v2+ |
| 32 | DescribeConfigs | 1 | 4 | 1, 2, 3, 4 | Topic resources only. Returns `retention.ms` and leaves out `cleanup.policy`. Flexible encoding at v4. See [`CONFIGS.md`](CONFIGS.md) |
| 33 | AlterConfigs | 0 | 2 | 0, 1, 2 | Persists `retention.ms` only. Flexible encoding at v2. See [`CONFIGS.md`](CONFIGS.md) |
+| 44 | IncrementalAlterConfigs | 0 | 1 | 0, 1 | Persists `retention.ms` only, one operation per entry; `APPEND` and `SUBTRACT` are refused. Flexible encoding at v1. See [`CONFIGS.md`](CONFIGS.md) |
| 60 | DescribeCluster | 0 | 2 | 0, 1, 2 | The [cluster id](#cluster-id) and the broker Metadata advertises on the same listener. The controller endpoint type gets `MISMATCHED_ENDPOINT_TYPE` (114) and an unknown one `UNSUPPORTED_ENDPOINT_TYPE` (115). `cluster_authorized_operations` stays unset, so a Java client reads it as null. Flexible encoding at every version |
A request is accepted when `min_version ≤ api_version ≤ max_version` for that API key. Any other version for a listed key closes the connection (ApiVersions excepted - see Governance model above).
@@ -102,6 +103,7 @@ Use this table when configuring clients or generating wire fixtures with `kafka-
| 32 | DescribeConfigs | 1–4 | v4 |
| 33 | AlterConfigs | 0–2 | v2 |
| 37 | CreatePartitions | 0–3 | v2 |
+| 44 | IncrementalAlterConfigs | 0–1 | v1 |
| 60 | DescribeCluster | 0–2 | v0 |
### Cluster id
@@ -154,7 +156,7 @@ All API keys not listed above close the connection (see Governance model above)
| 29 | DescribeAcls | Implemented on listeners that name a principal: the SASL ones, and `SSL` with client certificates; advertised only there ([`ACL_MAPPING.md`](ACL_MAPPING.md)) |
| 36 | SaslAuthenticate | Implemented on `SASL_PLAINTEXT` and `SASL_SSL` listeners, advertised only there ([`AUTHENTICATION.md`](AUTHENTICATION.md)) |
| 24, 25, 26, 28 | AddPartitionsToTxn, AddOffsetsToTxn, EndTxn, TxnOffsetCommit | Transactions - not supported, see below |
-| 23, 27, 30, 31, 34, 35, 38+ | `OffsetForLeaderEpoch`, `WriteTxnMarkers`, `CreateAcls`/`DeleteAcls`, IncrementalAlterConfigs (44), etc. | Later issues |
+| 23, 27, 30, 31, 34, 35, 38 to 43, 45 to 59, 61+ | `OffsetForLeaderEpoch`, `WriteTxnMarkers`, `CreateAcls`/`DeleteAcls`, etc. | Later issues |
| 21 | DeleteRecords | Not advertised on purpose, see below |
| 68 | ConsumerGroupHeartbeat | KIP-848 protocol, opt-in via `group.protocol=consumer`; the 4.0 default is still `classic` |
@@ -217,8 +219,8 @@ nor moved by retention. That is the same core change the ListOffsets `EARLIEST`
| Layer | #3421 | Description |
| ------- | ------- | ------------- |
| **1 — Wire framing** | In scope | `server.rs` — custom, zero-copy frame I/O; `header.rs` delegates version selection to `kafka_protocol::messages::ApiKey` |
-| **2 — Request/response codecs** | Partial | Decode/encode via the `kafka_protocol` crate (broker feature only) for 20 keys; `bounds_guard.rs` pre-validates against unbounded allocation before handing a frame to the crate; stub responses except InitProducerId and the consumer-group keys, and Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs with a bridge |
-| **3 — Iggy bridge** | Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs and AlterConfigs wired | `bridge/` module (connection, topic mapping, provisioning, high watermark, `topic_target` + `send_records`, `probe` + `poll`). Produce ([#3535](https://github.com/apache/iggy/issues/3535)), Fetch ([#3536](https://github.com/apache/iggy/issues/3536)), ListOffsets ([#3537](https://github.com/apache/iggy/issues/3537)), Metadata ([#3534](https: [...]
+| **2 — Request/response codecs** | Partial | Decode/encode via the `kafka_protocol` crate (broker feature only) for 22 keys; `bounds_guard.rs` pre-validates against unbounded allocation before handing a frame to the crate; stub responses except InitProducerId and the consumer-group keys, and Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and IncrementalAlterConfigs with a bridge |
+| **3 — Iggy bridge** | Produce, Fetch, ListOffsets, Metadata, CreateTopics, DeleteTopics, CreatePartitions, DescribeConfigs, AlterConfigs and IncrementalAlterConfigs wired | `bridge/` module (connection, topic mapping, provisioning, high watermark, `topic_target` + `send_records`, `probe` + `poll`). Produce ([#3535](https://github.com/apache/iggy/issues/3535)), Fetch ([#3536](https://github.com/apache/iggy/issues/3536)), ListOffsets ([#3537](https://github.com/apache/iggy/issues/3537)), [...]
---
diff --git a/gateways/kafka/scripts/ci-wire-fixtures.sh b/gateways/kafka/scripts/ci-wire-fixtures.sh
index 52259ce88..c7ea167fa 100755
--- a/gateways/kafka/scripts/ci-wire-fixtures.sh
+++ b/gateways/kafka/scripts/ci-wire-fixtures.sh
@@ -24,7 +24,7 @@ set -euo pipefail
FIXTURES_DIR="gateways/kafka/tools/kafka-tool/kafka_messages"
# API keys requested by api_handler_tests, version_firewall_tests, and server_e2e_tests.
-FIXTURE_API_KEYS=(0 1 2 8 9 10 11 12 13 14 15 16 19 20 22 32 33 37 60)
+FIXTURE_API_KEYS=(0 1 2 8 9 10 11 12 13 14 15 16 19 20 22 32 33 37 44 60)
usage() {
echo "Usage: $0 {generate|cleanup}" >&2
diff --git a/gateways/kafka/src/protocol/api.rs b/gateways/kafka/src/protocol/api.rs
index a679bf23c..d2a73b542 100644
--- a/gateways/kafka/src/protocol/api.rs
+++ b/gateways/kafka/src/protocol/api.rs
@@ -45,8 +45,8 @@ use crate::protocol::handlers::init_producer_id::ProducerIdAllocator;
use crate::protocol::handlers::{
alter_configs, api_versions, create_partitions, create_topics, decode_guarded, delete_topics,
describe_cluster, describe_configs, describe_groups, dispatch, fetch, find_coordinator,
- heartbeat, init_producer_id, join_group, leave_group, list_groups, list_offsets, metadata,
- offset_commit, offset_fetch, produce, respond_or_close, sync_group,
+ heartbeat, incremental_alter_configs, init_producer_id, join_group, leave_group, list_groups,
+ list_offsets, metadata, offset_commit, offset_fetch, produce, respond_or_close, sync_group,
};
use crate::protocol::probe_board::ProbeBoard;
use crate::protocol::sasl::{
@@ -76,6 +76,7 @@ pub const API_KEY_DESCRIBE_CONFIGS: i16 = 32;
pub const API_KEY_ALTER_CONFIGS: i16 = 33;
pub const API_KEY_SASL_AUTHENTICATE: i16 = 36;
pub const API_KEY_CREATE_PARTITIONS: i16 = 37;
+pub const API_KEY_INCREMENTAL_ALTER_CONFIGS: i16 = 44;
pub const API_KEY_DESCRIBE_CLUSTER: i16 = 60;
pub const DEFAULT_KAFKA_PORT: u16 = 9093;
@@ -301,6 +302,7 @@ static SUPPORTED_RANGES: &[ApiVersionRange] = &[
create_partitions::RANGE,
describe_configs::RANGE,
alter_configs::RANGE,
+ incremental_alter_configs::RANGE,
init_producer_id::RANGE,
find_coordinator::RANGE,
join_group::RANGE,
@@ -323,8 +325,9 @@ pub fn supported_api_ranges() -> &'static [ApiVersionRange] {
/// answers with its stub, so APIs can be wired one at a time.
///
/// Produce sends on one Iggy client per producer. Metadata, `CreateTopics`, `DeleteTopics`,
-/// `CreatePartitions`, `DescribeConfigs` and `AlterConfigs` share one lockstep `IggyClient`, so
-/// those calls run one at a time across connections. See the README's "Concurrency ceiling".
+/// `CreatePartitions`, `DescribeConfigs`, `AlterConfigs` and `IncrementalAlterConfigs` share one
+/// lockstep `IggyClient`, so those calls run one at a time across connections. See the README's
+/// "Concurrency ceiling".
pub struct GatewayState {
pub bridge: Option<Arc<IggyBridge>>,
pub max_frame_size: usize,
@@ -855,6 +858,9 @@ pub fn encode_error_for_key(
describe_configs::encode_error_response(api_version, error_code)
}
API_KEY_ALTER_CONFIGS => alter_configs::encode_error_response(api_version, error_code),
+ API_KEY_INCREMENTAL_ALTER_CONFIGS => {
+ incremental_alter_configs::encode_error_response(api_version, error_code)
+ }
API_KEY_DESCRIBE_CLUSTER => {
describe_cluster::encode_error_response(api_version, error_code)
}
diff --git a/gateways/kafka/src/protocol/bounds_guard.rs b/gateways/kafka/src/protocol/bounds_guard.rs
index 5ad041a9f..b7aa6534a 100644
--- a/gateways/kafka/src/protocol/bounds_guard.rs
+++ b/gateways/kafka/src/protocol/bounds_guard.rs
@@ -1448,6 +1448,60 @@ pub fn validate_alter_configs_shape(
Ok(())
}
+/// Mirrors the field order `IncrementalAlterConfigsRequest::decode` walks.
+///
+/// # Errors
+///
+/// Returns an error when a declared array or string length cannot fit in the bytes remaining
+/// in the frame, or the body is truncated or malformed in a way that cannot be walked.
+pub fn validate_incremental_alter_configs_shape(
+ version: i16,
+ body: &Bytes,
+ max_frame_size: usize,
+) -> Result<()> {
+ let mut c = ShapeCursor::new(body.clone(), max_frame_size);
+ let flexible = version >= 1;
+
+ let resources_count = if flexible {
+ c.compact_array_count()?
+ } else {
+ c.legacy_array_count()?
+ };
+ for _ in 0..resources_count {
+ let _resource_type = c.read_i8()?;
+ if flexible {
+ c.compact_string(false)?;
+ } else {
+ c.legacy_string(false)?;
+ }
+ let configs_count = if flexible {
+ c.compact_array_count()?
+ } else {
+ c.legacy_array_count()?
+ };
+ for _ in 0..configs_count {
+ if flexible {
+ c.compact_string(false)?;
+ let _config_operation = c.read_i8()?;
+ c.compact_string(true)?;
+ c.tagged_fields()?;
+ } else {
+ c.legacy_string(false)?;
+ let _config_operation = c.read_i8()?;
+ c.legacy_string(true)?;
+ }
+ }
+ if flexible {
+ c.tagged_fields()?;
+ }
+ }
+ let _validate_only = c.read_bool()?;
+ if flexible {
+ c.tagged_fields()?;
+ }
+ Ok(())
+}
+
/// `DescribeAcls` carries a fixed-shape filter: four enums and three nullable strings.
///
/// No arrays and nothing echoed into the response, so there is no amplification to project. The
@@ -2216,6 +2270,34 @@ mod tests {
assert!(validate_alter_configs_shape(2, &body, TEST_MAX_FRAME_SIZE).is_err());
}
+ #[test]
+ fn incremental_alter_configs_v0_huge_legacy_count_rejected() {
+ let body = Bytes::from_static(&[0x7F, 0xFF, 0xFF, 0xFF]);
+ assert!(validate_incremental_alter_configs_shape(0, &body, TEST_MAX_FRAME_SIZE).is_err());
+ }
+
+ #[test]
+ fn incremental_alter_configs_v1_huge_compact_count_rejected() {
+ let body = Bytes::from_static(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F]); // u32::MAX, 5-byte varint
+ assert!(validate_incremental_alter_configs_shape(1, &body, TEST_MAX_FRAME_SIZE).is_err());
+ }
+
+ /// A config entry declaring a value longer than the frame is caught by the walk, at the
+ /// nullable-string position that only this request has after the operation byte.
+ #[test]
+ fn incremental_alter_configs_v0_overlong_value_rejected() {
+ let body = Bytes::from_static(&[
+ 0x00, 0x00, 0x00, 0x01, // one resource
+ 0x02, // resource_type
+ 0x00, 0x01, b'a', // resource_name
+ 0x00, 0x00, 0x00, 0x01, // one config
+ 0x00, 0x01, b'k', // name
+ 0x00, // config_operation
+ 0x7F, 0xFF, // value length past the frame
+ ]);
+ assert!(validate_incremental_alter_configs_shape(0, &body, TEST_MAX_FRAME_SIZE).is_err());
+ }
+
#[test]
fn describe_groups_v5_huge_group_count_rejected() {
let body = Bytes::from_static(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
diff --git a/gateways/kafka/src/protocol/handlers/alter_configs.rs b/gateways/kafka/src/protocol/handlers/alter_configs.rs
index a7e52ceb6..f60094f2b 100644
--- a/gateways/kafka/src/protocol/handlers/alter_configs.rs
+++ b/gateways/kafka/src/protocol/handlers/alter_configs.rs
@@ -20,7 +20,7 @@
use std::collections::HashSet;
use bytes::Bytes;
-use iggy::prelude::IggyError;
+use iggy::prelude::{IggyError, IggyExpiry};
use kafka_protocol::messages::AlterConfigsRequest;
use kafka_protocol::messages::alter_configs_request::AlterConfigsResource;
use kafka_protocol::messages::alter_configs_response::{
@@ -40,8 +40,8 @@ use crate::protocol::api::{
};
use crate::protocol::bounds_guard::validate_alter_configs_shape;
use crate::protocol::handlers::topic_config::{
- ONLY_TOPIC_RESOURCES, RESOURCE_TYPE_TOPIC, bridge_failure, name_reason, plan_retention_update,
- topic_cap_and_duplicates, topic_cap_message,
+ ONLY_TOPIC_RESOURCES, RESOURCE_TYPE_TOPIC, alter_denial, bridge_failure, name_reason,
+ plan_retention_update, topic_cap_and_duplicates, topic_cap_message,
};
use crate::protocol::handlers::{
decode_guarded, encode_message, is_supported_version, respond_or_close,
@@ -123,29 +123,13 @@ pub async fn handle(
)
}
-/// Denies every resource when `principal` is not allowed to alter topic configuration, or when
-/// its permissions could not be read. `None` means no listener of this gateway names principals,
-/// so there is nothing to enforce against; once one does, a connection that proved no identity
-/// carries [`AuthenticatedPrincipal::anonymous`] instead and is denied here.
+/// Denies every resource when [`alter_denial`] says `principal` may not alter topic
+/// configuration.
fn authorize(
principal: Option<&AuthenticatedPrincipal>,
resources: &[AlterConfigsResource],
) -> Option<Vec<AlterConfigsResourceResponse>> {
- let principal = principal?;
- if principal.permissions_known && principal.permissions.manage_topics {
- return None;
- }
- if !principal.permissions_known {
- // The permission read failed after a successful login, so this connection holds no
- // real answer. Denying is the fail-closed choice: granting would authorize a write off
- // a value nothing ever actually read.
- tracing::warn!(
- principal = %principal.username,
- "AlterConfigs asked on a connection whose permissions were never read; denying"
- );
- }
- let message =
- StrBytes::from_static_str("the principal is not authorized to alter topic configuration");
+ let message = alter_denial(principal, "AlterConfigs")?;
Some(
resources
.iter()
@@ -291,6 +275,16 @@ async fn alter_one(
return resource_error(resource, ERROR_NONE, None);
}
+ write_expiry(bridge, resource, expiry, deadline).await
+}
+
+async fn write_expiry(
+ bridge: &IggyBridge,
+ resource: &AlterConfigsResource,
+ expiry: IggyExpiry,
+ deadline: Instant,
+) -> AlterConfigsResourceResponse {
+ let name = resource.resource_name.as_str();
// Do not start the write once the deadline has passed, and do not wrap it in
// `timeout_at`. Dropping that future does not abort the SDK task, so
// `UpdateTopic` can commit after this handler has already answered
@@ -385,4 +379,19 @@ mod tests {
let responses = authorize(Some(&principal), &[resource("orders")]).expect("denied");
assert_eq!(responses[0].error_code, ERROR_TOPIC_AUTHORIZATION_FAILED);
}
+
+ #[tokio::test]
+ async fn given_a_passed_deadline_when_writing_should_answer_timed_out_without_calling_iggy() {
+ let bridge = IggyBridge::offline();
+ let response = write_expiry(
+ &bridge,
+ &resource("orders"),
+ IggyExpiry::NeverExpire,
+ Instant::now(),
+ )
+ .await;
+ // A write started on the offline bridge fails fast as NOT_LEADER_OR_FOLLOWER instead.
+ assert_eq!(response.error_code, ERROR_REQUEST_TIMED_OUT);
+ assert!(response.error_message.is_none());
+ }
}
diff --git a/gateways/kafka/src/protocol/handlers/alter_configs.rs b/gateways/kafka/src/protocol/handlers/incremental_alter_configs.rs
similarity index 62%
copy from gateways/kafka/src/protocol/handlers/alter_configs.rs
copy to gateways/kafka/src/protocol/handlers/incremental_alter_configs.rs
index a7e52ceb6..5e1b0300c 100644
--- a/gateways/kafka/src/protocol/handlers/alter_configs.rs
+++ b/gateways/kafka/src/protocol/handlers/incremental_alter_configs.rs
@@ -15,16 +15,22 @@
// specific language governing permissions and limitations
// under the License.
-//! `AlterConfigs` (API key 33).
+//! `IncrementalAlterConfigs` (API key 44).
+//!
+//! `kafka-configs --alter` on a topic has sent this key since Kafka 2.5. `AlterConfigs` (33)
+//! comes from Java `Admin.alterConfigs` before 4.0, which removed it, and from other clients'
+//! non-incremental alter calls such as librdkafka's `rd_kafka_AlterConfigs`. Each entry carries
+//! one operation on one key, where 33 carries a whole new set. Both end in the same write, `retention.ms` onto the topic's
+//! `message_expiry`, behind the same checks. See `docs/CONFIGS.md`.
use std::collections::HashSet;
use bytes::Bytes;
-use iggy::prelude::IggyError;
-use kafka_protocol::messages::AlterConfigsRequest;
-use kafka_protocol::messages::alter_configs_request::AlterConfigsResource;
-use kafka_protocol::messages::alter_configs_response::{
- AlterConfigsResourceResponse, AlterConfigsResponse,
+use iggy::prelude::{IggyError, IggyExpiry};
+use kafka_protocol::messages::IncrementalAlterConfigsRequest;
+use kafka_protocol::messages::incremental_alter_configs_request::AlterConfigsResource;
+use kafka_protocol::messages::incremental_alter_configs_response::{
+ AlterConfigsResourceResponse, IncrementalAlterConfigsResponse,
};
use kafka_protocol::protocol::StrBytes;
use tokio::time::Instant;
@@ -33,15 +39,15 @@ use crate::auth::AuthenticatedPrincipal;
use crate::bridge::topic_map::validate_kafka_topic_name;
use crate::bridge::{BridgeError, IggyBridge, StreamTopicCache, TopicLoad};
use crate::protocol::api::{
- API_KEY_ALTER_CONFIGS, ApiVersionRange, ERROR_INVALID_CONFIG, ERROR_INVALID_REQUEST,
- ERROR_INVALID_TOPIC_EXCEPTION, ERROR_NONE, ERROR_NOT_CONTROLLER, ERROR_POLICY_VIOLATION,
- ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
- GatewayState, HandleOutcome, REQUEST_DEADLINE,
+ API_KEY_INCREMENTAL_ALTER_CONFIGS, ApiVersionRange, ERROR_INVALID_CONFIG,
+ ERROR_INVALID_REQUEST, ERROR_INVALID_TOPIC_EXCEPTION, ERROR_NONE, ERROR_NOT_CONTROLLER,
+ ERROR_POLICY_VIOLATION, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState, HandleOutcome, REQUEST_DEADLINE,
};
-use crate::protocol::bounds_guard::validate_alter_configs_shape;
+use crate::protocol::bounds_guard::validate_incremental_alter_configs_shape;
use crate::protocol::handlers::topic_config::{
- ONLY_TOPIC_RESOURCES, RESOURCE_TYPE_TOPIC, bridge_failure, name_reason, plan_retention_update,
- topic_cap_and_duplicates, topic_cap_message,
+ ONLY_TOPIC_RESOURCES, RESOURCE_TYPE_TOPIC, alter_denial, bridge_failure, incremental_ops,
+ name_reason, plan_incremental_update, topic_cap_and_duplicates, topic_cap_message,
};
use crate::protocol::handlers::{
decode_guarded, encode_message, is_supported_version, respond_or_close,
@@ -49,49 +55,61 @@ use crate::protocol::handlers::{
};
pub const RANGE: ApiVersionRange = ApiVersionRange {
- api_key: API_KEY_ALTER_CONFIGS,
+ api_key: API_KEY_INCREMENTAL_ALTER_CONFIGS,
min_version: 0,
- max_version: 2,
+ max_version: 1,
};
+const API_NAME: &str = "IncrementalAlterConfigs";
+
+/// Kafka's own text for a topic that more than one resource of the request names.
+const DUPLICATE_RESOURCE: &str = "Each resource must appear at most once.";
+
pub async fn handle(
state: &GatewayState,
principal: Option<&AuthenticatedPrincipal>,
api_version: i16,
body: Bytes,
) -> HandleOutcome {
- if !is_supported_version(API_KEY_ALTER_CONFIGS, api_version) {
- return unsupported_version_response(API_KEY_ALTER_CONFIGS, api_version, |version| {
- encode_error_response(version, ERROR_INVALID_REQUEST)
- });
+ if !is_supported_version(API_KEY_INCREMENTAL_ALTER_CONFIGS, api_version) {
+ return unsupported_version_response(
+ API_KEY_INCREMENTAL_ALTER_CONFIGS,
+ api_version,
+ |version| encode_error_response(version, ERROR_INVALID_REQUEST),
+ );
}
- let req = match decode_guarded::<AlterConfigsRequest>(api_version, body, |version, body| {
- validate_alter_configs_shape(version, body, state.max_frame_size)
- }) {
+ let req = match decode_guarded::<IncrementalAlterConfigsRequest>(
+ api_version,
+ body,
+ |version, body| {
+ validate_incremental_alter_configs_shape(version, body, state.max_frame_size)
+ },
+ ) {
Ok(req) => req,
Err(error) => {
- tracing::debug!(%error, "Failed to decode AlterConfigs request");
+ tracing::debug!(%error, "Failed to decode IncrementalAlterConfigs request");
return respond_or_close(
encode_error_response(api_version, ERROR_INVALID_REQUEST),
- "AlterConfigs",
+ API_NAME,
);
}
};
- // Checked before the bridge-availability stub, not inside `alter_all`: a cap or an
- // authorization decision does not depend on the controller being reachable, and a check
- // that only runs once the bridge is up is never exercised by a serverless/stub test.
+ // Authorization and the cap come before the bridge-availability stub: neither depends on
+ // the controller being reachable.
if let Some(responses) = authorize(principal, &req.resources) {
return respond_or_close(
encode_message(&response(responses), api_version, 256),
- "AlterConfigs",
+ API_NAME,
);
}
let (exceeds_cap, duplicate_names) = topic_cap_and_duplicates(&req.resources);
if exceeds_cap {
- let message = StrBytes::from(topic_cap_message("AlterConfigs"));
- tracing::warn!("AlterConfigs request addresses too many distinct topics; rejecting");
+ let message = StrBytes::from(topic_cap_message(API_NAME));
+ tracing::warn!(
+ "IncrementalAlterConfigs request addresses too many distinct topics; rejecting"
+ );
let responses = req
.resources
.iter()
@@ -99,7 +117,7 @@ pub async fn handle(
.collect();
return respond_or_close(
encode_message(&response(responses), api_version, 256),
- "AlterConfigs",
+ API_NAME,
);
}
@@ -111,7 +129,7 @@ pub async fn handle(
.collect();
return respond_or_close(
encode_message(&response(responses), api_version, 256),
- "AlterConfigs",
+ API_NAME,
);
};
@@ -119,33 +137,17 @@ pub async fn handle(
let responses = alter_all(bridge, &req, &duplicate_names, deadline).await;
respond_or_close(
encode_message(&response(responses), api_version, 256),
- "AlterConfigs",
+ API_NAME,
)
}
-/// Denies every resource when `principal` is not allowed to alter topic configuration, or when
-/// its permissions could not be read. `None` means no listener of this gateway names principals,
-/// so there is nothing to enforce against; once one does, a connection that proved no identity
-/// carries [`AuthenticatedPrincipal::anonymous`] instead and is denied here.
+/// Denies every resource when [`alter_denial`] says `principal` may not alter topic
+/// configuration.
fn authorize(
principal: Option<&AuthenticatedPrincipal>,
resources: &[AlterConfigsResource],
) -> Option<Vec<AlterConfigsResourceResponse>> {
- let principal = principal?;
- if principal.permissions_known && principal.permissions.manage_topics {
- return None;
- }
- if !principal.permissions_known {
- // The permission read failed after a successful login, so this connection holds no
- // real answer. Denying is the fail-closed choice: granting would authorize a write off
- // a value nothing ever actually read.
- tracing::warn!(
- principal = %principal.username,
- "AlterConfigs asked on a connection whose permissions were never read; denying"
- );
- }
- let message =
- StrBytes::from_static_str("the principal is not authorized to alter topic configuration");
+ let message = alter_denial(principal, API_NAME)?;
Some(
resources
.iter()
@@ -174,15 +176,15 @@ pub fn encode_error_response(version: i16, error_code: i16) -> crate::error::Res
encode_message(&response(responses), version, 128)
}
-fn response(responses: Vec<AlterConfigsResourceResponse>) -> AlterConfigsResponse {
- AlterConfigsResponse::default()
+fn response(responses: Vec<AlterConfigsResourceResponse>) -> IncrementalAlterConfigsResponse {
+ IncrementalAlterConfigsResponse::default()
.with_throttle_time_ms(0)
.with_responses(responses)
}
async fn alter_all(
bridge: &IggyBridge,
- req: &AlterConfigsRequest,
+ req: &IncrementalAlterConfigsRequest,
duplicate_names: &HashSet<&str>,
deadline: Instant,
) -> Vec<AlterConfigsResourceResponse> {
@@ -193,15 +195,19 @@ async fn alter_all(
if resource.resource_type == RESOURCE_TYPE_TOPIC
&& duplicate_names.contains(resource.resource_name.as_str())
{
- responses.push(resource_error(resource, ERROR_INVALID_REQUEST, None));
+ responses.push(resource_error(
+ resource,
+ ERROR_INVALID_REQUEST,
+ Some(StrBytes::from_static_str(DUPLICATE_RESOURCE)),
+ ));
continue;
}
if deadline_exceeded || Instant::now() >= deadline {
if !deadline_exceeded {
deadline_exceeded = true;
tracing::warn!(
- "AlterConfigs deadline passed; answering remaining resources retriable \
- instead of starting new Iggy calls"
+ "IncrementalAlterConfigs deadline passed; answering remaining resources \
+ retriable instead of starting new Iggy calls"
);
}
responses.push(resource_error(resource, ERROR_REQUEST_TIMED_OUT, None));
@@ -240,16 +246,32 @@ async fn alter_one(
);
}
- // Existence is checked before config keys. A missing topic is
- // UNKNOWN_TOPIC_OR_PARTITION even when a key would also be invalid.
- // A deadline that has already passed must not start the lockstep Iggy call.
- match cache.lookup(bridge, name, deadline, "AlterConfigs").await {
+ // Request faults need no Iggy call, so they are answered before the topic lookup. Config
+ // faults come after it, as in `AlterConfigs`: a missing topic is never `INVALID_CONFIG`.
+ let ops = match incremental_ops(resource.configs.iter().map(|config| {
+ (
+ config.name.as_str(),
+ config.config_operation,
+ config.value.as_ref().map(StrBytes::as_str),
+ )
+ })) {
+ Ok(ops) => ops,
+ Err(fault) => {
+ return resource_error(
+ resource,
+ ERROR_INVALID_REQUEST,
+ Some(StrBytes::from(fault.message())),
+ );
+ }
+ };
+
+ match cache.lookup(bridge, name, deadline, API_NAME).await {
TopicLoad::Found(_) => {}
TopicLoad::Missing => {
return resource_error(resource, ERROR_UNKNOWN_TOPIC_OR_PARTITION, None);
}
TopicLoad::Failed(error) => {
- let (code, message) = bridge_failure(error, "AlterConfigs", "altering");
+ let (code, message) = bridge_failure(error, API_NAME, "altering");
return resource_error(resource, code, message);
}
TopicLoad::NotStarted | TopicLoad::TimedOut => {
@@ -257,12 +279,7 @@ async fn alter_one(
}
}
- let expiry = match plan_retention_update(resource.configs.iter().map(|config| {
- (
- config.name.as_str(),
- config.value.as_ref().map(StrBytes::as_str),
- )
- })) {
+ let expiry = match plan_incremental_update(&ops) {
Ok(expiry) => expiry,
Err(fault) => {
return resource_error(
@@ -272,38 +289,32 @@ async fn alter_one(
);
}
};
- // Kafka's AlterConfigs replaces the whole set, so an empty list is a reset.
- // This gateway patches named keys. Reporting success would hide that the
- // previous expiry is still stored.
- let Some(expiry) = expiry else {
- return resource_error(
- resource,
- ERROR_INVALID_CONFIG,
- Some(StrBytes::from_static_str(
- "an empty configs list is rejected because this gateway patches named keys and does not replace the topic configuration",
- )),
- );
- };
-
- // `validate_only` already performed the existence read and the same key checks.
- // It does not call `update_topic`.
if validate_only {
return resource_error(resource, ERROR_NONE, None);
}
+ // Nothing named `retention.ms`, so there is nothing to store. Kafka answers an empty
+ // operation list, and a delete of an override that was never set, the same way.
+ let Some(expiry) = expiry else {
+ return resource_error(resource, ERROR_NONE, None);
+ };
+
+ write_expiry(bridge, resource, expiry, deadline).await
+}
- // Do not start the write once the deadline has passed, and do not wrap it in
- // `timeout_at`. Dropping that future does not abort the SDK task, so
- // `UpdateTopic` can commit after this handler has already answered
- // REQUEST_TIMED_OUT. A short retention then deletes sealed segments. This is a
- // policy choice about *this* handler's own deadline, independent of
- // `update_kafka_topic_message_expiry` itself: that bridge call already wraps its
- // SDK round trip in `with_request_timeout` (see `topics.rs`), so the write it
- // starts is never unbounded - it can simply still be in flight when this
- // handler's own, shorter deadline has already elapsed.
+async fn write_expiry(
+ bridge: &IggyBridge,
+ resource: &AlterConfigsResource,
+ expiry: IggyExpiry,
+ deadline: Instant,
+) -> AlterConfigsResourceResponse {
+ let name = resource.resource_name.as_str();
+ // Not started past the deadline and not wrapped in `timeout_at`: dropping the future does not
+ // abort the SDK call. The bridge bounds its own round trip with `with_request_timeout`, so a
+ // write can still commit after this handler answered REQUEST_TIMED_OUT.
if Instant::now() >= deadline {
tracing::warn!(
resource = name,
- "AlterConfigs deadline passed before update_topic; not starting the write"
+ "IncrementalAlterConfigs deadline passed before update_topic; not starting the write"
);
return resource_error(resource, ERROR_REQUEST_TIMED_OUT, None);
}
@@ -312,7 +323,7 @@ async fn alter_one(
resource_error(resource, ERROR_NONE, None)
}
Err(error) => {
- let (code, message) = bridge_failure(&error, "AlterConfigs", "altering");
+ let (code, message) = bridge_failure(&error, API_NAME, "altering");
resource_error(resource, code, message)
}
}
@@ -385,4 +396,19 @@ mod tests {
let responses = authorize(Some(&principal), &[resource("orders")]).expect("denied");
assert_eq!(responses[0].error_code, ERROR_TOPIC_AUTHORIZATION_FAILED);
}
+
+ #[tokio::test]
+ async fn given_a_passed_deadline_when_writing_should_answer_timed_out_without_calling_iggy() {
+ let bridge = IggyBridge::offline();
+ let response = write_expiry(
+ &bridge,
+ &resource("orders"),
+ IggyExpiry::NeverExpire,
+ Instant::now(),
+ )
+ .await;
+ // A write started on the offline bridge fails fast as NOT_LEADER_OR_FOLLOWER instead.
+ assert_eq!(response.error_code, ERROR_REQUEST_TIMED_OUT);
+ assert!(response.error_message.is_none());
+ }
}
diff --git a/gateways/kafka/src/protocol/handlers/mod.rs b/gateways/kafka/src/protocol/handlers/mod.rs
index bdf1ea809..1e0c3c364 100644
--- a/gateways/kafka/src/protocol/handlers/mod.rs
+++ b/gateways/kafka/src/protocol/handlers/mod.rs
@@ -35,6 +35,7 @@ pub mod describe_groups;
pub mod fetch;
pub mod find_coordinator;
pub mod heartbeat;
+pub mod incremental_alter_configs;
pub mod init_producer_id;
pub mod join_group;
pub mod leave_group;
@@ -63,11 +64,11 @@ use crate::protocol::api::{
API_KEY_ALTER_CONFIGS, API_KEY_API_VERSIONS, API_KEY_CREATE_PARTITIONS, API_KEY_CREATE_TOPICS,
API_KEY_DELETE_TOPICS, API_KEY_DESCRIBE_CLUSTER, API_KEY_DESCRIBE_CONFIGS,
API_KEY_DESCRIBE_GROUPS, API_KEY_FETCH, API_KEY_FIND_COORDINATOR, API_KEY_HEARTBEAT,
- API_KEY_INIT_PRODUCER_ID, API_KEY_JOIN_GROUP, API_KEY_LEAVE_GROUP, API_KEY_LIST_GROUPS,
- API_KEY_LIST_OFFSETS, API_KEY_METADATA, API_KEY_OFFSET_COMMIT, API_KEY_OFFSET_FETCH,
- API_KEY_PRODUCE, API_KEY_SYNC_GROUP, ConnectionState, ERROR_INVALID_REQUEST,
- ERROR_UNSUPPORTED_VERSION, GatewayState, HandleOutcome, is_supported_version,
- supported_max_version,
+ API_KEY_INCREMENTAL_ALTER_CONFIGS, API_KEY_INIT_PRODUCER_ID, API_KEY_JOIN_GROUP,
+ API_KEY_LEAVE_GROUP, API_KEY_LIST_GROUPS, API_KEY_LIST_OFFSETS, API_KEY_METADATA,
+ API_KEY_OFFSET_COMMIT, API_KEY_OFFSET_FETCH, API_KEY_PRODUCE, API_KEY_SYNC_GROUP,
+ ConnectionState, ERROR_INVALID_REQUEST, ERROR_UNSUPPORTED_VERSION, GatewayState, HandleOutcome,
+ is_supported_version, supported_max_version,
};
/// Record encodes and decodes of this many bytes or more run off the async worker.
@@ -128,6 +129,9 @@ pub async fn dispatch(
}
API_KEY_DESCRIBE_CONFIGS => describe_configs::handle(state, api_version, body).await,
API_KEY_ALTER_CONFIGS => alter_configs::handle(state, principal, api_version, body).await,
+ API_KEY_INCREMENTAL_ALTER_CONFIGS => {
+ incremental_alter_configs::handle(state, principal, api_version, body).await
+ }
API_KEY_FIND_COORDINATOR => {
find_coordinator::handle(state, connection, api_version, body).await
}
diff --git a/gateways/kafka/src/protocol/handlers/topic_config.rs b/gateways/kafka/src/protocol/handlers/topic_config.rs
index fb756e8b8..e368fb3e4 100644
--- a/gateways/kafka/src/protocol/handlers/topic_config.rs
+++ b/gateways/kafka/src/protocol/handlers/topic_config.rs
@@ -15,7 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-//! Topic configuration shared by `DescribeConfigs` and `AlterConfigs`.
+//! Topic configuration shared by `DescribeConfigs`, `AlterConfigs` and
+//! `IncrementalAlterConfigs`.
//!
//! Iggy stores `message_expiry` as [`IggyExpiry`]. A duration is microseconds
//! (`IggyDuration::from(u64)` / `as_micros`). `u64::MAX` is [`IggyExpiry::NeverExpire`]
@@ -31,8 +32,10 @@ use std::str::FromStr;
use iggy::prelude::{HeaderKey, IggyDuration, IggyExpiry, ResourceOptions, topic_option_keys};
use kafka_protocol::messages::alter_configs_request::AlterConfigsResource;
use kafka_protocol::messages::describe_configs_request::DescribeConfigsResource;
+use kafka_protocol::messages::incremental_alter_configs_request::AlterConfigsResource as IncrementalAlterConfigsResource;
use kafka_protocol::protocol::StrBytes;
+use crate::auth::AuthenticatedPrincipal;
use crate::bridge::BridgeError;
/// Kafka `ConfigResource.Type.TOPIC`.
@@ -54,8 +57,8 @@ pub const ONLY_TOPIC_RESOURCES: &str = "only topic resources are supported";
pub const RETENTION_DOC: &str = "How long a sealed segment is kept, in milliseconds. The active segment does not expire. -1 means sealed segments never expire.";
-/// Distinct topic names one `CreateTopics`, `CreatePartitions`, `DescribeConfigs`, or
-/// `AlterConfigs` request may address through the bridge.
+/// Distinct topic names one `CreateTopics`, `CreatePartitions`, `DescribeConfigs`, `AlterConfigs`
+/// or `IncrementalAlterConfigs` request may address through the bridge.
///
/// `bounds_guard`'s element ceiling is a pre-decode limit. `CreateTopics` can spend several
/// lockstep Iggy calls per name on the shared client (`ensure_stream`, `create_topic`, and a
@@ -64,6 +67,11 @@ pub const RETENTION_DOC: &str = "How long a sealed segment is kept, in milliseco
/// batch is `POLICY_VIOLATION` on every resource.
pub const MAX_CONFIG_TOPICS: usize = 100;
+const CLEANUP_POLICY_READ_ONLY: &str = "cleanup.policy is read-only";
+
+const NOT_AUTHORIZED_TO_ALTER: &str =
+ "the authenticated principal is not authorized to alter topic configuration";
+
/// One config name a describe request asked for, in request order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListedKey {
@@ -75,13 +83,18 @@ pub enum ListedKey {
Unknown,
}
-/// Why one resource's alter cannot be stored.
+/// Why one resource's alter cannot be stored. Every variant is `INVALID_CONFIG` (40).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigFault {
UnknownKey(String),
Repeated(String),
ReadOnly(&'static str),
InvalidRetention,
+ /// An `APPEND` or `SUBTRACT` on a key that is not a list, in Kafka's own words.
+ NotAList {
+ operation: ConfigOperation,
+ key: String,
+ },
}
impl ConfigFault {
@@ -95,6 +108,79 @@ impl ConfigFault {
"retention.ms must be -1 or a positive count whose duration is at most {} seconds",
u32::MAX
),
+ Self::NotAList { operation, key } => {
+ let operation = operation.kafka_name();
+ format!("Can't {operation} to key {key} because its type is not LIST.")
+ }
+ }
+ }
+}
+
+/// Kafka `AlterConfigOp.OpType`, one per `IncrementalAlterConfigs` entry.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConfigOperation {
+ Set,
+ Delete,
+ Append,
+ Subtract,
+}
+
+impl ConfigOperation {
+ /// The spelling Kafka's own error text uses.
+ #[must_use]
+ pub const fn kafka_name(self) -> &'static str {
+ match self {
+ Self::Set => "SET",
+ Self::Delete => "DELETE",
+ Self::Append => "APPEND",
+ Self::Subtract => "SUBTRACT",
+ }
+ }
+}
+
+impl TryFrom<i8> for ConfigOperation {
+ /// The byte that matched nothing, for the client-facing text.
+ type Error = i8;
+
+ fn try_from(operation: i8) -> Result<Self, Self::Error> {
+ match operation {
+ 0 => Ok(Self::Set),
+ 1 => Ok(Self::Delete),
+ 2 => Ok(Self::Append),
+ 3 => Ok(Self::Subtract),
+ other => Err(other),
+ }
+ }
+}
+
+/// One `IncrementalAlterConfigs` entry that passed [`incremental_ops`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ConfigOp<'a> {
+ pub name: &'a str,
+ pub operation: ConfigOperation,
+ pub value: Option<&'a str>,
+}
+
+/// Why one resource's incremental alter is refused before any Iggy call. Every variant is
+/// `INVALID_REQUEST` (42). The duplicate-key and null-value texts are Kafka's own; the
+/// unknown-operation text is borrowed from Kafka's broker-resource check, because Kafka's topic
+/// path has no well-formed answer for it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum RequestFault {
+ DuplicateKeys,
+ NullValues(Vec<String>),
+ UnknownOperation(i8),
+}
+
+impl RequestFault {
+ #[must_use]
+ pub fn message(&self) -> String {
+ match self {
+ Self::DuplicateKeys => "Error due to duplicate config keys".to_string(),
+ Self::NullValues(names) => {
+ format!("Null value not supported for : {}", names.join(", "))
+ }
+ Self::UnknownOperation(operation) => format!("Unknown operations type {operation}"),
}
}
}
@@ -253,6 +339,16 @@ impl TopicResource for DescribeConfigsResource {
}
}
+impl TopicResource for IncrementalAlterConfigsResource {
+ fn kafka_resource_type(&self) -> i8 {
+ self.resource_type
+ }
+
+ fn kafka_resource_name(&self) -> &str {
+ self.resource_name.as_str()
+ }
+}
+
/// The cap/duplicate verdict shared by `DescribeConfigs` and `AlterConfigs`: both filter
/// resources down to [`RESOURCE_TYPE_TOPIC`] before deciding whether the request exceeds
/// [`MAX_CONFIG_TOPICS`] or repeats a name, and the business decision is identical even
@@ -270,6 +366,31 @@ pub fn topic_cap_and_duplicates<R: TopicResource>(resources: &[R]) -> (bool, Has
)
}
+/// The denial every resource gets when `principal` may not alter topic configuration, or
+/// `None` when the alter may run.
+///
+/// No principal means no listener of this gateway names principals, so there is nothing to
+/// enforce against. Once one does, a connection that proved no identity carries
+/// [`AuthenticatedPrincipal::anonymous`] instead and is denied here. Permissions that were never
+/// read deny: granting would authorize a write off a value nothing read.
+#[must_use]
+pub fn alter_denial(
+ principal: Option<&AuthenticatedPrincipal>,
+ api_name: &str,
+) -> Option<StrBytes> {
+ let principal = principal?;
+ if principal.permissions_known && principal.permissions.manage_topics {
+ return None;
+ }
+ if !principal.permissions_known {
+ tracing::warn!(
+ principal = %principal.username,
+ "{api_name} asked on a connection whose permissions were never read; denying"
+ );
+ }
+ Some(StrBytes::from_static_str(NOT_AUTHORIZED_TO_ALTER))
+}
+
/// The reason a topic name failed Kafka's own naming rules, or a fixed fallback.
#[must_use]
pub fn name_reason(error: &BridgeError) -> String {
@@ -363,13 +484,94 @@ pub fn plan_retention_update<'a>(
};
expiry = Some(parse_retention_ms(value)?);
}
- CLEANUP_POLICY => return Err(ConfigFault::ReadOnly("cleanup.policy is read-only")),
+ CLEANUP_POLICY => return Err(ConfigFault::ReadOnly(CLEANUP_POLICY_READ_ONLY)),
other => return Err(ConfigFault::UnknownKey(other.to_string())),
}
}
Ok(expiry)
}
+/// The entries of one `IncrementalAlterConfigs` resource, checked in the order Kafka's broker
+/// checks them before it forwards the request: a repeated name, a null value on anything but a
+/// delete, then an operation byte it does not know.
+///
+/// # Errors
+///
+/// Returns the first [`RequestFault`] in that order.
+pub fn incremental_ops<'a>(
+ configs: impl IntoIterator<Item = (&'a str, i8, Option<&'a str>)>,
+) -> Result<Vec<ConfigOp<'a>>, RequestFault> {
+ let configs: Vec<(&str, i8, Option<&str>)> = configs.into_iter().collect();
+ let mut seen = HashSet::new();
+ if configs.iter().any(|(name, _, _)| !seen.insert(*name)) {
+ return Err(RequestFault::DuplicateKeys);
+ }
+ let null_values: Vec<String> = configs
+ .iter()
+ .filter(|(_, operation, value)| {
+ value.is_none() && ConfigOperation::try_from(*operation) != Ok(ConfigOperation::Delete)
+ })
+ .map(|(name, _, _)| (*name).to_string())
+ .collect();
+ if !null_values.is_empty() {
+ return Err(RequestFault::NullValues(null_values));
+ }
+ configs
+ .into_iter()
+ .map(|(name, operation, value)| {
+ let operation =
+ ConfigOperation::try_from(operation).map_err(RequestFault::UnknownOperation)?;
+ Ok(ConfigOp {
+ name,
+ operation,
+ value,
+ })
+ })
+ .collect()
+}
+
+/// The expiry an incremental alter stores, or `None` when no entry changes `retention.ms`.
+///
+/// `SET` stores the parsed value. `DELETE` stores never-expire, the value a topic has before any
+/// alter, and a delete of any other key changes nothing: Kafka removes an override there, and
+/// this gateway stored none. `APPEND` and `SUBTRACT` are refused for every key: `cleanup.policy`
+/// is a list in Kafka but read-only here, and no other key this gateway knows is a list. Kafka
+/// refuses them the same way for a key it does not know.
+///
+/// # Errors
+///
+/// Returns the first [`ConfigFault`] in request order.
+pub fn plan_incremental_update(ops: &[ConfigOp<'_>]) -> Result<Option<IggyExpiry>, ConfigFault> {
+ let mut expiry = None;
+ for op in ops {
+ match op.operation {
+ ConfigOperation::Set => match op.name {
+ RETENTION_MS => {
+ let value = op.value.ok_or(ConfigFault::InvalidRetention)?;
+ expiry = Some(parse_retention_ms(value)?);
+ }
+ CLEANUP_POLICY => return Err(ConfigFault::ReadOnly(CLEANUP_POLICY_READ_ONLY)),
+ other => return Err(ConfigFault::UnknownKey(other.to_string())),
+ },
+ ConfigOperation::Delete => {
+ if op.name == RETENTION_MS {
+ expiry = Some(IggyExpiry::NeverExpire);
+ }
+ }
+ ConfigOperation::Append | ConfigOperation::Subtract => {
+ if op.name == CLEANUP_POLICY {
+ return Err(ConfigFault::ReadOnly(CLEANUP_POLICY_READ_ONLY));
+ }
+ return Err(ConfigFault::NotAList {
+ operation: op.operation,
+ key: op.name.to_string(),
+ });
+ }
+ }
+ }
+ Ok(expiry)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -511,4 +713,140 @@ mod tests {
.expect_err("repeated key");
assert_eq!(err, ConfigFault::Repeated(RETENTION_MS.to_string()));
}
+
+ #[test]
+ fn incremental_ops_rejects_a_repeated_name_before_a_null_value() {
+ let err = incremental_ops([(RETENTION_MS, 0, Some("1")), (RETENTION_MS, 0, None)])
+ .expect_err("repeated");
+ assert_eq!(err, RequestFault::DuplicateKeys);
+ assert_eq!(err.message(), "Error due to duplicate config keys");
+ }
+
+ #[test]
+ fn incremental_ops_names_every_null_value_except_a_delete() {
+ let err = incremental_ops([
+ (RETENTION_MS, 0, None),
+ (CLEANUP_POLICY, 1, None),
+ ("no.such", 9, None),
+ ])
+ .expect_err("null values");
+ assert_eq!(
+ err,
+ RequestFault::NullValues(vec![RETENTION_MS.to_string(), "no.such".to_string()])
+ );
+ assert_eq!(
+ err.message(),
+ "Null value not supported for : retention.ms, no.such"
+ );
+ }
+
+ #[test]
+ fn incremental_ops_rejects_an_unknown_operation_byte() {
+ let err = incremental_ops([(RETENTION_MS, 4, Some("1"))]).expect_err("unknown op");
+ assert_eq!(err, RequestFault::UnknownOperation(4));
+ assert_eq!(err.message(), "Unknown operations type 4");
+ let err = incremental_ops([(RETENTION_MS, -1, Some("1"))]).expect_err("negative op");
+ assert_eq!(err, RequestFault::UnknownOperation(-1));
+ assert_eq!(err.message(), "Unknown operations type -1");
+ }
+
+ #[test]
+ fn incremental_ops_keeps_request_order_and_a_delete_value() {
+ let ops = incremental_ops([(RETENTION_MS, 1, Some("")), ("no.such", 0, Some("1"))])
+ .expect("well formed");
+ assert_eq!(
+ ops,
+ vec![
+ ConfigOp {
+ name: RETENTION_MS,
+ operation: ConfigOperation::Delete,
+ value: Some(""),
+ },
+ ConfigOp {
+ name: "no.such",
+ operation: ConfigOperation::Set,
+ value: Some("1"),
+ },
+ ]
+ );
+ }
+
+ #[test]
+ fn incremental_plan_sets_and_deletes_retention() {
+ let set = incremental_ops([(RETENTION_MS, 0, Some("1500"))]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&set).expect("set"),
+ Some(IggyExpiry::ExpireDuration(IggyDuration::from(
+ 1_500_000_u64
+ )))
+ );
+ let delete = incremental_ops([(RETENTION_MS, 1, None)]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&delete).expect("delete"),
+ Some(IggyExpiry::NeverExpire)
+ );
+ }
+
+ #[test]
+ fn incremental_plan_ignores_a_delete_of_a_key_it_never_stored() {
+ let ops = incremental_ops([("no.such", 1, None), (CLEANUP_POLICY, 1, None)]).expect("ops");
+ assert_eq!(plan_incremental_update(&ops).expect("no-op"), None);
+ assert_eq!(plan_incremental_update(&[]).expect("empty"), None);
+ }
+
+ #[test]
+ fn incremental_plan_refuses_set_of_unknown_read_only_and_invalid_values() {
+ let unknown = incremental_ops([("no.such", 0, Some("1"))]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&unknown).expect_err("unknown"),
+ ConfigFault::UnknownKey("no.such".to_string())
+ );
+ let read_only = incremental_ops([(CLEANUP_POLICY, 0, Some("compact"))]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&read_only).expect_err("read only"),
+ ConfigFault::ReadOnly(CLEANUP_POLICY_READ_ONLY)
+ );
+ let invalid = incremental_ops([(RETENTION_MS, 0, Some("abc"))]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&invalid).expect_err("invalid"),
+ ConfigFault::InvalidRetention
+ );
+ }
+
+ #[test]
+ fn incremental_plan_refuses_append_and_subtract_on_every_key() {
+ let append = incremental_ops([(RETENTION_MS, 2, Some("1"))]).expect("ops");
+ let err = plan_incremental_update(&append).expect_err("append");
+ assert_eq!(
+ err,
+ ConfigFault::NotAList {
+ operation: ConfigOperation::Append,
+ key: RETENTION_MS.to_string(),
+ }
+ );
+ assert_eq!(
+ err.message(),
+ "Can't APPEND to key retention.ms because its type is not LIST."
+ );
+ let subtract = incremental_ops([("no.such", 3, Some("1"))]).expect("ops");
+ let err = plan_incremental_update(&subtract).expect_err("subtract");
+ assert_eq!(
+ err.message(),
+ "Can't SUBTRACT to key no.such because its type is not LIST."
+ );
+ }
+
+ #[test]
+ fn incremental_plan_refuses_append_and_subtract_on_cleanup_policy_as_read_only() {
+ let append = incremental_ops([(CLEANUP_POLICY, 2, Some("compact"))]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&append).expect_err("append"),
+ ConfigFault::ReadOnly(CLEANUP_POLICY_READ_ONLY)
+ );
+ let subtract = incremental_ops([(CLEANUP_POLICY, 3, Some("delete"))]).expect("ops");
+ assert_eq!(
+ plan_incremental_update(&subtract).expect_err("subtract"),
+ ConfigFault::ReadOnly(CLEANUP_POLICY_READ_ONLY)
+ );
+ }
}
diff --git a/gateways/kafka/tests/common/scope.rs b/gateways/kafka/tests/common/scope.rs
index bb7ffddbb..3a34a2b26 100644
--- a/gateways/kafka/tests/common/scope.rs
+++ b/gateways/kafka/tests/common/scope.rs
@@ -46,6 +46,7 @@ pub const SCOPED_API_KEYS: &[(i16, &str, i16, i16)] = &[
(32, "DescribeConfigs", 1, 4),
(33, "AlterConfigs", 0, 2),
(37, "CreatePartitions", 0, 3),
+ (44, "IncrementalAlterConfigs", 0, 1),
(60, "DescribeCluster", 0, 2),
];
diff --git a/gateways/kafka/tests/common/wire.rs b/gateways/kafka/tests/common/wire.rs
index aadcd83ff..6e66211a9 100644
--- a/gateways/kafka/tests/common/wire.rs
+++ b/gateways/kafka/tests/common/wire.rs
@@ -45,11 +45,7 @@ pub fn decode<M: Decodable>(body: Bytes, version: i16) -> M {
}
/// Consumer-group and admin keys explicitly out of scope in SCOPE.md.
-pub const OUT_OF_SCOPE_API_KEYS: &[(i16, &str)] = &[
- (21, "DeleteRecords"),
- (42, "DeleteGroups"),
- (44, "IncrementalAlterConfigs"),
-];
+pub const OUT_OF_SCOPE_API_KEYS: &[(i16, &str)] = &[(21, "DeleteRecords"), (42, "DeleteGroups")];
/// Append Metadata request fields that follow the topics array for `version`.
fn write_metadata_request_trailer(enc: &mut Encoder, version: i16) {
@@ -355,6 +351,22 @@ pub fn build_alter_configs_empty_request(version: i16) -> Bytes {
enc.freeze()
}
+/// `IncrementalAlterConfigs` with no resources. Flexible from v1.
+pub fn build_incremental_alter_configs_empty_request(version: i16) -> Bytes {
+ let flexible = version >= 1;
+ let mut enc = Encoder::with_capacity(16);
+ if flexible {
+ enc.write_varint(1);
+ } else {
+ enc.write_i32(0);
+ }
+ enc.write_bool(false); // validate_only
+ if flexible {
+ enc.write_empty_tagged_fields();
+ }
+ enc.freeze()
+}
+
/// `InitProducerId` request for any supported version (v0-v5), flexible from v2.
pub fn build_init_producer_id_request(version: i16, transactional_id: Option<&str>) -> Bytes {
let flexible = version >= 2;
diff --git a/gateways/kafka/tests/configs_handler_tests.rs b/gateways/kafka/tests/configs_handler_tests.rs
index 06499d692..d8d28c67e 100644
--- a/gateways/kafka/tests/configs_handler_tests.rs
+++ b/gateways/kafka/tests/configs_handler_tests.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-//! `DescribeConfigs` and `AlterConfigs` with the bridge off.
+//! `DescribeConfigs`, `AlterConfigs` and `IncrementalAlterConfigs` with the bridge off.
use kafka_protocol::messages::alter_configs_request::{
AlterConfigsRequest, AlterConfigsResource, AlterableConfig,
@@ -25,17 +25,24 @@ use kafka_protocol::messages::describe_configs_request::{
DescribeConfigsRequest, DescribeConfigsResource,
};
use kafka_protocol::messages::describe_configs_response::DescribeConfigsResponse;
+use kafka_protocol::messages::incremental_alter_configs_request::{
+ AlterConfigsResource as IncrementalAlterConfigsResource,
+ AlterableConfig as IncrementalAlterableConfig, IncrementalAlterConfigsRequest,
+};
+use kafka_protocol::messages::incremental_alter_configs_response::IncrementalAlterConfigsResponse;
use kafka_protocol::protocol::StrBytes;
use tokio_util::sync::CancellationToken;
-use bytes::Bytes;
+use iggy_gateway_kafka::auth::AuthenticatedPrincipal;
use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
-
+use iggy_gateway_kafka::protocol::acl::PrincipalPermissions;
use iggy_gateway_kafka::protocol::api::{
- BrokerAdvertise, ERROR_NOT_CONTROLLER, ERROR_POLICY_VIOLATION, GatewayState, handle_request,
+ ERROR_NOT_CONTROLLER, ERROR_POLICY_VIOLATION, ERROR_TOPIC_AUTHORIZATION_FAILED, GatewayState,
is_supported_version, supported_api_ranges,
};
-use iggy_gateway_kafka::protocol::handlers::{alter_configs, describe_configs};
+use iggy_gateway_kafka::protocol::handlers::{
+ alter_configs, describe_configs, incremental_alter_configs,
+};
#[path = "common/codec.rs"]
mod codec;
@@ -46,6 +53,9 @@ use wire::{decode, encode};
const DESCRIBE_VERSION: i16 = 4;
const ALTER_VERSION: i16 = 2;
+const INCREMENTAL_VERSION: i16 = 1;
+/// Kafka `AlterConfigOp.OpType.SET`.
+const OP_SET: i8 = 0;
fn state_without_bridge() -> GatewayState {
GatewayState::new(
@@ -115,21 +125,112 @@ async fn alter_configs_without_a_bridge_returns_not_controller() {
assert_eq!(response.responses[0].error_code, ERROR_NOT_CONTROLLER);
}
+fn incremental_resource(name: &str) -> IncrementalAlterConfigsResource {
+ IncrementalAlterConfigsResource::default()
+ .with_resource_type(2)
+ .with_resource_name(StrBytes::from(name.to_string()))
+ .with_configs(vec![
+ IncrementalAlterableConfig::default()
+ .with_name(StrBytes::from_static_str("retention.ms"))
+ .with_config_operation(OP_SET)
+ .with_value(Some(StrBytes::from_static_str("1000"))),
+ ])
+}
+
+async fn incremental_alter(
+ principal: Option<&AuthenticatedPrincipal>,
+ resources: Vec<IncrementalAlterConfigsResource>,
+) -> IncrementalAlterConfigsResponse {
+ let request = IncrementalAlterConfigsRequest::default()
+ .with_resources(resources)
+ .with_validate_only(false);
+ let outcome = incremental_alter_configs::handle(
+ &state_without_bridge(),
+ principal,
+ INCREMENTAL_VERSION,
+ encode(&request, INCREMENTAL_VERSION),
+ )
+ .await;
+ decode(
+ outcome.expect_response("IncrementalAlterConfigs answers"),
+ INCREMENTAL_VERSION,
+ )
+}
+
#[test]
-fn incremental_alter_configs_is_not_advertised() {
+fn incremental_alter_configs_is_advertised_at_v0_and_v1() {
+ let range = supported_api_ranges()
+ .iter()
+ .find(|range| range.api_key == 44)
+ .expect("IncrementalAlterConfigs is advertised");
+ assert_eq!((range.min_version, range.max_version), (0, 1));
+ assert!(is_supported_version(44, 0));
+ assert!(is_supported_version(44, 1));
+ assert!(!is_supported_version(44, 2));
+}
+
+#[tokio::test]
+async fn incremental_alter_configs_without_a_bridge_returns_not_controller() {
+ let response = incremental_alter(None, vec![incremental_resource("orders")]).await;
+ assert_eq!(response.responses.len(), 1);
+ assert_eq!(response.responses[0].error_code, ERROR_NOT_CONTROLLER);
+ assert_eq!(response.responses[0].resource_name.as_str(), "orders");
+}
+
+#[tokio::test]
+async fn incremental_alter_configs_over_the_cap_is_rejected_even_with_the_bridge_off() {
+ const OVER_CAP: usize = 101;
+ let resources = (0..OVER_CAP)
+ .map(|i| incremental_resource(&format!("topic-{i}")))
+ .collect();
+ let response = incremental_alter(None, resources).await;
+ assert_eq!(response.responses.len(), OVER_CAP);
assert!(
- supported_api_ranges()
+ response
+ .responses
.iter()
- .all(|range| range.api_key != 44)
+ .all(|r| r.error_code == ERROR_POLICY_VIOLATION)
);
- assert!(!is_supported_version(44, 0));
- assert!(!is_supported_version(44, 1));
}
+/// The `manage_topics` gate sits before the bridge-availability stub, so a denied principal
+/// never reaches `NOT_CONTROLLER`, and an allowed one does.
#[tokio::test]
-async fn incremental_alter_configs_closes_the_connection() {
- let outcome = handle_request(44, 1, Bytes::new(), &BrokerAdvertise::default()).await;
- assert!(outcome.is_close());
+async fn incremental_alter_configs_requires_manage_topics_before_the_stub() {
+ let principal = |manage_topics| AuthenticatedPrincipal {
+ username: "alice".to_string(),
+ permissions: PrincipalPermissions {
+ manage_topics,
+ ..PrincipalPermissions::default()
+ },
+ permissions_known: true,
+ };
+
+ let denied = incremental_alter(
+ Some(&principal(false)),
+ vec![
+ incremental_resource("orders"),
+ incremental_resource("payments"),
+ ],
+ )
+ .await;
+ assert_eq!(denied.responses.len(), 2);
+ assert!(
+ denied
+ .responses
+ .iter()
+ .all(|r| r.error_code == ERROR_TOPIC_AUTHORIZATION_FAILED)
+ );
+ assert!(
+ denied.responses[0]
+ .error_message
+ .as_ref()
+ .is_some_and(|message| message.as_str().contains("not authorized"))
+ );
+
+ let allowed =
+ incremental_alter(Some(&principal(true)), vec![incremental_resource("orders")]).await;
+ assert_eq!(allowed.responses[0].error_code, ERROR_NOT_CONTROLLER);
}
/// The over-100-distinct-topics cap is checked before the bridge-availability stub: with the
diff --git a/gateways/kafka/tests/configs_java_client_tests.rs b/gateways/kafka/tests/configs_java_client_tests.rs
index bfe18179d..bdefa6ce4 100644
--- a/gateways/kafka/tests/configs_java_client_tests.rs
+++ b/gateways/kafka/tests/configs_java_client_tests.rs
@@ -305,4 +305,13 @@ async fn kafka_39_admin_client_describes_and_alters_topic_configs() {
text.contains("altered_retention.ms=8000 source=DYNAMIC_TOPIC_CONFIG"),
"{text}"
);
+ assert!(text.contains("incremental_set_retention.ms=9000"), "{text}");
+ assert!(
+ text.contains("incremental_append_rejected=InvalidConfigurationException"),
+ "{text}"
+ );
+ assert!(
+ text.contains("incremental_delete_retention.ms=-1"),
+ "{text}"
+ );
}
diff --git a/gateways/kafka/tests/configs_real_bridge_tests.rs b/gateways/kafka/tests/configs_real_bridge_tests.rs
index 58ff52b13..d18121d5b 100644
--- a/gateways/kafka/tests/configs_real_bridge_tests.rs
+++ b/gateways/kafka/tests/configs_real_bridge_tests.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-//! `DescribeConfigs` and `AlterConfigs` against a real `iggy-server`.
+//! `DescribeConfigs`, `AlterConfigs` and `IncrementalAlterConfigs` against a real `iggy-server`.
use std::sync::Arc;
@@ -29,6 +29,11 @@ use kafka_protocol::messages::describe_configs_request::{
use kafka_protocol::messages::describe_configs_response::{
DescribeConfigsResourceResult, DescribeConfigsResponse, DescribeConfigsSynonym,
};
+use kafka_protocol::messages::incremental_alter_configs_request::{
+ AlterConfigsResource as IncrementalAlterConfigsResource,
+ AlterableConfig as IncrementalAlterableConfig, IncrementalAlterConfigsRequest,
+};
+use kafka_protocol::messages::incremental_alter_configs_response::IncrementalAlterConfigsResponse;
use kafka_protocol::protocol::StrBytes;
use serial_test::serial;
use tokio_util::sync::CancellationToken;
@@ -39,7 +44,9 @@ use iggy_gateway_kafka::protocol::api::{
ERROR_INVALID_CONFIG, ERROR_INVALID_REQUEST, ERROR_INVALID_TOPIC_EXCEPTION, ERROR_NONE,
ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
};
-use iggy_gateway_kafka::protocol::handlers::{alter_configs, describe_configs};
+use iggy_gateway_kafka::protocol::handlers::{
+ alter_configs, describe_configs, incremental_alter_configs,
+};
#[path = "common/codec.rs"]
mod codec;
@@ -55,9 +62,19 @@ const DESCRIBE_V4: i16 = 4;
const DESCRIBE_V1: i16 = 1;
const ALTER_V2: i16 = 2;
const ALTER_V0: i16 = 0;
+const INCREMENTAL_V1: i16 = 1;
+const INCREMENTAL_V0: i16 = 0;
const TOPIC: i8 = 2;
const SOURCE_TOPIC: i8 = 1;
const SOURCE_DEFAULT: i8 = 5;
+/// Kafka `AlterConfigOp.OpType` bytes.
+const OP_SET: i8 = 0;
+const OP_DELETE: i8 = 1;
+const OP_APPEND: i8 = 2;
+const OP_SUBTRACT: i8 = 3;
+
+/// The entries of one incremental resource: name, operation byte, value.
+type Configs = &'static [(&'static str, i8, Option<&'static str>)];
const fn text(value: &'static str) -> StrBytes {
StrBytes::from_static_str(value)
@@ -138,6 +155,88 @@ async fn alter(
decode(outcome.expect_response("AlterConfigs answers"), version)
}
+fn incremental_resource(
+ name: &str,
+ resource_type: i8,
+ configs: Configs,
+) -> IncrementalAlterConfigsResource {
+ IncrementalAlterConfigsResource::default()
+ .with_resource_type(resource_type)
+ .with_resource_name(StrBytes::from(name.to_string()))
+ .with_configs(
+ configs
+ .iter()
+ .map(|(key, operation, value)| {
+ IncrementalAlterableConfig::default()
+ .with_name(text(key))
+ .with_config_operation(*operation)
+ .with_value(value.map(text))
+ })
+ .collect(),
+ )
+}
+
+async fn incremental_alter(
+ state: &GatewayState,
+ version: i16,
+ resources: Vec<IncrementalAlterConfigsResource>,
+ validate_only: bool,
+) -> IncrementalAlterConfigsResponse {
+ let request = IncrementalAlterConfigsRequest::default()
+ .with_resources(resources)
+ .with_validate_only(validate_only);
+ let outcome =
+ incremental_alter_configs::handle(state, None, version, encode(&request, version)).await;
+ decode(
+ outcome.expect_response("IncrementalAlterConfigs answers"),
+ version,
+ )
+}
+
+/// One resource, one topic: its error code and message.
+async fn incremental_one(
+ state: &GatewayState,
+ version: i16,
+ name: &str,
+ configs: Configs,
+) -> (i16, String) {
+ let response = incremental_alter(
+ state,
+ version,
+ vec![incremental_resource(name, TOPIC, configs)],
+ false,
+ )
+ .await;
+ let resource = &response.responses[0];
+ (
+ resource.error_code,
+ resource
+ .error_message
+ .as_ref()
+ .map_or(String::new(), |message| message.as_str().to_string()),
+ )
+}
+
+/// `retention.ms` as a describe reports it: the value and its config source.
+async fn retention(state: &GatewayState, name: &str) -> (String, i8) {
+ let described = describe(
+ state,
+ DESCRIBE_V4,
+ vec![describe_resource(name, Some(vec!["retention.ms"]))],
+ false,
+ false,
+ )
+ .await;
+ let config = &described.results[0].configs[0];
+ (
+ config
+ .value
+ .as_ref()
+ .map_or(String::new(), |value| value.as_str().to_string()),
+ config.config_source,
+ )
+}
+
fn entry<'a>(
configs: &'a [DescribeConfigsResourceResult],
name: &str,
@@ -632,3 +731,406 @@ async fn alter_configs_rejects_an_empty_list_and_leaves_retention_unchanged() {
);
assert_eq!(described.results[0].configs[0].config_source, SOURCE_TOPIC);
}
+
+#[tokio::test]
+#[serial]
+async fn incremental_alter_configs_sets_deletes_and_validates_retention() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let state = connected_state(&server).await;
+ create_topic(&state, "orders").await;
+
+ let validated = incremental_alter(
+ &state,
+ INCREMENTAL_V1,
+ vec![incremental_resource(
+ "orders",
+ TOPIC,
+ &[("retention.ms", OP_SET, Some("8000"))],
+ )],
+ true,
+ )
+ .await;
+ assert_eq!(validated.responses[0].error_code, ERROR_NONE);
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_DEFAULT),
+ "validate_only must not write"
+ );
+
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[("retention.ms", OP_SET, Some("8000"))]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("8000".to_string(), SOURCE_TOPIC)
+ );
+
+ assert_eq!(
+ incremental_one(&state, INCREMENTAL_V1, "orders", &[]).await,
+ (ERROR_NONE, String::new()),
+ "an empty operation list is a no-op, not a reset"
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("8000".to_string(), SOURCE_TOPIC)
+ );
+
+ // `kafka-configs.sh --delete-config` sends an empty value with its delete.
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[("retention.ms", OP_DELETE, Some(""))]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_TOPIC),
+ "a delete stores never-expire, and the key stays explicitly set"
+ );
+
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V0,
+ "orders",
+ &[("retention.ms", OP_SET, Some("7000"))]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("7000".to_string(), SOURCE_TOPIC)
+ );
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V0,
+ "orders",
+ &[("retention.ms", OP_DELETE, None)]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_TOPIC)
+ );
+
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[("retention.ms", OP_SET, Some("6000"))]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[("retention.ms", OP_DELETE, Some("5000"))]
+ )
+ .await,
+ (ERROR_NONE, String::new()),
+ "the value sent with a delete is ignored"
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_TOPIC)
+ );
+}
+
+/// A delete writes never-expire even where nothing was ever set, so the describe source flips
+/// to the topic although the value does not change. Kafka writes nothing there.
+#[tokio::test]
+#[serial]
+async fn incremental_alter_configs_delete_on_a_never_altered_topic_marks_retention_explicit() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let state = connected_state(&server).await;
+ create_topic(&state, "orders").await;
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_DEFAULT)
+ );
+
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[("retention.ms", OP_DELETE, Some(""))]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_TOPIC)
+ );
+}
+
+/// Request faults are answered without an Iggy call, so a missing topic still gets
+/// `INVALID_REQUEST` for them. Config faults come after the lookup, so a missing topic gets
+/// `UNKNOWN_TOPIC_OR_PARTITION` for those. Nothing in this test writes.
+#[tokio::test]
+#[serial]
+async fn incremental_alter_configs_answers_request_faults_then_config_faults() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let state = connected_state(&server).await;
+ create_topic(&state, "orders").await;
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[("retention.ms", OP_SET, Some("4000"))]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+
+ let request_faults: [(&str, Configs, &str); 4] = [
+ (
+ "orders",
+ &[
+ ("retention.ms", OP_SET, Some("1")),
+ ("retention.ms", OP_SET, Some("2")),
+ ],
+ "Error due to duplicate config keys",
+ ),
+ (
+ "orders",
+ &[("retention.ms", OP_SET, None), ("no.such", OP_SET, None)],
+ "Null value not supported for : retention.ms, no.such",
+ ),
+ (
+ "orders",
+ &[("retention.ms", 7, Some("1"))],
+ "Unknown operations type 7",
+ ),
+ (
+ "missing-topic",
+ &[("retention.ms", 7, Some("1"))],
+ "Unknown operations type 7",
+ ),
+ ];
+ for (name, configs, message) in request_faults {
+ assert_eq!(
+ incremental_one(&state, INCREMENTAL_V1, name, configs).await,
+ (ERROR_INVALID_REQUEST, message.to_string()),
+ "{name}: {configs:?}"
+ );
+ }
+
+ let config_faults: [(Configs, &str); 6] = [
+ (
+ &[("retention.ms", OP_APPEND, Some("1"))],
+ "Can't APPEND to key retention.ms because its type is not LIST.",
+ ),
+ (
+ &[("no.such", OP_SUBTRACT, Some("1"))],
+ "Can't SUBTRACT to key no.such because its type is not LIST.",
+ ),
+ (
+ &[("cleanup.policy", OP_APPEND, Some("compact"))],
+ "cleanup.policy is read-only",
+ ),
+ (
+ &[("no.such", OP_SET, Some("1"))],
+ "unknown config key 'no.such'",
+ ),
+ (
+ &[("cleanup.policy", OP_SET, Some("compact"))],
+ "cleanup.policy is read-only",
+ ),
+ (
+ &[("retention.ms", OP_SET, Some("abc"))],
+ "retention.ms must be -1 or a positive count",
+ ),
+ ];
+ for (configs, message) in config_faults {
+ let (code, text) = incremental_one(&state, INCREMENTAL_V1, "orders", configs).await;
+ assert_eq!(code, ERROR_INVALID_CONFIG, "{configs:?}");
+ assert!(text.starts_with(message), "{configs:?}: {text}");
+ }
+
+ // `validate_only` runs the same checks, so a dry run reports a fault instead of hiding it.
+ let validated = incremental_alter(
+ &state,
+ INCREMENTAL_V1,
+ vec![incremental_resource(
+ "orders",
+ TOPIC,
+ &[
+ ("retention.ms", OP_SET, Some("1")),
+ ("retention.ms", OP_SET, Some("2")),
+ ],
+ )],
+ true,
+ )
+ .await;
+ assert_eq!(validated.responses[0].error_code, ERROR_INVALID_REQUEST);
+ let validated = incremental_alter(
+ &state,
+ INCREMENTAL_V1,
+ vec![incremental_resource(
+ "orders",
+ TOPIC,
+ &[("retention.ms", OP_APPEND, Some("1"))],
+ )],
+ true,
+ )
+ .await;
+ assert_eq!(validated.responses[0].error_code, ERROR_INVALID_CONFIG);
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "missing-topic",
+ &[("no.such", OP_SET, Some("1"))]
+ )
+ .await
+ .0,
+ ERROR_UNKNOWN_TOPIC_OR_PARTITION
+ );
+
+ // A delete of a key this gateway never stored removes nothing, as Kafka answers an
+ // override that was never set.
+ assert_eq!(
+ incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "orders",
+ &[
+ ("no.such", OP_DELETE, None),
+ ("cleanup.policy", OP_DELETE, None)
+ ]
+ )
+ .await,
+ (ERROR_NONE, String::new())
+ );
+
+ let (code, text) = incremental_one(
+ &state,
+ INCREMENTAL_V1,
+ "has a space",
+ &[("retention.ms", OP_SET, Some("1000"))],
+ )
+ .await;
+ assert_eq!(code, ERROR_INVALID_TOPIC_EXCEPTION);
+ assert!(!text.contains("has a space"));
+
+ let nontopic = incremental_alter(
+ &state,
+ INCREMENTAL_V1,
+ vec![incremental_resource(
+ "1",
+ 4,
+ &[("retention.ms", OP_SET, Some("1000"))],
+ )],
+ false,
+ )
+ .await;
+ assert_eq!(nontopic.responses[0].error_code, ERROR_INVALID_REQUEST);
+ assert_eq!(
+ nontopic.responses[0]
+ .error_message
+ .as_ref()
+ .map(StrBytes::as_str),
+ Some("only topic resources are supported")
+ );
+
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("4000".to_string(), SOURCE_TOPIC),
+ "no refused request may write"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn incremental_alter_configs_rejects_every_occurrence_of_a_duplicate_resource() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let state = connected_state(&server).await;
+ create_topic(&state, "orders").await;
+
+ let altered = incremental_alter(
+ &state,
+ INCREMENTAL_V1,
+ vec![
+ incremental_resource("orders", TOPIC, &[("retention.ms", OP_SET, Some("4000"))]),
+ incremental_resource("orders", TOPIC, &[("retention.ms", OP_SET, Some("5000"))]),
+ ],
+ false,
+ )
+ .await;
+ assert_eq!(altered.responses.len(), 2);
+ for resource in &altered.responses {
+ assert_eq!(resource.error_code, ERROR_INVALID_REQUEST);
+ assert_eq!(
+ resource.error_message.as_ref().map(StrBytes::as_str),
+ Some("Each resource must appear at most once.")
+ );
+ }
+ assert_eq!(
+ retention(&state, "orders").await,
+ ("-1".to_string(), SOURCE_DEFAULT)
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn incremental_alter_configs_one_bad_resource_skips_only_that_resource() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let state = connected_state(&server).await;
+ create_topic(&state, "kept").await;
+ create_topic(&state, "changed").await;
+
+ let altered = incremental_alter(
+ &state,
+ INCREMENTAL_V1,
+ vec![
+ incremental_resource(
+ "kept",
+ TOPIC,
+ &[
+ ("retention.ms", OP_SET, Some("4000")),
+ ("no.such", OP_APPEND, Some("1")),
+ ],
+ ),
+ incremental_resource("changed", TOPIC, &[("retention.ms", OP_SET, Some("5000"))]),
+ ],
+ false,
+ )
+ .await;
+ assert_eq!(altered.responses[0].error_code, ERROR_INVALID_CONFIG);
+ assert_eq!(altered.responses[1].error_code, ERROR_NONE);
+ assert_eq!(
+ retention(&state, "kept").await,
+ ("-1".to_string(), SOURCE_DEFAULT)
+ );
+ assert_eq!(
+ retention(&state, "changed").await,
+ ("5000".to_string(), SOURCE_TOPIC)
+ );
+}
diff --git a/gateways/kafka/tests/golden_wire_fixtures_tests.rs b/gateways/kafka/tests/golden_wire_fixtures_tests.rs
index 8b35419ab..f7ee5ba6d 100644
--- a/gateways/kafka/tests/golden_wire_fixtures_tests.rs
+++ b/gateways/kafka/tests/golden_wire_fixtures_tests.rs
@@ -41,11 +41,11 @@ async fn golden_apiversions_v3_flexible_response_fixture() {
.await
.expect_response("test request has acks != 0 and expects a response");
- // error_code=0, api_count=21 (compact array: N+1=22)
+ // error_code=0, api_count=22 (compact array: N+1=23)
// each entry followed by an empty tagged-fields byte; throttle_ms=0; top-level tagged fields
- let expected: [u8; 155] = [
+ let expected: [u8; 162] = [
0x00, 0x00, // error_code
- 0x16, // compact array count (21+1)
+ 0x17, // compact array count (22+1)
0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, // key 0: Produce 0-9 (advertised)
0x00, 0x01, 0x00, 0x04, 0x00, 0x0C, 0x00, // key 1: Fetch 4-12
0x00, 0x02, 0x00, 0x01, 0x00, 0x07, 0x00, // key 2: ListOffsets 1-7
@@ -66,6 +66,7 @@ async fn golden_apiversions_v3_flexible_response_fixture() {
0x00, 0x20, 0x00, 0x01, 0x00, 0x04, 0x00, // key 32: DescribeConfigs 1-4
0x00, 0x21, 0x00, 0x00, 0x00, 0x02, 0x00, // key 33: AlterConfigs 0-2
0x00, 0x25, 0x00, 0x00, 0x00, 0x03, 0x00, // key 37: CreatePartitions 0-3
+ 0x00, 0x2C, 0x00, 0x00, 0x00, 0x01, 0x00, // key 44: IncrementalAlterConfigs 0-1
0x00, 0x3C, 0x00, 0x00, 0x00, 0x02, 0x00, // key 60: DescribeCluster 0-2
0x00, 0x00, 0x00, 0x00, // throttle_ms
0x00, // top-level tagged fields
@@ -80,10 +81,10 @@ async fn golden_apiversions_v1_response_fixture() {
.await
.expect_response("test request has acks != 0 and expects a response");
- // error_code=0, api_count=21; Produce advertises min=0 per KAFKA-18659; throttle_ms=0
- let expected: [u8; 136] = [
+ // error_code=0, api_count=22; Produce advertises min=0 per KAFKA-18659; throttle_ms=0
+ let expected: [u8; 142] = [
0x00, 0x00, // error_code
- 0x00, 0x00, 0x00, 0x15, // api count = 21
+ 0x00, 0x00, 0x00, 0x16, // api count = 22
0x00, 0x00, 0x00, 0x00, 0x00, 0x09, // key 0: Produce 0-9 (advertised)
0x00, 0x01, 0x00, 0x04, 0x00, 0x0C, // key 1: Fetch 4-12
0x00, 0x02, 0x00, 0x01, 0x00, 0x07, // key 2: ListOffsets 1-7
@@ -104,6 +105,7 @@ async fn golden_apiversions_v1_response_fixture() {
0x00, 0x20, 0x00, 0x01, 0x00, 0x04, // key 32: DescribeConfigs 1-4
0x00, 0x21, 0x00, 0x00, 0x00, 0x02, // key 33: AlterConfigs 0-2
0x00, 0x25, 0x00, 0x00, 0x00, 0x03, // key 37: CreatePartitions 0-3
+ 0x00, 0x2C, 0x00, 0x00, 0x00, 0x01, // key 44: IncrementalAlterConfigs 0-1
0x00, 0x3C, 0x00, 0x00, 0x00, 0x02, // key 60: DescribeCluster 0-2
0x00, 0x00, 0x00, 0x00, // throttle_ms
];
diff --git a/gateways/kafka/tests/java/ConfigsProbe.java b/gateways/kafka/tests/java/ConfigsProbe.java
index 454c666f2..b01671269 100644
--- a/gateways/kafka/tests/java/ConfigsProbe.java
+++ b/gateways/kafka/tests/java/ConfigsProbe.java
@@ -23,6 +23,7 @@ import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.AlterConfigOp;
import org.apache.kafka.clients.admin.AlterConfigsOptions;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.ConfigEntry;
@@ -30,7 +31,8 @@ import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.errors.InvalidConfigurationException;
/**
- * Kafka 3.9 AdminClient probe for DescribeConfigs and the deprecated AlterConfigs API.
+ * Kafka 3.9 AdminClient probe for DescribeConfigs, the deprecated AlterConfigs API and
+ * IncrementalAlterConfigs, the only alter API a 4.x client has.
* Prints elapsed time for 50 describes and does not fail on a latency threshold.
*/
public final class ConfigsProbe {
@@ -94,6 +96,32 @@ public final class ConfigsProbe {
"altered retention source");
System.out.println("altered_retention.ms=" + changed.value() + " source=" + changed.source());
+ admin.incrementalAlterConfigs(Map.of(resource, List.of(op("retention.ms", "9000", AlterConfigOp.OpType.SET))))
+ .all()
+ .get();
+ Config incremented = describe(admin, resource);
+ require("9000".equals(incremented.get("retention.ms").value()), "incremental set retention.ms");
+ System.out.println("incremental_set_retention.ms=" + incremented.get("retention.ms").value());
+
+ try {
+ admin.incrementalAlterConfigs(Map.of(resource, List.of(op("retention.ms", "1", AlterConfigOp.OpType.APPEND))))
+ .all()
+ .get();
+ throw new AssertionError("append to a non-list key was accepted");
+ } catch (ExecutionException exception) {
+ if (!(exception.getCause() instanceof InvalidConfigurationException)) {
+ throw exception;
+ }
+ System.out.println("incremental_append_rejected=" + exception.getCause().getClass().getSimpleName());
+ }
+
+ admin.incrementalAlterConfigs(Map.of(resource, List.of(op("retention.ms", "", AlterConfigOp.OpType.DELETE))))
+ .all()
+ .get();
+ Config deleted = describe(admin, resource);
+ require("-1".equals(deleted.get("retention.ms").value()), "incremental delete retention.ms");
+ System.out.println("incremental_delete_retention.ms=" + deleted.get("retention.ms").value());
+
long started = System.nanoTime();
for (int i = 0; i < 50; i++) {
describe(admin, resource);
@@ -112,6 +140,10 @@ public final class ConfigsProbe {
return new Config(List.of(new ConfigEntry(name, value)));
}
+ private static AlterConfigOp op(String name, String value, AlterConfigOp.OpType type) {
+ return new AlterConfigOp(new ConfigEntry(name, value), type);
+ }
+
private static void require(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
diff --git a/gateways/kafka/tests/kafka_client_e2e_tests.rs b/gateways/kafka/tests/kafka_client_e2e_tests.rs
index 04de935a9..65b03d557 100644
--- a/gateways/kafka/tests/kafka_client_e2e_tests.rs
+++ b/gateways/kafka/tests/kafka_client_e2e_tests.rs
@@ -1155,6 +1155,98 @@ fn kafka_topics(gateway: SocketAddr, args: &[&str]) -> ClientRun {
run_client(KAFKA_IMAGE, &full_args, &[])
}
+/// Runs `kafka-configs.sh` with `args` against `gateway`, with SASL off like [`kafka_topics`].
+fn kafka_configs(gateway: SocketAddr, args: &[&str]) -> ClientRun {
+ let bootstrap = gateway.to_string();
+ let mut full_args: Vec<&str> = vec![
+ "/opt/kafka/bin/kafka-configs.sh",
+ "--bootstrap-server",
+ &bootstrap,
+ ];
+ full_args.extend_from_slice(args);
+ run_client(KAFKA_IMAGE, &full_args, &[])
+}
+
+/// `kafka-configs.sh --alter` on a topic sends only `IncrementalAlterConfigs` (44): a `SET` for
+/// `--add-config` and a `DELETE` for `--delete-config`, after a describe of the topic's dynamic
+/// configs. This is the real-tool round trip for that key through the bridge.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn given_kafka_configs_sh_when_adding_then_deleting_retention_should_round_trip_through_the_bridge()
+ {
+ let Some((_server, gateway)) = bridged_stack().await else {
+ return;
+ };
+ let completed = format!("Completed updating config for topic {TOPIC}.");
+
+ let added = kafka_configs(
+ gateway,
+ &[
+ "--alter",
+ "--entity-type",
+ "topics",
+ "--entity-name",
+ TOPIC,
+ "--add-config",
+ "retention.ms=8000",
+ ],
+ )
+ .expect_ran("kafka-configs.sh --add-config");
+ assert!(
+ added.contains(&completed),
+ "kafka-configs.sh must report the alter completed, got: {added}"
+ );
+
+ let described = kafka_configs(
+ gateway,
+ &[
+ "--describe",
+ "--entity-type",
+ "topics",
+ "--entity-name",
+ TOPIC,
+ ],
+ )
+ .expect_ran("kafka-configs.sh --describe after --add-config");
+ assert!(
+ described.contains("retention.ms=8000 sensitive=false"),
+ "the describe must show the stored retention.ms, got: {described}"
+ );
+
+ let deleted = kafka_configs(
+ gateway,
+ &[
+ "--alter",
+ "--entity-type",
+ "topics",
+ "--entity-name",
+ TOPIC,
+ "--delete-config",
+ "retention.ms",
+ ],
+ )
+ .expect_ran("kafka-configs.sh --delete-config");
+ assert!(
+ deleted.contains(&completed),
+ "kafka-configs.sh must report the delete completed, got: {deleted}"
+ );
+
+ let described_after = kafka_configs(
+ gateway,
+ &[
+ "--describe",
+ "--entity-type",
+ "topics",
+ "--entity-name",
+ TOPIC,
+ ],
+ )
+ .expect_ran("kafka-configs.sh --describe after --delete-config");
+ assert!(
+ described_after.contains("retention.ms=-1 sensitive=false"),
+ "a deleted retention.ms reads as never expire, got: {described_after}"
+ );
+}
+
/// #3546's own acceptance criterion: `kafka-topics.sh` must work against the gateway for create
/// and delete. (`--describe` needs `DescribeConfigs`, not yet implemented, so it is not covered
/// here.) Runs against the bridged stack, since this exercises the real `CreateTopics`/
diff --git a/gateways/kafka/tests/version_firewall_tests.rs b/gateways/kafka/tests/version_firewall_tests.rs
index 8c61c798a..3b8df9ba1 100644
--- a/gateways/kafka/tests/version_firewall_tests.rs
+++ b/gateways/kafka/tests/version_firewall_tests.rs
@@ -39,11 +39,12 @@ use tokio::net::TcpStream;
use iggy_gateway_kafka::protocol::api::{
API_KEY_ALTER_CONFIGS, API_KEY_API_VERSIONS, API_KEY_CREATE_PARTITIONS, API_KEY_CREATE_TOPICS,
API_KEY_DELETE_TOPICS, API_KEY_DESCRIBE_CONFIGS, API_KEY_DESCRIBE_GROUPS, API_KEY_FETCH,
- API_KEY_FIND_COORDINATOR, API_KEY_HEARTBEAT, API_KEY_INIT_PRODUCER_ID, API_KEY_JOIN_GROUP,
- API_KEY_LEAVE_GROUP, API_KEY_LIST_GROUPS, API_KEY_LIST_OFFSETS, API_KEY_METADATA,
- API_KEY_OFFSET_COMMIT, API_KEY_OFFSET_FETCH, API_KEY_PRODUCE, API_KEY_SYNC_GROUP,
- ERROR_INVALID_REQUEST, ERROR_NONE, ERROR_UNSUPPORTED_VERSION, advertised_min_version,
- handle_request, is_supported_version, supported_api_ranges,
+ API_KEY_FIND_COORDINATOR, API_KEY_HEARTBEAT, API_KEY_INCREMENTAL_ALTER_CONFIGS,
+ API_KEY_INIT_PRODUCER_ID, API_KEY_JOIN_GROUP, API_KEY_LEAVE_GROUP, API_KEY_LIST_GROUPS,
+ API_KEY_LIST_OFFSETS, API_KEY_METADATA, API_KEY_OFFSET_COMMIT, API_KEY_OFFSET_FETCH,
+ API_KEY_PRODUCE, API_KEY_SYNC_GROUP, ERROR_INVALID_REQUEST, ERROR_NONE,
+ ERROR_UNSUPPORTED_VERSION, advertised_min_version, handle_request, is_supported_version,
+ supported_api_ranges,
};
use codec::Decoder;
@@ -61,15 +62,16 @@ use wire::{
build_create_topics_empty_request, build_delete_topics_empty_request,
build_describe_configs_empty_request, build_describe_groups_request,
build_fetch_empty_topics_request, build_find_coordinator_request, build_heartbeat_request,
- build_init_producer_id_request, build_join_group_request, build_leave_group_request,
- build_list_groups_request, build_list_offsets_request, build_metadata_all_topics_flexible,
+ build_incremental_alter_configs_empty_request, build_init_producer_id_request,
+ build_join_group_request, build_leave_group_request, build_list_groups_request,
+ build_list_offsets_request, build_metadata_all_topics_flexible,
build_metadata_all_topics_legacy, build_metadata_flexible_request_v10,
build_offset_commit_request, build_offset_fetch_request, build_sync_group_request,
};
#[test]
-fn supported_ranges_table_has_twenty_one_entries() {
- assert_eq!(supported_api_ranges().len(), 21);
+fn supported_ranges_table_has_twenty_two_entries() {
+ assert_eq!(supported_api_ranges().len(), 22);
}
#[test]
@@ -109,8 +111,8 @@ fn is_supported_version_matches_scope_table() {
/// in that order (Produce, Fetch, `ListOffsets`, Metadata, `OffsetCommit`, `OffsetFetch`,
/// `FindCoordinator`, `JoinGroup`, Heartbeat, `LeaveGroup`, `SyncGroup`, `DescribeGroups`,
/// `ListGroups`, `ApiVersions`, `CreateTopics`, `DeleteTopics`, `InitProducerId`,
-/// `DescribeConfigs`, `AlterConfigs`, `CreatePartitions`, `DescribeCluster`).
-/// `supported_ranges_table_has_twenty_one_entries` and `is_supported_version_matches_scope_table`
+/// `DescribeConfigs`, `AlterConfigs`, `CreatePartitions`, `IncrementalAlterConfigs`, `DescribeCluster`).
+/// `supported_ranges_table_has_twenty_two_entries` and `is_supported_version_matches_scope_table`
/// pin that both tables cover the same keys.
#[tokio::test]
async fn apiversions_advertises_exact_supported_ranges_v1() {
@@ -533,6 +535,7 @@ fn request_body_for_scoped_api(api_key: i16, name: &str, version: i16) -> Bytes
API_KEY_LIST_GROUPS => build_list_groups_request(version, &[], &[]),
API_KEY_DESCRIBE_CONFIGS => build_describe_configs_empty_request(version),
API_KEY_ALTER_CONFIGS => build_alter_configs_empty_request(version),
+ API_KEY_INCREMENTAL_ALTER_CONFIGS => build_incremental_alter_configs_empty_request(version),
API_KEY_OFFSET_COMMIT => build_offset_commit_request(version, "scope-group", "orders", 0),
API_KEY_OFFSET_FETCH => build_offset_fetch_request(version, "scope-group", Some("orders")),
_ => Bytes::new(),
@@ -927,3 +930,40 @@ async fn corrupt_alter_configs_overlong_count_returns_invalid_request_error() {
assert_eq!(d.read_i32().unwrap(), 1, "responses len");
assert_eq!(d.read_i16().unwrap(), ERROR_INVALID_REQUEST);
}
+
+/// v0 is legacy. A count that stops mid-integer never reaches `kafka_protocol`.
+#[tokio::test]
+async fn corrupt_incremental_alter_configs_truncated_body_returns_invalid_request_error() {
+ let body = Bytes::from_static(&[0xFF, 0xFF, 0xFF]);
+ let resp = handle_request(
+ API_KEY_INCREMENTAL_ALTER_CONFIGS,
+ 0,
+ body,
+ &default_broker(),
+ )
+ .await
+ .expect_response("IncrementalAlterConfigs v0 has an encodable error response");
+ let mut d = Decoder::new(resp);
+ assert_eq!(d.read_i32().unwrap(), 0, "throttle");
+ assert_eq!(d.read_i32().unwrap(), 1, "responses len");
+ assert_eq!(d.read_i16().unwrap(), ERROR_INVALID_REQUEST);
+}
+
+/// v1 is flexible: the error body carries a compact array, and the count that is rejected is a
+/// compact varint rather than an `i32`.
+#[tokio::test]
+async fn corrupt_incremental_alter_configs_overlong_compact_count_returns_invalid_request_error() {
+ let body = Bytes::from_static(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
+ let resp = handle_request(
+ API_KEY_INCREMENTAL_ALTER_CONFIGS,
+ 1,
+ body,
+ &default_broker(),
+ )
+ .await
+ .expect_response("IncrementalAlterConfigs v1 has an encodable error response");
+ let mut d = Decoder::new(resp);
+ assert_eq!(d.read_i32().unwrap(), 0, "throttle");
+ assert_eq!(d.read_varint().unwrap(), 2, "responses len + 1");
+ assert_eq!(d.read_i16().unwrap(), ERROR_INVALID_REQUEST);
+}
diff --git a/gateways/kafka/tools/kafka-tool/README.md b/gateways/kafka/tools/kafka-tool/README.md
index 03a3eb462..75bac6871 100644
--- a/gateways/kafka/tools/kafka-tool/README.md
+++ b/gateways/kafka/tools/kafka-tool/README.md
@@ -230,8 +230,8 @@ Kafka introduced "flexible" encoding (compact ULEB128 strings/arrays) starting a
### API Key Coverage
-- **Explicit builders (28 API keys):** Produce, Fetch, ListOffsets, Metadata, OffsetCommit, OffsetFetch, FindCoordinator, JoinGroup, Heartbeat, LeaveGroup, SyncGroup, DescribeGroups, ListGroups, SaslHandshake, ApiVersions, CreateTopics, DeleteTopics, DeleteRecords, InitProducerId, AddPartitionsToTxn, AddOffsetsToTxn, EndTxn, TxnOffsetCommit, DescribeConfigs, AlterConfigs, SaslAuthenticate, CreatePartitions, DescribeCluster
-- **Header-framing test (36 API keys):** All remaining API keys are framed correctly with an empty payload — useful for testing that your server returns a proper error response rather than crashing
+- **Explicit builders (29 API keys):** Produce, Fetch, ListOffsets, Metadata, OffsetCommit, OffsetFetch, FindCoordinator, JoinGroup, Heartbeat, LeaveGroup, SyncGroup, DescribeGroups, ListGroups, SaslHandshake, ApiVersions, CreateTopics, DeleteTopics, DeleteRecords, InitProducerId, AddPartitionsToTxn, AddOffsetsToTxn, EndTxn, TxnOffsetCommit, DescribeConfigs, AlterConfigs, SaslAuthenticate, CreatePartitions, IncrementalAlterConfigs, DescribeCluster
+- **Header-framing test (35 API keys):** All remaining API keys are framed correctly with an empty payload — useful for testing that your server returns a proper error response rather than crashing
---
diff --git a/gateways/kafka/tools/kafka-tool/src/main.rs b/gateways/kafka/tools/kafka-tool/src/main.rs
index c85126c4d..9100f4588 100644
--- a/gateways/kafka/tools/kafka-tool/src/main.rs
+++ b/gateways/kafka/tools/kafka-tool/src/main.rs
@@ -27,6 +27,10 @@ use kafka_protocol::messages::delete_records_request::*;
use kafka_protocol::messages::delete_topics_request::*;
use kafka_protocol::messages::describe_configs_request::*;
use kafka_protocol::messages::fetch_request::*;
+use kafka_protocol::messages::incremental_alter_configs_request::{
+ AlterConfigsResource as IncrementalAlterConfigsResource,
+ AlterableConfig as IncrementalAlterableConfig,
+};
use kafka_protocol::messages::join_group_request::*;
use kafka_protocol::messages::leave_group_request::MemberIdentity;
use kafka_protocol::messages::list_offsets_request::*;
@@ -588,6 +592,21 @@ fn build_payload(api_key: i16, version: i16) -> Result<Bytes> {
.encode(&mut buf, version)
.context("CreatePartitions")?;
}
+ 44 => {
+ let config = IncrementalAlterableConfig::default()
+ .with_name(StrBytes::from_static_str("retention.ms"))
+ .with_config_operation(0)
+ .with_value(Some(StrBytes::from_static_str("60000")));
+ let resource = IncrementalAlterConfigsResource::default()
+ .with_resource_type(2)
+ .with_resource_name(StrBytes::from_static_str("test-topic"))
+ .with_configs(vec![config]);
+ IncrementalAlterConfigsRequest::default()
+ .with_resources(vec![resource])
+ .with_validate_only(false)
+ .encode(&mut buf, version)
+ .context("IncrementalAlterConfigs")?;
+ }
60 => {
DescribeClusterRequest::default()
.with_include_cluster_authorized_operations(false)