You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by "ryerraguntla (via GitHub)" <gi...@apache.org> on 2026/09/03 02:39:21 UTC
[PR] feat(gateways): Iggy Kafka bridge core (#3533) [iggy]
ryerraguntla opened a new pull request, #4043:
URL: https://github.com/apache/iggy/pull/4043
## Summary
- Initial Kafka–Iggy bridge core for #3533
## Test plan
- [ ] `cargo test -p iggy-gateway-kafka` (or crate name you use)
- [ ] CI required checks green
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020287040
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
+
+/// Wraps a single Iggy client call in [`REQUEST_TIMEOUT`]. See that constant's doc for why every
+/// bridge method needs this, not just [`IggyBridge::connect`].
+async fn with_request_timeout<T>(
+ op: impl Future<Output = Result<T, IggyError>>,
+) -> Result<T, BridgeError> {
+ tokio::time::timeout(REQUEST_TIMEOUT, op)
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)
+}
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+///
+/// One `IggyClient`, shared across every Kafka connection this gateway serves - and the SDK's TCP
+/// transport is lockstep, one request in flight at a time (`tcp_client.rs`: "the connection is
+/// lockstep", its stream mutex held across write, flush, and read). Every concurrent Kafka
+/// connection ends up serialized behind whichever single Iggy request is in flight; the Kafka
+/// side's own connection limit does nothing to relieve this. No pooling exists yet - `close`
+/// already takes `self` by value, which anticipates an eventual `Arc`-shared bridge, but nothing
+/// wires that up today. Documented here and in the README rather than silently discovered under
+/// load once `#3535`/`#3536` land.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ with_request_timeout(client.connect()).await?;
Review Comment:
Merged CONNECT_TIMEOUT/REQUEST_TIMEOUT into one constant.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3965758069
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
Review Comment:
yes, `disconnect()` forgets the session overlay and leaves `AutoLogin` + the heartbeat task. The next `ping` hits `NotConnected`, which is retriable, so the SDK redials.
Will change to `close(self) -> Result<(), BridgeError>` calling `self.client.shutdown()`. Heartbeat then sees `ClientShutdown` and exits; `Drop` still aborts the handle.
Doc will note this cannot be called through an `Arc`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5658664944
/ready
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967909782
##########
gateways/kafka/Cargo.toml:
##########
@@ -34,11 +34,14 @@ path = "src/main.rs"
[dependencies]
bytes = { workspace = true }
+iggy = { workspace = true }
Review Comment:
Agreed. Not changing `Cargo.lock` grouping or rail config in this PR. The reverse-dep on `core/sdk` is inherent once the gateway speaks Iggy; isolating those tests is a CI/rail follow-up, not a bridge-module change.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967505414
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
Review Comment:
Kafka’s text for 37 is “number of partitions is below 1”, which is not this case.
Will map `PartitionCountMismatch` to `TOPIC_ALREADY_EXISTS` (36) and add `ERROR_TOPIC_ALREADY_EXISTS` in `protocol/api.rs`. Still not a perfect Kafka analogue (the topic exists, but with a *different* count); 36 is the closest code that does not lie about “< 1 partitions”.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001467653
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ // `TryFrom<GetTopicResponse> for TopicDetails` (wire_conversions.rs) sorts `partitions` by
+ // `id` on every decode, so a binary search is correct here, not just faster than the
+ // linear scan it replaces - for a 1000-partition topic, the difference is O(log n) vs
+ // O(n) probes on every high_watermark call.
+ let partition_details = match details
+ .partitions
+ .binary_search_by_key(&partition, |p| p.id)
+ {
+ Ok(index) => &details.partitions[index],
+ Err(_) => {
+ return Err(BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the
+ // wrong (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ });
+ }
+ };
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
+ 0
+ } else {
+ partition_details.current_offset + 1
Review Comment:
**Fixed** - saturating_add(1), no reason not to given the input is wire-decoded.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001605226
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,287 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches `DEFAULT_ROOT_USERNAME` (`core/server/src/boot/credentials.rs`) - the root user's
+/// username is always `iggy` regardless of how its password was provisioned, so defaulting this
+/// one field is safe. The password is a different story - see why there is no
+/// `DEFAULT_IGGY_PASSWORD` at [`IggyBridgeConfig::from_env`].
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
+ /// surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in `core/configs`, so the
+ /// central provider's own typo-detection doesn't cover this namespace either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root username.
+ ///
+ /// `IGGY_KAFKA_IGGY_PASSWORD` has no default and must be set explicitly. `iggy-server` only
+ /// provisions the well-known `iggy`/`iggy` root credentials when started with
+ /// `--with-default-root-credentials` (`args.rs`, itself documented "INSECURE - FOR DEVELOPMENT
+ /// ONLY!"); without that flag it generates a random password (`boot/credentials.rs`) that no
+ /// constant here could ever guess. Defaulting the password to `"iggy"` would make this bridge
+ /// silently authenticate as root, with the credential in no config file and no log, on any
+ /// server that does happen to run dev-flagged - the failure mode of getting it wrong is a
+ /// loud, immediate auth rejection instead.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_IGGY_PASSWORD` is unset, or if
+ /// `IGGY_KAFKA_TOPIC_MAP_PATH` is set but the file is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD").map_err(|_| {
Review Comment:
**Fixed** - both now checked explicitly, with tests, and the doc comment updated to say "unset or empty" as you noted it should.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5573197443
@ryerraguntla I'll review it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal merged PR #4043:
URL: https://github.com/apache/iggy/pull/4043
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3965798959
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,204 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::TopicMapping;
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches the Iggy server's own default root user - not a made-up example, the same default
+/// every fresh `iggy-server` and every CLI quick-start in this repo uses.
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+const DEFAULT_IGGY_PASSWORD: &str = "iggy";
Review Comment:
Fixing the comment : `--with-default-root-credentials` defaults to false and is labelled insecure. A gateway that defaults the password to `iggy` logs in as root on any server started with that flag, with the secret in neither file nor log.
Will drop `DEFAULT_IGGY_PASSWORD`, require `IGGY_KAFKA_IGGY_PASSWORD` in `from_env`, and fix the comment. Tests already pass the password explicitly.
Leaving `IGGY_KAFKA_IGGY_USERNAME` defaulting to `iggy` unless you want that required too — password is the actual secret.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001646162
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. See `IggyBridge::connect`'s doc comment.
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
+still fall back to the default rule.
+
+### Provisioning and idempotency
+
+`ensure_stream_and_topic(kafka_topic, partition_count)` creates the mapped Iggy stream and topic
+if either is missing. Idempotent when repeated with the *same* `partition_count`: a no-op if both
+already exist with that count, and a `NameAlreadyExists` race against a concurrent caller creating
+the same stream/topic is treated as success, not an error - the goal is "it exists," not "this
+call created it." A *different* `partition_count` against an already-existing topic returns
+`BridgeError::PartitionCountMismatch` rather than silently keeping the old count or growing it -
+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. Nothing is bounding retention until it's configured explicitly (Iggy's own topic options,
+outside this bridge today); repointing a Kafka app that assumes bounded retention onto this bridge
+will accumulate data indefinitely unless you set that up yourself.
+
+### Error mapping
+
+`BridgeError::to_kafka_error_code()` maps Iggy failures to Kafka wire error codes - stream/topic
+not found → `UNKNOWN_TOPIC_OR_PARTITION` (3), auth/credential failures →
+`TOPIC_AUTHORIZATION_FAILED` (29), connection-shaped failures → `NOT_LEADER_OR_FOLLOWER` (6, the
+same retriable code the foundation's own stubs send, so a client backs off and retries),
+`PartitionCountMismatch` → `TOPIC_ALREADY_EXISTS` (36, not `INVALID_PARTITIONS` - that code's own
+text is "below 1", a different condition), anything else → `UNKNOWN_SERVER_ERROR` (-1).
Review Comment:
**Fixed** - added the missing line, table is now exhaustive again.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001466282
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
Review Comment:
**Fixed** - reworded to offset_frontier vs mint_frontier explicitly, and flagged that a future Produce handler predicting a base offset from this would be wrong post-crash.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020498006
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,345 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches `DEFAULT_ROOT_USERNAME` (`core/server/src/boot/credentials.rs`) - the root user's
+/// username is always `iggy` regardless of how its password was provisioned, so defaulting this
+/// one field is safe. The password is a different story - see why there is no
+/// `DEFAULT_IGGY_PASSWORD` at [`IggyBridgeConfig::from_env`].
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. `main.rs`'s
+ /// `reject_unknown_kafka_env_vars` checks this list *and* its own separate
+ /// `KNOWN_KAFKA_ENV_VARS`, not one merged copy - a var added only here is already
+ /// recognized there with no corresponding edit needed, and vice versa. A var this module
+ /// reads still has to be listed *somewhere* the guard checks, or a typo silently no-ops
+ /// instead of surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in
+ /// `core/configs`, so the central provider's own typo-detection doesn't cover this namespace
+ /// either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root username.
+ ///
+ /// `IGGY_KAFKA_IGGY_PASSWORD` has no default and must be set explicitly. `iggy-server` only
+ /// provisions the well-known `iggy`/`iggy` root credentials when started with
+ /// `--with-default-root-credentials` (`args.rs`, itself documented "INSECURE - FOR DEVELOPMENT
+ /// ONLY!"); without that flag it generates a random password (`boot/credentials.rs`) that no
+ /// constant here could ever guess. Defaulting the password to `"iggy"` would make this bridge
+ /// silently authenticate as root, with the credential in no config file and no log, on any
+ /// server that does happen to run dev-flagged - the failure mode of getting it wrong is a
+ /// loud, immediate auth rejection instead.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_IGGY_PASSWORD` is unset or empty, if
+ /// `IGGY_KAFKA_IGGY_USERNAME` is set but empty, or if `IGGY_KAFKA_TOPIC_MAP_PATH` is set but
+ /// the file is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ // set-but-empty (`VAR=""`) is `Ok("")` from `env::var`, not `Err` - distinct from unset,
+ // and unchecked here would otherwise pass both cleanly through to a login attempt neither
+ // could ever satisfy.
+ if username.is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_USERNAME must not be empty".to_string(),
+ ));
+ }
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD").map_err(|_| {
+ BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_PASSWORD must be set - iggy-server generates a random root \
+ password unless started with --with-default-root-credentials, so there is no \
+ safe default to fall back to"
+ .to_string(),
+ )
+ })?;
+ if password.is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_PASSWORD must not be empty".to_string(),
+ ));
+ }
+ let stream_env = std::env::var("IGGY_KAFKA_IGGY_STREAM").ok();
+ // TopicMapping::new (below, on the no-file branch) validates default_stream too now, so
+ // removing this check wouldn't let an invalid value through uncaught - but its own message
+ // would say "topic mapping's default_stream", not IGGY_KAFKA_IGGY_STREAM, leaving whoever
+ // reads the error to work out which env var that phrase actually refers to. Checked here
+ // first so the message names the var an operator can actually go fix.
+ if let Some(ref stream) = stream_env {
Review Comment:
Moved IGGY_KAFKA_IGGY_STREAM validation into the no-file branch only.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020517195
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Locates the already-built `iggy-server` binary. Does not build it - see this crate's
+/// `docs/TEST_SUITE.md` for the prerequisite, the same one `core/integration`'s own
+/// server-spawning tests already carry.
+///
+/// `assert_cmd::cargo::cargo_bin`, matching `core/integration`'s own
+/// `harness::handle::server::start` - not a from-scratch `cargo build` invocation. An earlier
+/// version of this function drove `cargo build --package server --bin iggy-server` directly,
+/// reasoning that `Command::cargo_bin` "only resolves `CARGO_BIN_EXE_*` for binaries owned by
+/// *this* package" - true of the `CARGO_BIN_EXE_*` env-var lookup alone, but `cargo_bin` falls
+/// back to `legacy_cargo_bin` when that's unset, which derives the target directory from
+/// `env::current_exe()` (this test binary's own path) and looks for a same-named file there -
+/// correct under `CARGO_TARGET_DIR`, `--release`, or a `--target` triple subdirectory precisely
+/// because it reads back from where cargo actually placed *this* binary, not a guessed path. That
+/// version also re-ran a `cargo build` from every one of this file's server-spawning tests
+/// (nextest runs each as its own process, so the `OnceLock` memoized nothing across them),
+/// serialized by `.config/nextest.toml`'s `kafka_bridge` test-group but still real, avoidable
+/// per-test overhead this version has none of.
+fn iggy_server_binary() -> PathBuf {
+ assert_cmd::cargo::cargo_bin("iggy-server")
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ password: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with the default `iggy`/`iggy` root credentials. See
+ /// [`Self::spawn_with_password`] for the general form.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ Self::spawn_with_password(data_dir, "iggy").await
+ }
+
+ /// Spawns `iggy-server` with an isolated temp data dir, a locked TCP port, and the given root
+ /// password, then blocks until its listener is ready or the startup budget is exhausted.
+ ///
+ /// A dedicated password parameter (not just the `spawn()` default everywhere) lets a
+ /// password-shaped regression test (special characters, say) reuse this harness's
+ /// `PortGuard`/graceful-`Drop`/`wait_ready` machinery instead of hand-rolling a second,
+ /// `Drop`-less spawn: a `Drop`-less copy has no guard to run `graceful_kill` on a panic before
+ /// its assertions, orphaning a process that still holds its `PortGuard` slot, which then
+ /// fails the next test that draws that slot to bind.
+ async fn spawn_with_password(data_dir: &std::path::Path, password: &str) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
Review Comment:
Added IGGY_SHARDING_CPU_ALLOCATION=0..4.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020274046
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
+
+/// Wraps a single Iggy client call in [`REQUEST_TIMEOUT`]. See that constant's doc for why every
+/// bridge method needs this, not just [`IggyBridge::connect`].
+async fn with_request_timeout<T>(
+ op: impl Future<Output = Result<T, IggyError>>,
+) -> Result<T, BridgeError> {
+ tokio::time::timeout(REQUEST_TIMEOUT, op)
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
Review Comment:
Added BridgeError::Timeout → REQUEST_TIMED_OUT (7), not borrowed CannotEstablishConnection's retriable code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5618300139
@krishvishal - prechecks for BDD are failing (foreign cpp). I will look into it and retrigger the build. Meanwhile please go ahead and review the PR
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core (#3533) [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5519505586
/author
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001364509
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
Review Comment:
**Fixed**. TopicMapping's fields are now private; Deserialize moved to a private RawTopicMapping, and TopicMapping::new(default_stream, topics) -> Result<Self, BridgeError> is the sole checked constructor - used by both from_toml_str and the no-file path in config.rs, and by every direct construction in tests.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001454891
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
Review Comment:
**Acknowledged**, no code change needed -(36, TOPIC_ALREADY_EXISTS) and README already agree; only the PR description text is stale.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020521758
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,120 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up high watermarks (one or many partitions of
+a topic per call) for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The initial connect retries a fixed, bounded number of times (`RECONNECTION_RETRIES = 3`, not the
+Iggy SDK client's own default of unlimited retries, one dial per second, forever), and the whole
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so `IggyBridge::connect`
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. Every other bridge call (`ensure_stream_and_topic`,
+`high_watermark(s)`, `close`) carries its own `REQUEST_TIMEOUT` (same 15s bound) for the same
+reason: the SDK reconnects internally, mid-call, on a transport error, through the same
+undead-lined dial path - a bridge call made well after the initial connect can still hit this if
+Iggy becomes unreachable later. See `IggyBridge`'s own doc comment (its rustdoc is private, so
+this isn't a followable link outside the crate - read the source at `src/bridge/iggy_bridge.rs`).
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
+still fall back to the default rule.
+
+`default_stream` is required in a map file - it has no `#[serde(default)]`, unlike `topics` -
+so an override-only file with no `default_stream` key fails to load rather than falling back to
+`kafka`. When both `IGGY_KAFKA_TOPIC_MAP_PATH` and `IGGY_KAFKA_IGGY_STREAM` are set, the file's own
+`default_stream` always wins and the env var is ignored entirely: a TOML file is a complete mapping
+document, not an overlay on top of the env var.
+
+### Provisioning and idempotency
+
+`ensure_stream_and_topic(kafka_topic, partition_count)` creates the mapped Iggy stream and topic
+if either is missing. Idempotent when repeated with the *same* `partition_count`: a no-op if both
+already exist with that count, and a `NameAlreadyExists` race against a concurrent caller creating
+the same stream/topic is treated as success, not an error - the goal is "it exists," not "this
+call created it." A *different* `partition_count` against an already-existing topic returns
+`BridgeError::PartitionCountMismatch` rather than silently keeping the old count or growing it -
+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. Nothing is bounding retention until it's configured explicitly (Iggy's own topic options,
+outside this bridge today); repointing a Kafka app that assumes bounded retention onto this bridge
+will accumulate data indefinitely unless you set that up yourself.
+
+They also use Iggy's default **durability**, `Durability::Replicated` - quorum commit without an
+additional stable-storage barrier, with the disk write itself threshold-gated (flushed at 1024
+messages or 1 MiB of unflushed data, whichever comes first). Kafka's own defaults take the same
+posture, so this isn't a wrong choice, but on a single node both can lose an acked write to a power
+cut before that threshold is reached - worth knowing rather than discovering later.
+
+### Concurrency ceiling
+
+One `IggyBridge` (one `IggyClient`) is meant to serve every Kafka connection this gateway handles,
+and the Iggy SDK's TCP transport is lockstep - one request in flight per client, its stream mutex
+held across write, flush, and read. Every concurrent Kafka connection ends up serialized behind
+whichever single Iggy request is in flight; the Kafka side's own connection limit
+(`IGGY_KAFKA_MAX_CONNECTIONS`) does nothing to relieve this. No connection pooling exists yet - it
+is a known gap to address before `#3535`/`#3536` put this on a hot path, not a design decision to
+rely on.
+
+### Error mapping
+
+`BridgeError::to_kafka_error_code()` maps Iggy failures to Kafka wire error codes:
+
+- Stream/topic/partition not found → `UNKNOWN_TOPIC_OR_PARTITION` (3)
+- A rejected *permission* (`Unauthorized`) → `TOPIC_AUTHORIZATION_FAILED` (29) - a real,
+ fixable-by-the-Kafka-operator ACL problem
+- A rejected *login* (the bridge's own `IGGY_KAFKA_IGGY_USERNAME`/`_PASSWORD` are wrong) →
+ `UNKNOWN_SERVER_ERROR` (-1), deliberately **not** 29 - the Kafka client can't fix a bridge-side
+ credential misconfiguration, and blaming its own ACLs for one is worse than an unexplained
+ fatal error
+- Connection-shaped failures → `NOT_LEADER_OR_FOLLOWER` (6, the same retriable code the
+ foundation's own stubs send, so a client backs off and retries)
+- An Iggy commit whose outcome is genuinely unknown (`TransientNotCommitted`) →
+ `REQUEST_TIMED_OUT` (7) - retriable in real Kafka too, chosen because it's what a real broker
+ sends for the same shape of failure, not to make a client stop retrying
+- An invalid Kafka-side topic name (empty, whitespace-padded, oversized, illegal characters) →
+ `INVALID_TOPIC_EXCEPTION` (17), checked before any Iggy call is made
+- `PartitionCountMismatch` → `TOPIC_ALREADY_EXISTS` (36, not `INVALID_PARTITIONS` - that code's
+ own text is "below 1", a different condition)
+- Anything else → `UNKNOWN_SERVER_ERROR` (-1)
Review Comment:
Added missing TooManyPartitions → INVALID_PARTITIONS (37) bullet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3968288288
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count` as segments are dropped
+ /// (`core/partitions/src/iggy_partition.rs::decrement_messages_count`) but never rewinds
+ /// `current_offset` - a fully-retention-purged partition that has produced messages reports
+ /// `messages_count == 0` with `current_offset` still at its high value. Treating that as
+ /// "empty" would report high watermark `0` for a partition that has, in fact, produced past
+ /// offset `0`; a future `ListOffsets` (`#3537`) LATEST built on this would rewind instead of
+ /// pointing at the true next-write position.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ let partition_details = details
Review Comment:
good one, now uses binary_search_by_key — verified TopicDetails::partitions is always sorted by id (wire_conversions.rs), so this is correctness-preserving, not just faster.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3954378536
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthenticated
+ | IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
Review Comment:
**CRITICAL** (same match as the `_` arm below, opposite direction).
`Unauthenticated` maps to 29, which is `retriable=false`. But `core/common/src/traits/binary_auth.rs:27` shows `ClientState::Connected => Err(IggyError::Unauthenticated)`, i.e. it is the window between the socket coming up and auto-sign-in finishing, not an authorization decision. The SDK itself lists it as retriable at `tcp_client.rs:219`.
So a brief reconnect kills a consumer thread with "Not authorized to access topics", sending whoever is on call to audit Kafka ACLs that don't exist in this gateway. The same code also fires for a wrong `IGGY_KAFKA_IGGY_PASSWORD`, which is the gateway's own config fault reported as the client's ACL problem.
Suggested: move `Unauthenticated` to `ERROR_NOT_LEADER_OR_FOLLOWER` (6) and keep 29 for `Unauthorized` only. `unauthenticated_maps_to_topic_authorization_failed` asserts the current mapping, so it needs updating alongside.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthenticated
+ | IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected | IggyError::CannotEstablishConnection => {
+ ERROR_NOT_LEADER_OR_FOLLOWER
+ }
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
Review Comment:
**CRITICAL.** This map doesn't match the error types the SDK actually returns.
The SDK's retriable set is at `core/sdk/src/tcp/tcp_client.rs:215-224`: `Disconnected | EmptyResponse | Unauthenticated | StaleClient | NotConnected | CannotEstablishConnection | TcpError`. This map covers two of those seven; the rest land here and become `ERROR_UNKNOWN_SERVER_ERROR`, which `kafka-protocol-0.18.0/src/error.rs:183` marks `retriable=false`. A producer drops the batch instead of retrying.
Two of the missing five are common. `send_raw` returns `NotConnected` for any call made while the client is `Disconnected` or `Connecting` (`tcp_client.rs:1234-1241`), so every call during a reconnect hits it. And an Iggy view change raises `TransientNotAccepted` (58), whose doc string is "Request transiently not accepted; retry, on any replica".
Suggested: use the SDK's list rather than a hand-written subset. Keep `ClientShutdown` on `-1`, since that one really is terminal. `TransientNotCommitted` needs a deliberate choice rather than a fallthrough: it means the outcome is unknown, so retrying can produce a duplicate. `REQUEST_TIMED_OUT` (7) is Kafka's own answer to that, retriable without claiming the write failed.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,204 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::TopicMapping;
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches the Iggy server's own default root user - not a made-up example, the same default
+/// every fresh `iggy-server` and every CLI quick-start in this repo uses.
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+const DEFAULT_IGGY_PASSWORD: &str = "iggy";
Review Comment:
**CRITICAL.** The comment above these constants doesn't match what the server does.
`core/server/src/args.rs:109-120` shows `--with-default-root-credentials` is `default_value_t = false` and labelled "Use default root credentials (INSECURE - FOR DEVELOPMENT ONLY!)". Without it, `core/server/src/boot/credentials.rs:112-118` generates a random password and logs it once. So `iggy`/`iggy` is not "the same default every fresh `iggy-server` uses"; it is what you get only under an explicitly-insecure, default-off dev flag.
The effect once #3535 calls `from_env()`: a gateway with no `IGGY_KAFKA_IGGY_*` set holds full root on that Iggy, and the credential appears in no config file and no startup log, so nothing records that a choice was made.
For comparison, the connectors runtime and MCP also ship `iggy`/`iggy`, but as visible TOML an operator edits (`core/connectors/runtime/config.toml:48-52`), and the CLI has no password default at all (`core/cli/src/credentials.rs:148-152`). This is the only component combining an env-var default with no config file.
Suggested: drop `DEFAULT_IGGY_PASSWORD`, make `IGGY_KAFKA_IGGY_PASSWORD` required, and correct the comment either way. `helm/charts/iggy/templates/deployment.yaml:120-143` already has the `existingSecret` -> `secretKeyRef` pattern for `IGGY_ROOT_PASSWORD` to reuse. Quick-starts then need two env vars, which costs once now and permanently later.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
Review Comment:
**CRITICAL.** `close()` doesn't close.
`IggyClient::disconnect` (`core/sdk/src/clients/client.rs:993-995`) forwards to the transport and never touches `heartbeat_handle`. Only `Drop for IggyClient` (`:933-943`) aborts it. So five seconds later the heartbeat pings, `send_raw` returns `NotConnected`, that variant is in the transport's retriable set, and `sign_in_credentials()` still returns the configured `AutoLogin` even after the session was forgotten. The client redials and re-authenticates, leaving a live authenticated session on a bridge the caller believes is closed.
Dropping the bridge is currently safer than calling `close()` on it, which is the tell.
Suggested: `self.client.shutdown()` instead, which sets `ClientState::Shutdown` so the heartbeat loop's own `if error == IggyError::ClientShutdown { return; }` terminates it. Worth taking `self` by value at the same time, since `close(&self)` can be called twice and has no closed state. Two costs: `shutdown()` is terminal, and it can `Err` on a live socket where `disconnect()` effectively could not.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
+const PORT_LOCK_BAND_SLOTS: u16 = 200;
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, nothing ever binds the port on this side, so there is no TOCTOU window between
+/// picking it and `iggy-server` binding it: the lock, not a socket, is the allocator.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..PORT_LOCK_BAND_SLOTS {
+ let port = PORT_LOCK_BAND_START + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{PORT_LOCK_BAND_START}, {}]",
+ PORT_LOCK_BAND_START + PORT_LOCK_BAND_SLOTS - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_SYSTEM_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ async fn wait_ready(&self) {
Review Comment:
**CRITICAL.** Three problems in this harness, all of which `core/integration/src/harness/handle/server.rs` already solves.
**`#[serial]` does nothing here.** `.config/nextest.toml:24-26` states it in-repo: "nextest does not support #[serial] macro which shall enforce sequential execution". The workaround the repo uses is `threads-required = "num-cpus"`, which wasn't added for these tests. So up to num-cpus of them run concurrently.
**Shard pinning then oversubscribes the runner.** The spawn at `:145-159` doesn't set the sharding vars, so each server inherits `cpu_allocation = "numa:auto"` and `pin_cores = true` (`core/server/config.toml:873,883`). `handle/server.rs:311-319` overrides both, with the reason stated: "On a 4-core CI runner every server computes the same 0..4 range, so pinned shards of concurrently running tests pile onto the same cores and starve each other."
**No crash detection.** `wait_ready` polls a bare TCP connect and never calls `self.child.try_wait()`, so a server that exits at boot produces a 30s spin and then asserts "did not become ready within the startup budget", which names the wrong cause and prints no exit code or stderr. `Drop` at `:209-214` uses `Child::kill()` (SIGKILL) where `common.rs:138-159` has `graceful_kill` (SIGTERM, 5s, then SIGKILL). With `[profile.ci] retries = 3` that repeats four times.
Suggested minimum, keeping the no-dependency-edge property the comment at `:86-90` argues for: set `IGGY_SYSTEM_SHARDING_CPU_ALLOCATION=1` and `IGGY_SYSTEM_SHARDING_PIN_CORES=false`, add `try_wait()` to the poll loop, and redirect child stdio to files under the tempdir. Note a 1-shard server stops covering the multi-shard dispatch path this file covers by accident today.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
Review Comment:
**CRITICAL.** This hands `ensure_topic` a slab key that the server recycles.
The doc comment at `:125-130` argues carefully for `Identifier::named` over `try_from`, then converts to numeric for the handoff at `:118`, while `high_watermark:275` resolves the same stream by name. Two identities for one resource on adjacent methods.
Stream ids are `slab::Slab` keys. `core/metadata/src/stm/stream.rs:1595-1599` says so directly: "Takes `vacant_key()` rather than `len()` because the KEY is what gets packed and keys are recycled on delete."
So: `ensure_stream("kafka")` returns `numeric(3)`; a concurrent delete frees slot 3; a create assigns 3 to `billing`; `ensure_topic(numeric(3), "orders", ...)` creates `orders` inside `billing` and returns `Ok(())`. A silent wrong-target write, and under #3535 the Produce data follows it. Resolving by name in the same window yields `StreamNameNotFound` instead, which is the correct, loud answer.
Suggested: pass the `Identifier::named(stream_name)` already built at `:132` and drop the numeric conversion. Nothing breaks, and it also removes three dead `.map_err` calls (`Identifier::numeric` is infallible, `core/common/src/types/identifier/mod.rs:159-165`) plus the `:226` error that renders a slab key where `TopicNameNotFound`'s second field expects a stream name.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,204 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::TopicMapping;
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches the Iggy server's own default root user - not a made-up example, the same default
+/// every fresh `iggy-server` and every CLI quick-start in this repo uses.
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+const DEFAULT_IGGY_PASSWORD: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
+ /// surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in `core/configs`, so the
+ /// central provider's own typo-detection doesn't cover this namespace either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root credentials.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_TOPIC_MAP_PATH` is set but the file
+ /// is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD")
+ .unwrap_or_else(|_| DEFAULT_IGGY_PASSWORD.to_string());
+ let stream_env = std::env::var("IGGY_KAFKA_IGGY_STREAM").ok();
+ // Caught here, not left to TopicMapping::from_toml_str's own empty check: that
+ // validation only runs when IGGY_KAFKA_TOPIC_MAP_PATH is set, since the no-file branch
+ // below builds a TopicMapping directly rather than through the validating constructor.
+ // An explicitly-empty (not merely absent) IGGY_KAFKA_IGGY_STREAM would otherwise pass
+ // from_env cleanly and only fail much later, deep in the first ensure_stream_and_topic
+ // call, as an opaque Identifier::named("") error.
+ if let Some(ref stream) = stream_env
+ && stream.trim().is_empty()
+ {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_STREAM must not be empty".to_string(),
+ ));
+ }
+ let topic_map_path = std::env::var("IGGY_KAFKA_TOPIC_MAP_PATH").ok();
+
+ let topic_mapping = match topic_map_path {
+ Some(path) => {
+ if stream_env.is_some() {
+ warn!(
+ "IGGY_KAFKA_IGGY_STREAM is set but ignored: IGGY_KAFKA_TOPIC_MAP_PATH's \
+ own default_stream takes precedence"
+ );
+ }
+ TopicMapping::from_file(Path::new(&path))?
+ }
+ None => TopicMapping {
+ default_stream: stream_env.unwrap_or_else(|| "kafka".to_string()),
+ topics: std::collections::HashMap::new(),
+ },
+ };
+
+ Ok(Self {
+ address,
+ username,
+ password: SecretString::from(password),
+ topic_mapping,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serial_test::serial;
+
+ use super::*;
+
+ fn test_config() -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: "127.0.0.1:8090".to_string(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: std::collections::HashMap::new(),
+ },
+ }
+ }
+
+ #[test]
+ fn debug_output_does_not_expose_password() {
+ // A distinctive value, not the shared fixture's "iggy" - that string also appears as the
+ // username and inside the struct's own name, which would make a substring check here
+ // pass trivially regardless of whether the password field itself is actually redacted.
+ let mut config = test_config();
+ config.password = SecretString::from("correct-horse-battery-staple");
+ let debug_output = format!("{config:?}");
+ assert!(
+ !debug_output.contains("correct-horse-battery-staple"),
+ "Debug output must not expose the plaintext password: {debug_output}"
+ );
+ }
+
+ #[test]
+ #[serial]
+ fn from_env_rejects_missing_topic_map_file() {
+ // Safety: single-threaded within this function; no other test in this crate touches
+ // IGGY_KAFKA_TOPIC_MAP_PATH.
+ unsafe {
Review Comment:
These `unsafe` blocks race a concurrent `getenv` in the same test binary, and the `# Safety` comment states the wrong condition.
Edition 2024's rule is process-wide: no thread may read *or* write the environment concurrently. "Single-threaded within this function" isn't the requirement, and "no other test touches `IGGY_KAFKA_*`" doesn't matter because the race is against any env access.
The concurrent reader is `src/server.rs:891` `init_tracing_is_idempotent`, which calls `init_tracing()` and thus `EnvFilter::try_from_default_env()` (`server.rs:557`), a `getenv("RUST_LOG")`. It carries no `#[serial]`, and both files compile into the lib test target, so it's one binary. On glibc, `setenv` can `realloc` and free the old `environ` array under a walking `getenv`.
Reachable under `cargo test -p iggy-gateway-kafka`, which `docs/TEST_SUITE.md` tells developers to run. Not reachable under nextest, which is process-per-test, so CI won't show it.
Suggested: the fix that removes the `unsafe` entirely is injecting the lookup, e.g. `from_vars(impl Fn(&str) -> Option<String>)` with `from_env` as a thin wrapper. Adding `#[serial]` to `init_tracing_is_idempotent` only patches the `cargo test` path, since `.config/nextest.toml:24-26` notes `#[serial]` is inert under nextest. Either way the three `# Safety` comments should be reworded, since they'll be copied.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape, if
+ /// `default_stream` is empty, or if any `[topics.*]` override has an empty `stream`/`topic` -
+ /// in every case, an empty Iggy stream/topic name would otherwise pass config loading
+ /// cleanly and only fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, as
+ /// an opaque `Identifier::named("")` error with no link back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ if mapping.default_stream.trim().is_empty() {
Review Comment:
Two gaps in validation that the rustdoc's own rationale covers.
**Trims to check, stores untrimmed.** `default_stream = " kafka "` (a copy-paste artifact) passes here, and the untrimmed value is what reaches `Identifier::named`. Iggy applies no normalization: `core/metadata/src/stm/stream.rs:612` keys streams on a byte-exact `AHashMap<Arc<str>, usize>`. So the gateway creates and uses a stream literally named `" kafka "`, `iggy stream get kafka` finds nothing, and the operator concludes nothing was provisioned.
This one is worth doing before merge rather than after: adding `.trim()` later would silently repoint an existing deployment from `" kafka "` to `"kafka"` and strand its data. Rejecting a name that differs from its trimmed form avoids that.
**Length isn't bounded.** `Identifier::named` rejects on two conditions (`core/common/src/types/identifier/mod.rs:169-171`): `length == 0 || length > 255`. Only the first is checked here and in `config.rs:85-91`. A 256-byte name loads cleanly and then fails at the first `ensure_stream_and_topic` as the opaque `InvalidIdentifier` this validation exists to prevent, mapped to `-1`. Note the bound is bytes, not chars, so a 200-character UTF-8 name can exceed it.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
Review Comment:
The create path discards `TopicDetails` and skips the partition-count check the other two branches make.
`:188-196` and `:228-234` both verify `existing.partitions_count != partition_count`, with a comment explaining that the postcondition is "the topic has `partition_count` partitions afterward". Here the response is dropped with `Ok(_)` and the `info!` below asserts a count nothing verified.
Concretely: `ensure_stream_and_topic("orders", 0)`. `core/common/src/traits/binary_impls/topics.rs:97` substitutes `DEFAULT_PARTITIONS_COUNT` only for `None`, so `Some(0)` goes to the wire verbatim, and `core/server/src/rewrite.rs:218` bounds only the upper end. The result is a zero-partition topic that `ensure_topic` reports as provisioned and `high_watermark` then rejects with `PartitionOutOfRange`. A naive #3535 wiring that forwards Kafka's `num_partitions` without normalizing the `-1`/`0` sentinel gets exactly this.
Suggested: reject `partition_count == 0` at the top of `ensure_stream_and_topic`. Verifying on this branch too is tempting, but it should compare against the count the server actually resolved, not the requested one, or a server-side normalization would turn a working call into a permanent `PartitionCountMismatch` no retry can clear.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
Review Comment:
`#[from]` plus `{0}` forwards the SDK's `Display` verbatim, and for server-originated errors the payloads are always blank.
Only the `u32` code crosses the wire (`core/metadata/src/stm/result.rs:59-65`). `core/sdk/src/vsr.rs:310` reconstructs with `IggyError::from_code`, which is `from_repr(code).unwrap_or(Error)` (`core/common/src/error/iggy_error.rs:582-584`), and strum's `FromRepr` fills fieldful variants with `Default::default()`. `Identifier::default()` is numeric 0 (`identifier/mod.rs:59-67`).
So a `create_topic` that fails because the stream was deleted concurrently logs:
> `Iggy client error: Stream with ID: 0 was not found.`
There is no stream 0 in play, and 0 is a real id in the system, so it reads as a fact rather than a placeholder. The error *code* survives intact, so `to_kafka_error_code` is unaffected; it's the human-readable half that misleads. The bridge's self-constructed errors at `:156`, `:226` and `:283` carry real values and are fine.
Suggested: build the message in the bridge from the names it already holds, scoped to the arms it already matches on. A blanket override would lose the SDK's wording for every other variant.
##########
gateways/kafka/Cargo.toml:
##########
@@ -34,11 +34,14 @@ path = "src/main.rs"
[dependencies]
bytes = { workspace = true }
+iggy = { workspace = true }
Review Comment:
Worth knowing about this edge: it makes `iggy-gateway-kafka` a reverse-dependency of the SDK in cargo-rail's DAG, so from now on every PR touching `core/sdk/**` puts `package(iggy-gateway-kafka)` in `NEXTEST_FILTER` and runs the six server-spawning tests in `tests/bridge_iggy_integration_tests.rs`. Given the timeout and pinning issues in that file, that's a recurring tax on SDK work.
(Not this PR, incidentally: `Cargo.lock` is listed under `infrastructure` in `.config/rail.toml`, which forces full-workspace mode here anyway.)
Separately, `core/sdk` has no `[features]` section and depends unconditionally on `quinn`, `reqwest` and `rustls`, while the bridge only ever uses `.with_tcp()`. The Cargo.toml comment just above already makes this argument for `kafka-protocol`'s unused compression codecs; it applies here too. Gating those in the SDK is out of scope for this PR, but the cost is real for every test binary in this crate.
##########
gateways/kafka/src/main.rs:
##########
@@ -71,13 +76,20 @@ const KNOWN_KAFKA_ENV_VARS: &[&str] = &[
"IGGY_KAFKA_SHUTDOWN_DRAIN_TIMEOUT_SECS",
];
-/// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] - a typo (e.g.
-/// `IGGY_KAFKA_BIN_ADDR`) would otherwise be silently ignored: `core/configs`' central provider
-/// skips the whole `IGGY_KAFKA_` prefix, and this crate's own `env_var()` only ever looks up
-/// exact known names, so nothing reads the misspelled var and nothing warns either.
+/// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] or
+/// [`IggyBridgeConfig::KNOWN_ENV_VARS`] - a typo (e.g. `IGGY_KAFKA_BIN_ADDR`) would otherwise be
+/// silently ignored: `core/configs`' central provider skips the whole `IGGY_KAFKA_` prefix, and
+/// this crate's own `env_var()` only ever looks up exact known names, so nothing reads the
+/// misspelled var and nothing warns either. Checking both lists (not `IggyBridgeConfig`'s
+/// wiring into `main`) is deliberate: a user who exports a bridge var ahead of
+/// `#3535`/`#3536` landing must not see a spurious "unknown env var" rejection for a name this
+/// crate already recognizes.
fn reject_unknown_kafka_env_vars() -> Result<(), String> {
for (key, _) in std::env::vars() {
- if key.starts_with("IGGY_KAFKA_") && !KNOWN_KAFKA_ENV_VARS.contains(&key.as_str()) {
+ if key.starts_with("IGGY_KAFKA_")
+ && !KNOWN_KAFKA_ENV_VARS.contains(&key.as_str())
+ && !IggyBridgeConfig::KNOWN_ENV_VARS.contains(&key.as_str())
Review Comment:
This accepts five env var names that nothing reads, which is the failure mode the function exists to prevent.
`IggyBridgeConfig::from_env` has no caller: `load_config()` builds only `GatewayConfig`, and this line is the sole bridge reference in `main.rs`. So an operator following `README.md:72-78` and setting `IGGY_KAFKA_TOPIC_MAP_PATH` gets a clean startup, no log line, and no effect. The rejection message a few lines down says an unknown var "would otherwise be silently ignored", which is now what the accepted ones do.
There's also a deferred break: when #3535 starts calling `from_env()` at startup, that same deployment stops booting on a bad path or a malformed map file, and the change that caused it landed here.
Suggested: keep the names allowlisted and add one `warn!` in `load_config` when any `KNOWN_ENV_VARS` entry is set, saying the bridge isn't wired into the request path yet. Optionally call `from_env()` and discard the result so a bad topic-map path fails at startup today.
Minor, on the doc comment at `:64-66`: the anti-desync rationale doesn't hold, since `A.contains(k) || B.contains(k)` is the same as checking their union. What actually prevents desync is referencing `IggyBridgeConfig::KNOWN_ENV_VARS` instead of copying it, which `.iter().chain(...)` would do equally well.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
Review Comment:
**CRITICAL.** This isn't true for a single-address client, and `README.md:79-82` repeats the claim.
`max_retries` bounds passes, not wall time, and the per-dial timeout doesn't apply here. `core/sdk/src/tcp/tcp_client.rs:1144`:
```rust
if candidates.len() < 2 { return self.establish(server_address).await; }
```
`FAILOVER_DIAL_TIMEOUT` is skipped entirely for one endpoint, and `establish` (`:1034`) is a bare `TcpStream::connect` with no timeout. A bridge config carries exactly one address, so `candidates.len() == 1` always.
Against a firewall or security group that DROPs rather than refuses, each dial blocks for the kernel SYN timeout (~127s at Linux's default `tcp_syn_retries=6`). Four passes is roughly 8.5 minutes with nothing bounding it. `connect_to_unreachable_iggy_returns_err_not_panic` dials an unbound loopback port, which RSTs instantly, so it only exercises connection-refused.
Suggested: wrap `client.connect()` in `tokio::time::timeout` and state the real bound here. Set it above p99 handshake rather than at 2s, or slow-but-alive servers on a congested link start failing.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count` as segments are dropped
+ /// (`core/partitions/src/iggy_partition.rs::decrement_messages_count`) but never rewinds
+ /// `current_offset` - a fully-retention-purged partition that has produced messages reports
+ /// `messages_count == 0` with `current_offset` still at its high value. Treating that as
+ /// "empty" would report high watermark `0` for a partition that has, in fact, produced past
+ /// offset `0`; a future `ListOffsets` (`#3537`) LATEST built on this would rewind instead of
+ /// pointing at the true next-write position.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ let partition_details = details
+ .partitions
+ .iter()
+ .find(|p| p.id == partition)
+ .ok_or_else(|| BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the wrong
+ // (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ })?;
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
Review Comment:
This test conflates five states, not two.
The doc above argues correctly that `messages_count == 0` alone is insufficient, and the retention mechanism it cites is real (`core/common/src/types/streaming_stats.rs:290`, called only from `iggy_partition.rs:5991`, which doesn't touch `current_offset`). Two gaps:
**A registry miss also produces `(0, 0)`.** `core/server/src/responses.rs:1436` is `stats.map_or((0, 0, 0), |stats| ...)`, and `core/metadata/src/stm/stream.rs:463-464` documents the lookup as `None` "until the owning shard materializes the partition". So a partition holding real data reports a high watermark of 0 during that window. The server refuses to make the same mistake next door: `responses.rs:1387` clamps `segments_count` to a floor of 1 for exactly this reason, and `:1430-1432` carries a standing TODO for a materialization signal.
**One message at offset 0, then aged out by retention, also lands here** and returns 0 where the true next offset is 1.
To be fair, this is not novel: `core/partitions/src/iggy_partition.rs:2681-2683` uses the identical `current == 0 && messages_count == 0` idiom. The code is defensible; the doc comment claiming the pair is sufficient is not. The real answer already exists server-side as `offset_frontier()` (`iggy_partition.rs:1274-1280`), gated on `committed_seeded` rather than inferred, but it isn't on the wire.
Suggested: replace the "that empty case is" paragraph with the enumerated ambiguity, so #3537 doesn't build LATEST on this as-is. Carrying `committed_seeded` on `PartitionResponse` is the real fix and is a `binary_protocol` change, so out of scope here.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
Review Comment:
`resolve` isn't injective, and nothing checks for collisions.
A mid-migration config like:
```toml
default_stream = "kafka"
[topics.orders]
stream = "kafka"
topic = "orders_v2"
```
maps Kafka topic `orders` to `(kafka, orders_v2)` via the override, and Kafka topic `orders_v2` to `(kafka, orders_v2)` via the default rule. Two Kafka topics, one Iggy topic. Under #3535/#3536 the records interleave and per-topic ordering is gone for both, with no error and no way for a client to notice.
A rename or alias while both names still have clients is the most likely reason to write an override file at all, so this is the common case rather than an exotic one.
Suggested: in `from_toml_str`, build the resolved set (every `[topics.*]` target plus the identity mapping of every key) and reject duplicates, naming both colliding Kafka topics. It can't catch a collision against a topic not listed in the file, so it's a partial guard, but it covers the shape above.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
Review Comment:
`..TopicCreateOptions::default()` leaves `message_expiry: None`, which `core/metadata/src/stm/stream.rs:1872` stores as `IggyExpiry::ServerDefault`, and `core/server/src/segment_cleaner.rs:93,98` treats that as never expire. Kafka brokers default to `retention.ms = 604800000` (7 days).
Not a format freeze, to be clear: `max_topic_size: ServerDefault` is re-resolved against node config at enforcement time (`segment_cleaner.rs:181,197`), so changing the server default later does affect existing topics. But a team repointing a Kafka producer at this gateway will assume 7-day retention and bounded disk, and get neither.
Suggested: either set an explicit `message_expiry`, or document in the README that auto-provisioned topics inherit Iggy's retention (none by default), not Kafka's.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
Review Comment:
The band is hardcoded, and the doc comment's TOCTOU claim is stronger than what the lock provides.
`flock` is advisory and honored only by processes that open this same lock directory. It removes the window against other tests in this file, not against the machine. Two non-participants can still take 15000-15199: the kernel's ephemeral allocator, and this crate's own other test binaries, which all use `bind("127.0.0.1:0")` (`tests/common/server.rs:57`, `tests/server_integration_tests.rs:31`).
The comment's reasoning about staying clear of ephemeral is right about the Linux default but assumes it. `core/integration/src/harness/port_reserver.rs` reads the real value from `/proc/sys/net/ipv4/ip_local_port_range` (`:79`) and `band_for` (`:115-130`) falls back *above* the ceiling when the floor is too low, with the reason stated at `:112-114`: "the only thing that lets a box tuned for high connection counts (`1024 65535` and the like) run the suite at all." On such a host this band sits inside the ephemeral range. (The comment's other claim checks out, incidentally: `BAND_START` really is 20000.)
The failure is quiet: a lost port means `iggy-server` can't bind and exits, then `wait_ready` spins its full 30s and blames startup time.
Suggested: reuse `SinglePortReserver`, or at minimum read the sysctl and refuse to hand out a port inside the ephemeral range, and soften the comment to "advisory within this suite".
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
Review Comment:
`INVALID_PARTITIONS` (37) is Kafka's code for "Number of partitions is below 1" (`kafka-protocol-0.18.0/src/error.rs:221`), not for "exists with a different count".
A client that asked for 6 partitions against a topic already created with 3 gets told its request had fewer than 1, and goes off debugging its own arguments. Kafka's own code for CreateTopics against an existing topic is `TOPIC_ALREADY_EXISTS` (36).
Worth also noting the operational shape once #3535 lands: anyone calling Iggy's `CreatePartitions` on a bridged topic makes every later `ensure_stream_and_topic` for that Kafka topic fail permanently, since 37 is `retriable=false` and nothing in the bridge heals it. And a Kafka Produce request carries partition indices, not a count, so a Produce handler has no count of its own to pass here. `Option<u32>` meaning "whatever it already has" may fit that caller better than the current signature.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
Review Comment:
Three things about this struct that get harder to change after merge.
**No `deny_unknown_fields`.** A singular `[topic.orders]` typo (the README shows the plural at `:91-104`) parses cleanly as an unknown top-level key, leaves `topics` empty, and silently routes every Kafka topic to the default stream. Same for an extra key on an override.
**No `version` key.** Added later it can only ever be `#[serde(default)]`, so the schema can never be asserted, only inferred. If #3535 wants per-topic `partitions` or a retention override, there's no way to tell a v1 file from a v2 one except probing for the field.
**`Default` yields `default_stream: ""`**, which is exactly what `from_toml_str:68-72` rejects. With public fields the invariant isn't enforceable, and the tests already construct literals that bypass it (`tests/bridge_iggy_integration_tests.rs:201-204`, `config.rs:130-133`), which is why `config.rs:85-91` needs its own separate empty check. Two validation sites for one invariant.
Suggested: `#[serde(deny_unknown_fields)]` on both structs and a `version: u32` now. The cost today is one line in the README examples and three unit tests. Later it's a breaking config change.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
+const PORT_LOCK_BAND_SLOTS: u16 = 200;
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, nothing ever binds the port on this side, so there is no TOCTOU window between
+/// picking it and `iggy-server` binding it: the lock, not a socket, is the allocator.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..PORT_LOCK_BAND_SLOTS {
+ let port = PORT_LOCK_BAND_START + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{PORT_LOCK_BAND_START}, {}]",
+ PORT_LOCK_BAND_START + PORT_LOCK_BAND_SLOTS - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_SYSTEM_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ async fn wait_ready(&self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
Review Comment:
This asserts three `Ok`s and never reads back the end state.
An implementation that created a second stream on every call and returned `Ok(())` would pass. It currently catches a wrong partition count only indirectly, because call 2 trips the mismatch check in `ensure_topic`, so if that branch were ever softened to `Ok(())` plus a `warn!` this test would quietly stop verifying anything beyond "no error".
Suggested: assert through `raw_client` that exactly one stream and one topic exist afterward with 3 partitions.
Branches with no test at all, while I'm here:
- `BridgeError::PartitionCountMismatch`, both the existing-topic and lost-race branches. Two lines after the existing test would cover it: `ensure_stream_and_topic("orders", 3)`, then expect `ensure_stream_and_topic("orders", 5)` to fail with `PartitionCountMismatch { existing: 3, requested: 5, .. }`.
- Any `TopicMapping` override through `IggyBridge`. Every config here uses `topics: HashMap::new()`, so `kafka_topic == topic_name` throughout, and the deliberate choice to report the Kafka-side name at `:190-192` and `:294-297` can't fail. `high_watermark`'s doc makes a specific claim about overrides that nothing exercises.
- `from_env`'s no-file branch and all four defaults at `config.rs:26-30`. All three existing tests take the `Some(path)` arm or return early.
- `connect`'s empty-address guard, `high_watermark`'s topic-not-found path, and the dotted-key TOML form the README documents.
The two `NameAlreadyExists` race arms are genuinely hard to test without concurrency and I wouldn't block on them, though it's worth knowing they ship unexecuted.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
No caching, on the method #3535 is meant to call per Produce request.
Round trips: 2 when both already exist (`get_stream` at `:133`, `get_topic` at `:175`), 4 cold, 6 if both create races are lost. `high_watermark` adds a third independent `get_topic`. So a steady-state Produce becomes `get_stream` + `get_topic` + `send_messages`, three round trips where the Kafka contract needs one, and a Fetch that needs the high watermark costs four.
Worth flagging alongside it: the bridge holds one `IggyClient`, and the SDK's TCP transport is lockstep, one request in flight per client, with the stream mutex held across write, flush and both reads (`core/sdk/src/tcp/tcp_client.rs:1417-1430`). Every Kafka connection the gateway serves funnels through that. The ceiling is 1/RTT for the whole process, and adding cores or connections doesn't move it.
Not a merge blocker, since nothing calls this yet. But it's the shape #3535 inherits, and a cache added later needs an invalidation path in the error handler that doesn't exist yet: a stale `Identifier` currently surfaces as `StreamIdNotFound`, mapped to error 3, with nothing to evict on.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count` as segments are dropped
+ /// (`core/partitions/src/iggy_partition.rs::decrement_messages_count`) but never rewinds
+ /// `current_offset` - a fully-retention-purged partition that has produced messages reports
+ /// `messages_count == 0` with `current_offset` still at its high value. Treating that as
+ /// "empty" would report high watermark `0` for a partition that has, in fact, produced past
+ /// offset `0`; a future `ListOffsets` (`#3537`) LATEST built on this would rewind instead of
+ /// pointing at the true next-write position.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ let partition_details = details
Review Comment:
`.find()` on a vector the SDK already sorted, after decoding all of it for 16 bytes.
`core/common/src/wire_conversions.rs:172-174` collects into a second `Vec` and calls `sort_by_key(|p| p.id)`, so the result is ordered. Per-partition wire size is fixed at 40 bytes (`core/binary_protocol/src/responses/topics/get_topic.rs:40`).
At 1000 partitions that's ~40 KB off the wire and ~120 KB across three buffers per call, plus an O(N log N) sort and this O(N) scan, to read one `current_offset` and one `messages_count`. At 32 partitions it's unremarkable, so the cost scales entirely with partition count.
`binary_search_by_key(&partition, |p| p.id)` is free today and correct given the sort. Ids happen to be dense and 0-based (`core/metadata/src/impls/metadata.rs:3515-3527`), so indexing plus an id check would also work, but `DELETE_PARTITIONS` could break that assumption later; the binary search is the safer form.
The larger version of this (a narrow per-partition request instead of full `TopicDetails`) needs a new wire code and belongs with #3537, not here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3954378584
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape, if
+ /// `default_stream` is empty, or if any `[topics.*]` override has an empty `stream`/`topic` -
+ /// in every case, an empty Iggy stream/topic name would otherwise pass config loading
+ /// cleanly and only fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, as
+ /// an opaque `Identifier::named("")` error with no link back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ if mapping.default_stream.trim().is_empty() {
Review Comment:
Validation trims but stores untrimmed (also `config.rs:86`). `default_stream = " kafka "` creates a stream named `" kafka "`. Adding `.trim()` later would silently repoint a live deployment, so reject instead, before this ships.
Same code checks `Identifier::named`'s empty case but not its 255-byte case (`identifier/mod.rs:169-171`) - the other half of one condition.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
Review Comment:
The create path throws away `TopicDetails` and skips the partition-count check done on the other two branches. `topics.rs:97` passes `Some(0)` straight through; `rewrite.rs:218` only bounds the top end.
##########
gateways/kafka/src/main.rs:
##########
@@ -71,13 +76,20 @@ const KNOWN_KAFKA_ENV_VARS: &[&str] = &[
"IGGY_KAFKA_SHUTDOWN_DRAIN_TIMEOUT_SECS",
];
-/// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] - a typo (e.g.
-/// `IGGY_KAFKA_BIN_ADDR`) would otherwise be silently ignored: `core/configs`' central provider
-/// skips the whole `IGGY_KAFKA_` prefix, and this crate's own `env_var()` only ever looks up
-/// exact known names, so nothing reads the misspelled var and nothing warns either.
+/// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] or
+/// [`IggyBridgeConfig::KNOWN_ENV_VARS`] - a typo (e.g. `IGGY_KAFKA_BIN_ADDR`) would otherwise be
+/// silently ignored: `core/configs`' central provider skips the whole `IGGY_KAFKA_` prefix, and
+/// this crate's own `env_var()` only ever looks up exact known names, so nothing reads the
+/// misspelled var and nothing warns either. Checking both lists (not `IggyBridgeConfig`'s
+/// wiring into `main`) is deliberate: a user who exports a bridge var ahead of
+/// `#3535`/`#3536` landing must not see a spurious "unknown env var" rejection for a name this
+/// crate already recognizes.
fn reject_unknown_kafka_env_vars() -> Result<(), String> {
for (key, _) in std::env::vars() {
- if key.starts_with("IGGY_KAFKA_") && !KNOWN_KAFKA_ENV_VARS.contains(&key.as_str()) {
+ if key.starts_with("IGGY_KAFKA_")
+ && !KNOWN_KAFKA_ENV_VARS.contains(&key.as_str())
+ && !IggyBridgeConfig::KNOWN_ENV_VARS.contains(&key.as_str())
Review Comment:
Five bridge env vars are allowlisted at startup and read by nothing. The guard's own message says they'd "otherwise be silently ignored", which is what it now permits. One `warn!` fixes it. The anti-desync note at `:64-66` is also meaningless, since checking two lists separately is the same as checking their union.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count` as segments are dropped
+ /// (`core/partitions/src/iggy_partition.rs::decrement_messages_count`) but never rewinds
+ /// `current_offset` - a fully-retention-purged partition that has produced messages reports
+ /// `messages_count == 0` with `current_offset` still at its high value. Treating that as
+ /// "empty" would report high watermark `0` for a partition that has, in fact, produced past
+ /// offset `0`; a future `ListOffsets` (`#3537`) LATEST built on this would rewind instead of
+ /// pointing at the true next-write position.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ let partition_details = details
Review Comment:
`high_watermark` decodes and sorts the whole partition vector for 16 bytes: at N=1000 that's about 40 KB on the wire and 120 KB allocated per call, plus an O(N) scan of a vector `wire_conversions.rs:174` already sorted. `binary_search_by_key` is free.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
No caching: 2 round trips steady-state, 4 cold, plus 1 for `high_watermark`, on a path #3535 wants to call per Produce, through one lockstep TCP connection (`tcp_client.rs:1428-1430`).
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
Review Comment:
`PortGuard`'s "no TOCTOU window" claim is wrong. flock is advisory, and unlike `port_reserver.rs:115-130` it never reads `/proc/sys/net/ipv4/ip_local_port_range`, so `[15000,15199]` lands inside the ephemeral range on a box tuned `1024 65535`. Sibling test binaries all `bind("127.0.0.1:0")`.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
Review Comment:
`BridgeError::Iggy`'s Display prints empty payloads: `from_repr` fills variants with `Default::default()` and `Identifier::default()` is numeric 0, so you get "for stream with ID: 0" - a made-up id that's also a real one.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
+const PORT_LOCK_BAND_SLOTS: u16 = 200;
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, nothing ever binds the port on this side, so there is no TOCTOU window between
+/// picking it and `iggy-server` binding it: the lock, not a socket, is the allocator.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..PORT_LOCK_BAND_SLOTS {
+ let port = PORT_LOCK_BAND_START + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{PORT_LOCK_BAND_START}, {}]",
+ PORT_LOCK_BAND_START + PORT_LOCK_BAND_SLOTS - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_SYSTEM_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ async fn wait_ready(&self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
Review Comment:
Coverage gaps: nothing hits `PartitionCountMismatch` on either branch; no test uses a `TopicMapping` override through `IggyBridge` (all use `HashMap::new()`), so the deliberate `kafka_topic` vs `topic_name` choice at `:190,:294` can't fail; `from_env`'s no-file branch and all four defaults never run; and this test checks three `Ok`s while reading back nothing.
##########
gateways/kafka/Cargo.toml:
##########
@@ -34,11 +34,14 @@ path = "src/main.rs"
[dependencies]
bytes = { workspace = true }
+iggy = { workspace = true }
Review Comment:
Adding `iggy` makes this crate a reverse-dependency of the SDK, so every `core/sdk/**` PR will run these server-spawning tests from now on. Not this PR - `Cargo.lock` is `infrastructure` in `.config/rail.toml`, forcing full-workspace mode.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthenticated
+ | IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
Review Comment:
**CRITICAL** (same match as the `_` arm below, opposite direction).
`Unauthenticated` maps to 29, which is `retriable=false`. But `core/common/src/traits/binary_auth.rs:27` shows `ClientState::Connected => Err(IggyError::Unauthenticated)`, i.e. it is the window between the socket coming up and auto-sign-in finishing, not an authorization decision. The SDK itself lists it as retriable at `tcp_client.rs:219`.
So a brief reconnect kills a consumer thread with "Not authorized to access topics", sending whoever is on call to audit Kafka ACLs that don't exist in this gateway. The same code also fires for a wrong `IGGY_KAFKA_IGGY_PASSWORD`, which is the gateway's own config fault reported as the client's ACL problem.
Suggested: move `Unauthenticated` to `ERROR_NOT_LEADER_OR_FOLLOWER` (6) and keep 29 for `Unauthorized` only. `unauthenticated_maps_to_topic_authorization_failed` asserts the current mapping, so it needs updating alongside.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3965851129
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
Review Comment:
The named-vs-numeric doc is doing the right thing on lookup, then throwing it away. Recycled stream ids after delete+recreate would send `create_topic` at the wrong stream.
Will pass the `Identifier::named(stream_name)` already built at the start of `ensure_stream` into `ensure_topic`. That also drops the `Identifier::numeric` `map_err` calls (infallible for any `u32`) and stops printing a slab key in the `:226` not-found path.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3977799378
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
Review Comment:
The get and race-lost arms check `partitions_count`; the `Ok(created)` arm trusts the request. `Some(0)` is not rejected at the SDK boundary. Will use the returned `TopicDetails` and apply the same mismatch check (and reject 0 up front so we do not round-trip a request we already know is invalid).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5618301833
/ready
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001340419
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
**Fixed**. Added REQUEST_TIMEOUT (same 15s bound as CONNECT_TIMEOUT) and a with_request_timeout<T> helper wrapping every post-connect SDK call: connect, shutdown (in close), get_stream/create_stream (in ensure_stream), get_topic/create_topic including the race-recovery arm (in ensure_topic), and get_topic (in high_watermarks).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020483466
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Locates the already-built `iggy-server` binary. Does not build it - see this crate's
+/// `docs/TEST_SUITE.md` for the prerequisite, the same one `core/integration`'s own
+/// server-spawning tests already carry.
+///
+/// `assert_cmd::cargo::cargo_bin`, matching `core/integration`'s own
+/// `harness::handle::server::start` - not a from-scratch `cargo build` invocation. An earlier
+/// version of this function drove `cargo build --package server --bin iggy-server` directly,
+/// reasoning that `Command::cargo_bin` "only resolves `CARGO_BIN_EXE_*` for binaries owned by
+/// *this* package" - true of the `CARGO_BIN_EXE_*` env-var lookup alone, but `cargo_bin` falls
+/// back to `legacy_cargo_bin` when that's unset, which derives the target directory from
+/// `env::current_exe()` (this test binary's own path) and looks for a same-named file there -
+/// correct under `CARGO_TARGET_DIR`, `--release`, or a `--target` triple subdirectory precisely
+/// because it reads back from where cargo actually placed *this* binary, not a guessed path. That
+/// version also re-ran a `cargo build` from every one of this file's server-spawning tests
+/// (nextest runs each as its own process, so the `OnceLock` memoized nothing across them),
+/// serialized by `.config/nextest.toml`'s `kafka_bridge` test-group but still real, avoidable
+/// per-test overhead this version has none of.
+fn iggy_server_binary() -> PathBuf {
+ assert_cmd::cargo::cargo_bin("iggy-server")
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ password: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with the default `iggy`/`iggy` root credentials. See
+ /// [`Self::spawn_with_password`] for the general form.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ Self::spawn_with_password(data_dir, "iggy").await
+ }
+
+ /// Spawns `iggy-server` with an isolated temp data dir, a locked TCP port, and the given root
+ /// password, then blocks until its listener is ready or the startup budget is exhausted.
+ ///
+ /// A dedicated password parameter (not just the `spawn()` default everywhere) lets a
+ /// password-shaped regression test (special characters, say) reuse this harness's
+ /// `PortGuard`/graceful-`Drop`/`wait_ready` machinery instead of hand-rolling a second,
+ /// `Drop`-less spawn: a `Drop`-less copy has no guard to run `graceful_kill` on a panic before
+ /// its assertions, orphaning a process that still holds its `PortGuard` slot, which then
+ /// fails the next test that draws that slot to bind.
+ async fn spawn_with_password(data_dir: &std::path::Path, password: &str) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", password);
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ password: password.to_string(),
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from(self.password.clone()),
+ topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
+ .expect("valid mapping for this test's fixture data"),
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is heavyweight, and pulling it in for one function isn't worth it; this crate already
+/// depends directly on `iggy`/`core/sdk`, so `core/integration` wouldn't add a *new*
+/// core/sdk-change-reruns-these-tests edge, just an unrelated dependency). A bare SIGKILL skips
+/// `iggy-server`'s shutdown path entirely, which is a materially different exit than what the
+/// binary is actually built to do on `SIGTERM` - `.kill()` alone bypassed that in every test run
+/// before this fix.
+const SIGTERM_TIMEOUT: Duration = Duration::from_secs(5);
+const SIGKILL_POLL_INTERVAL: Duration = Duration::from_millis(50);
+
+fn graceful_kill(child: &mut Child) {
+ // `wait_ready` calls `try_wait()` too (and panics on an early exit, unwinding into this via
+ // `Drop`) - if it already reaped the child, `child.id()` is a PID the OS is free to hand to an
+ // unrelated process by the time we get here, and a raw `libc::kill` (unlike `std::Child::kill`,
+ // which checks its own cached exit status first and no-ops instead) has no such guard against
+ // signaling that PID anyway. Checking here first closes the same gap `std` already closes for
+ // its own `kill`.
+ if matches!(child.try_wait(), Ok(Some(_))) {
+ return;
+ }
+
+ let pid = child.id() as libc::pid_t;
+ // Safety: `pid` is this process's own live child, confirmed by the `try_wait` check above;
+ // sending it a signal is exactly what `Child::kill` itself does internally.
+ unsafe {
+ libc::kill(pid, libc::SIGTERM);
+ }
+
+ let deadline = std::time::Instant::now() + SIGTERM_TIMEOUT;
+ while std::time::Instant::now() < deadline {
+ match child.try_wait() {
+ Ok(None) => std::thread::sleep(SIGKILL_POLL_INTERVAL),
+ Ok(Some(_)) | Err(_) => return,
+ }
+ }
+
+ let _ = child.kill();
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ graceful_kill(&mut self.child);
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("second call is a no-op against the now-existing stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("third call is still a no-op");
+
+ // Read back real state, not just three Oks: proves the second and third calls were actually
+ // no-ops against the one topic the first call created, not e.g. three independent topics
+ // that all happen to satisfy Ok(()) individually.
+ let raw = raw_client(&server).await;
+ let topics = raw
+ .get_topics(&Identifier::named("kafka").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(topics.len(), 1, "must be exactly one topic, not three");
+ assert_eq!(topics[0].name, "orders");
+ assert_eq!(topics[0].partitions_count, 3);
+}
+
+/// Regression test for coverage: nothing previously exercised `PartitionCountMismatch` on a real
+/// server - only unit tests constructed the variant directly.
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_rejects_a_second_call_with_a_different_partition_count() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the topic with 3 partitions");
+
+ let err = bridge
+ .ensure_stream_and_topic("orders", 5)
+ .await
+ .expect_err(
+ "a different partition count against an existing topic must not silently succeed",
+ );
+ match err {
+ BridgeError::PartitionCountMismatch {
+ topic,
+ existing,
+ requested,
+ } => {
+ assert_eq!(topic, "orders", "must report the Kafka-side name");
+ assert_eq!(existing, 3);
+ assert_eq!(requested, 5);
+ }
+ other => panic!("expected PartitionCountMismatch, got {other:?}"),
+ }
+}
+
+/// Regression test for coverage: every other test uses an empty `TopicMapping` (`HashMap::new()`),
+/// so the Kafka-name-vs-Iggy-name distinction `ensure_topic`/`high_watermark` deliberately
+/// maintain in their error paths (`kafka_topic`, not the resolved `topic_name`) can never actually
+/// differ and so can never be caught wrong. This test maps a Kafka topic to a differently-named
+/// Iggy stream/topic and checks both the happy path and the error paths report the Kafka-side
+/// name a real caller (a future handler) would recognize.
+#[tokio::test]
+#[serial]
+async fn bridge_operations_report_the_kafka_side_name_through_a_real_topic_mapping_override() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let mut config = server.test_config();
+ let mut topics = HashMap::new();
+ topics.insert(
+ "orders".to_string(),
+ TopicOverride {
+ stream: "billing".to_string(),
+ topic: "orders_v2".to_string(),
+ },
+ );
+ config.topic_mapping = TopicMapping::new("kafka".to_string(), topics)
+ .expect("valid mapping for this test's fixture data");
+ let bridge = IggyBridge::connect(config)
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("must create the mapped Iggy stream/topic, not one named after the Kafka topic");
+
+ // The Iggy-side resources are named differently from the Kafka topic - confirms the mapping
+ // actually took effect, not that resolve() was a no-op that happened to pass either way.
+ let raw = raw_client(&server).await;
+ let billing_topics = raw
+ .get_topics(&Identifier::named("billing").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(billing_topics.len(), 1);
+ assert_eq!(billing_topics[0].name, "orders_v2");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("must resolve through the mapping, not fail looking for a stream named 'orders'");
+ assert_eq!(watermark, 0);
+
+ let out_of_range = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(
+ matches!(
+ &out_of_range,
+ BridgeError::PartitionOutOfRange { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {out_of_range:?}"
+ );
+
+ let mismatch = bridge
+ .ensure_stream_and_topic("orders", 2)
+ .await
+ .expect_err("different partition count against the mapped topic must not silently succeed");
+ assert!(
+ matches!(
+ &mismatch,
+ BridgeError::PartitionCountMismatch { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {mismatch:?}"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_is_zero_for_a_fresh_empty_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("fresh topic must report a watermark, not an error");
+ assert_eq!(
+ watermark, 0,
+ "a freshly created, empty partition's high watermark must be 0"
+ );
+}
+
+/// Pins the exact semantics of `Iggy::Partition::current_offset` (offset of the *last written*
+/// message, not Kafka's "next offset to produce") against a real server - a test that only
+/// checked the empty-topic case would pass under either interpretation and hide an off-by-one.
+#[tokio::test]
+#[serial]
+async fn high_watermark_reflects_produced_messages() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before producing");
+
+ let stream_id = Identifier::named("kafka").expect("valid stream name");
+ let topic_id = Identifier::named("orders").expect("valid topic name");
+ let mut messages: Vec<IggyMessage> = (0..3)
+ .map(|i| IggyMessage::from(format!("message-{i}")))
+ .collect();
+ let client = raw_client(&server).await;
+ client
+ .send_messages(
+ &stream_id,
+ &topic_id,
+ &Partitioning::partition_id(0),
+ &mut messages,
+ )
+ .await
+ .expect("send 3 messages");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("topic must report a watermark after producing");
+ assert_eq!(
+ watermark, 3,
+ "high watermark after 3 messages (offsets 0, 1, 2) must be 3, not the last offset (2)"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_rejects_out_of_range_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let err = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(matches!(err, BridgeError::PartitionOutOfRange { .. }));
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_for_a_numeric_topic_name() {
+ // Regression test: Identifier::try_from/FromStr parses an all-digit string as a numeric ID,
+ // not a name - a second call for the same numeric-named topic would look it up by the wrong
+ // resource kind and fail with StreamIdNotFound/TopicIdNotFound despite the topic existing.
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("first call creates the numeric-named stream and topic");
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("second call must still find the numeric-named topic by name, not by ID");
+}
+
+/// Regression test: `ensure_stream` used to hand `ensure_topic` the stream's *numeric* id
+/// (`Identifier::numeric`), and streams are backed by a recycled slab (freed keys are reused by
+/// the next created stream) - a stream deleted and recreated between the two calls would leave
+/// `ensure_topic` writing into whatever stream now holds that recycled numeric key, not the one
+/// `ensure_stream_and_topic`'s caller actually resolved. The fix threads the *named* `Identifier`
+/// through instead. This does not (cannot, from a black-box test) hit the exact `await` window the
+/// bug lived in, but it does prove the name, not a captured numeric id, is what actually governs:
+/// delete the stream, recreate it under the same name, and the very next call must still land the
+/// topic on the live incarnation.
+#[tokio::test]
+#[serial]
+async fn ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate() {
Review Comment:
fixed.this scenario is black-box untestable given private methods with no await seam; explains what the test actually proves.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020505187
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
Review Comment:
Documented the exact collision condition (floor ≤ 10000) precisely rather than a risky fix.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3965747370
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthenticated
+ | IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected | IggyError::CannotEstablishConnection => {
+ ERROR_NOT_LEADER_OR_FOLLOWER
+ }
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
Review Comment:
Good point. The map was written from Kafka-ish categories, not from `tcp_client.rs`'s retriable match.
changing `iggy_error_to_kafka_code` to:
- SDK retriable set (`Disconnected | EmptyResponse | Unauthenticated | StaleClient | NotConnected | CannotEstablishConnection | TcpError`) plus `TransientNotAccepted` → `NOT_LEADER_OR_FOLLOWER` (6)
- `Unauthenticated` moves from 29 to 6 (reconnect window, not ACLs)
- `InvalidCredentials | Unauthorized | InvalidUsername | InvalidPassword` stay at `TOPIC_AUTHORIZATION_FAILED` (29)
- `TransientNotCommitted` → `REQUEST_TIMED_OUT` (7) — unknown outcome; 6 would invite a duplicate produce
- `ClientShutdown` stays `-1`
Will add `ERROR_REQUEST_TIMED_OUT` next to the other `ERROR_*` consts in `protocol/api.rs` and rewrite `unauthenticated_maps_to_topic_authorization_failed`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3965841984
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
+const PORT_LOCK_BAND_SLOTS: u16 = 200;
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, nothing ever binds the port on this side, so there is no TOCTOU window between
+/// picking it and `iggy-server` binding it: the lock, not a socket, is the allocator.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..PORT_LOCK_BAND_SLOTS {
+ let port = PORT_LOCK_BAND_START + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{PORT_LOCK_BAND_START}, {}]",
+ PORT_LOCK_BAND_START + PORT_LOCK_BAND_SLOTS - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_SYSTEM_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ async fn wait_ready(&self) {
Review Comment:
Confirmed. `#[serial]` does not serialize across nextest processes, and the spawn was missing the overrides `harness/handle/server.rs` already uses.
Will set `IGGY_SYSTEM_CLUSTER_CPU_ALLOCATION` / pin-cores (same pair as the integration harness), call `try_wait()` inside `wait_ready` so a dead child fails with the real exit instead of a 30s timeout, and capture child stdio.
Not pulling in `ServerHandle` this PR — that is a larger test-infra change than this crate needs. Same env + wait/stdio behavior, local `TestServer`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core (#3533) [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5523463283
please dont include #PR_NUMBER in PR title because it'd look weird after merge, e.g.
`feat(gateways): Iggy Kafka bridge core (#3533) #4043`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967781481
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
Review Comment:
yes it is silent today. An override that renames `orders` → `orders_v2` collides with a Kafka topic that is actually named `orders_v2` and falls through to the default rule.
Will reject a mapping where two Kafka names resolve to the same `(stream, topic)` pair at `from_toml_str` time (and the same check on the env-built map if we ever add overrides there). That keeps overrides as renames without silent merge.Added new tests.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3997012188
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthorized
+ | IggyError::InvalidCredentials
Review Comment:
**warning**
This lumps `InvalidCredentials`, `InvalidUsername` and `InvalidPassword` in with `Unauthorized` and sends all four back as `TOPIC_AUTHORIZATION_FAILED` (29). Those three are *our* login to Iggy failing, not the Kafka client doing anything wrong.
Code 29 is fatal on the client side (`TopicAuthorizationException extends AuthorizationException`, never `RetriableException`), and the app owner sees "Not authorized to access topics". They cannot fix a wrong `IGGY_KAFKA_IGGY_PASSWORD`.
It is not startup-only either. `core/sdk/src/tcp/tcp_client.rs:281` re-runs `connect()` mid-request, so a rotated password surfaces this on a live request.
Send those three to `ERROR_UNKNOWN_SERVER_ERROR` and log the real cause. Keep `Unauthorized` on 29. The comment at `error.rs:88-90` already makes exactly this argument for a different case.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape (an
+ /// unrecognized field - e.g. a `[topic.x]` typo for `[topics.x]` - is rejected here rather
+ /// than silently parsing to an empty override map), if `default_stream` or any override's
+ /// `stream`/`topic` is empty, has leading/trailing whitespace, or exceeds
+ /// `MAX_IDENTIFIER_LEN`, or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)) - in every validation case, letting it through here would
+ /// otherwise fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, with no link
+ /// back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ validate_identifier_name("topic mapping's default_stream", &mapping.default_stream)?;
+
+ let mut targets = HashSet::with_capacity(mapping.topics.len());
+ for (kafka_topic, over) in &mapping.topics {
Review Comment:
**warning**
This loop checks `over.stream` and `over.topic` but never the Kafka topic key itself.
So `[topics." orders "]` loads clean, and then matches nothing, because `resolve` at `:99` does an exact `HashMap::get`. That topic quietly goes to the default stream and nobody gets an error. Kafka's own `LEGAL_CHARS` has no space in it, so the padded key is not just unlikely to match, it is impossible to match.
This is the one thing in the PR that fails silently. Everything else fails loudly.
Reject empty and whitespace-padded keys here. Do not reuse `validate_identifier_name` as-is though: it enforces 255 (the Iggy bound) and Kafka's own cap is 249, so label the error as a Kafka-side name.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
**warning**
`connect` is the only thing in this file with a deadline. Line 101 wraps it in `tokio::time::timeout(CONNECT_TIMEOUT, ...)`. `ensure_stream_and_topic`, `ensure_stream`, `ensure_topic`, `high_watermark` and `close` are all bare.
That matters because the SDK reconnects underneath you. On a transport error `send_raw_with_response` calls `self.connect()` (`tcp_client.rs:296`). For a single-address client `dial_candidates` returns one entry, so `establish_bounded:1144` takes the `candidates.len() < 2` branch straight into `establish:1034`, which is a plain `TcpStream::connect` with no deadline. Against a black-holed address that parks for the kernel SYN-retry window.
The doc at `:45-54` calls out this exact hazard and then only fixes the one call site. Wrap the rest too.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
Review Comment:
**warning**
`TopicMapping` derives `Deserialize` and both fields are public, so anyone can build one straight from TOML and skip every check in `from_toml_str`: `default_stream`, whitespace, length, both injectivity rules.
That is not hypothetical, it already happens in this PR. `config.rs:117-120` constructs the struct directly, which is why `config.rs:103` needs its own separate `validate_identifier_name` call to make up for it.
Deserialize into a private raw struct and expose a checked conversion. You will also need a checked constructor for the no-file path, otherwise this breaks `config.rs:117-120` plus the direct constructions at `topic_map.rs:184`, `:204` and `config.rs:143`.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
Review Comment:
**warning**
Related to this comment, and worth settling before #3537: `PartitionResponse` has no log start offset at all. Fields are id, created_at, segments_count, current_offset, size_bytes, messages_count (`core/binary_protocol/src/responses/topics/get_topic.rs:30`), and the SDK type mirrors it.
So a `ListOffsets` EARLIEST answer built on this has to guess 0. Once retention trims sealed segments the earliest readable offset is above 0, and a consumer that seeks to the guessed 0 takes `OFFSET_OUT_OF_RANGE` on the next Fetch.
This is a pre-existing gap in the wire response, not something this PR introduced, but this module is where it bites. Add a partition start offset before the ListOffsets handler lands.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected
+ | IggyError::EmptyResponse
+ | IggyError::Unauthenticated
+ | IggyError::StaleClient
+ | IggyError::NotConnected
+ | IggyError::CannotEstablishConnection
+ | IggyError::TcpError
+ | IggyError::TransientNotAccepted => ERROR_NOT_LEADER_OR_FOLLOWER,
+ IggyError::TransientNotCommitted => ERROR_REQUEST_TIMED_OUT,
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
Review Comment:
nit: two Iggy errors fall through to `UNKNOWN_SERVER_ERROR` (-1) here when better codes exist.
`TooManyPartitions` (server raises it above 1000, `core/server/src/rewrite.rs:219`) could use `ERROR_INVALID_PARTITIONS`, which already exists unused at `protocol/api.rs:74`.
`InvalidIdentifier` is a client-input error too. Worth narrowing if you do it though: the server also returns `InvalidIdentifier` for an absent partition id (`core/server/src/responses.rs:488`), so a blanket arm to `INVALID_TOPIC_EXCEPTION` (17) would mislabel that.
Not a retry problem, since -1 is already fatal on the client. Just message quality.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
Review Comment:
nit: the rationale here (and the twin at `protocol/api.rs:56-59`) is wrong about Kafka. `REQUEST_TIMED_OUT` does not stop a retry: `TimeoutException extends RetriableException`, and `Sender.canRetry` retries anything retriable. The Java producer treats 7 the same as 6.
Keep code 7 though. A real broker sends it for the same unknown-outcome case after an ack timeout, and Kafka has no non-retriable "outcome unknown" code at all. Changing the value also breaks the test at `:222-228`.
So just rewrite both comments to say that, and note the duplicate-write window stays open until #3535 has an idempotent produce path.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
Review Comment:
**warning**
`high_watermark` takes one partition, so one Kafka `ListOffsets` request costs one `get_topic` round trip per partition. `ListOffsetsRequest.json` has `Topics[] -> Partitions[]`, so a client asks about many at once.
Worse, every decode rebuilds and sorts the whole partition vector (`core/common/src/wire_conversions.rs:171-174`), so N partitions costs N round trips and N*P decoded records for a single request.
One `get_topic` can serve the whole thing. Add a batch variant that takes a slice of partition ids and fetches `TopicDetails` once.
Nothing calls this yet, so it costs nothing today, but #3537 inherits the signature. Cheaper to change now than in four PRs.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
Review Comment:
nit: the doc says this is "the offset the next produced message receives". It is one past the last committed offset, which is not the same thing. `mint_frontier` sits above `offset_frontier` by the journaled-but-uncommitted offsets plus the crash reservation lease.
The number is still correct for ListOffsets LATEST, so this is only the wording. But a Produce handler that predicts a base offset from it would be wrong after a crash.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
Review Comment:
nit: stream first, then topic, so a topic failure leaves an empty stream behind. An idempotent retry heals it, but until then it holds a metadata slab key and shows up in `get_streams`.
Worth a line in the doc comment. Do not roll back the stream on failure: `topic_map.rs:99-102` sends every unmapped Kafka topic to the same `default_stream`, so a delete could take out another topic's data, and `ensure_stream` cannot tell you whether this call created it anyway.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
Review Comment:
**warning**
One `IggyClient` for the whole gateway, and the SDK TCP client is lockstep. Its own comment says so at `core/sdk/src/tcp/tcp_client.rs:1428`: "The connection is lockstep (one request in flight per client)". The stream mutex is held across write, flush and read at `:1421-1487`.
So every Kafka connection ends up serialized behind one Iggy request, no matter how many Kafka clients connect. The Kafka-side connection limit does not help.
Either pool clients or say the ceiling out loud in the README, which currently mentions neither. `close(self)` already looks like it anticipates an Arc-shared bridge.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ // `TryFrom<GetTopicResponse> for TopicDetails` (wire_conversions.rs) sorts `partitions` by
+ // `id` on every decode, so a binary search is correct here, not just faster than the
+ // linear scan it replaces - for a 1000-partition topic, the difference is O(log n) vs
+ // O(n) probes on every high_watermark call.
+ let partition_details = match details
+ .partitions
+ .binary_search_by_key(&partition, |p| p.id)
+ {
+ Ok(index) => &details.partitions[index],
+ Err(_) => {
+ return Err(BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the
+ // wrong (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ });
+ }
+ };
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
Review Comment:
nit: `messages_count == 0 && current_offset == 0` also matches a partition whose single message at offset 0 got trimmed, so the watermark goes 1 then back to 0. A Kafka watermark is never supposed to move backward.
Narrow in practice, and not fixable from this side anyway since `PartitionResponse` has no frontier field, which the comment above already says. Flagging it so it is on the record.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
Review Comment:
nit: this says the arm re-verifies by name "the same way `ensure_stream`'s arm does", but that arm at `:194-197` is a comment and `Ok(identifier)`. It does no second lookup. Drop the cross-reference.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
Review Comment:
nit: `resolve` hands back owned `String`s and both callers immediately copy them into `Identifier`s, so that is two allocations plus a copy per call.
`resolve<'a>(&'a self, kafka_topic: &'a str) -> (&'a str, &'a str)` works at both production call sites. The error arm at `iggy_bridge.rs:347-348` turns two `clone()` into two `to_string()` on a cold path, and four test tuples need updating.
Low stakes since it sits behind a network round trip, but this is the signature Produce will be calling.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
Review Comment:
nit: no test reaches this arm or the `TopicNameAlreadyExists` one at `:271`, and the second one carries a whole extra `get_topic` plus a mismatch check. The README sells the create-race handling as the idempotency promise, so it is a shame it is uncovered.
I do not think there is a clean fix right now. `IggyBridge` holds a concrete `IggyClient`, so there is no seam for a fake that returns `StreamNameAlreadyExists`, and pre-creating the stream sends you down the `get_stream` path instead. Two concurrent calls would hit it sometimes, which is a flaky test that can pass while covering nothing.
Probably just a comment recording the gap until something introduces a client seam.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,287 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches `DEFAULT_ROOT_USERNAME` (`core/server/src/boot/credentials.rs`) - the root user's
+/// username is always `iggy` regardless of how its password was provisioned, so defaulting this
+/// one field is safe. The password is a different story - see why there is no
+/// `DEFAULT_IGGY_PASSWORD` at [`IggyBridgeConfig::from_env`].
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
Review Comment:
nit: this says to add each new var to both lists or a typo silently no-ops. `main.rs:65-67` says the opposite, that the lists stay separate on purpose, and the guard at `main.rs:90-93` ORs two `contains` calls, so one list is enough and the silent no-op does not happen. Two comments disagreeing.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,287 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches `DEFAULT_ROOT_USERNAME` (`core/server/src/boot/credentials.rs`) - the root user's
+/// username is always `iggy` regardless of how its password was provisioned, so defaulting this
+/// one field is safe. The password is a different story - see why there is no
+/// `DEFAULT_IGGY_PASSWORD` at [`IggyBridgeConfig::from_env`].
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
+ /// surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in `core/configs`, so the
+ /// central provider's own typo-detection doesn't cover this namespace either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root username.
+ ///
+ /// `IGGY_KAFKA_IGGY_PASSWORD` has no default and must be set explicitly. `iggy-server` only
+ /// provisions the well-known `iggy`/`iggy` root credentials when started with
+ /// `--with-default-root-credentials` (`args.rs`, itself documented "INSECURE - FOR DEVELOPMENT
+ /// ONLY!"); without that flag it generates a random password (`boot/credentials.rs`) that no
+ /// constant here could ever guess. Defaulting the password to `"iggy"` would make this bridge
+ /// silently authenticate as root, with the credential in no config file and no log, on any
+ /// server that does happen to run dev-flagged - the failure mode of getting it wrong is a
+ /// loud, immediate auth rejection instead.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_IGGY_PASSWORD` is unset, or if
+ /// `IGGY_KAFKA_TOPIC_MAP_PATH` is set but the file is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD").map_err(|_| {
Review Comment:
nit: `std::env::var` returns `Ok("")` for `VAR=`, so this rejects an unset password but accepts an empty one. Same for the username at `:84`, where an empty value also skips the `DEFAULT_IGGY_USERNAME` fallback.
These two are the only inputs in the function with no check at all, while `IGGY_KAFKA_IGGY_STREAM` gets `validate_identifier_name` at `:103`. It does fail loudly at login, so not urgent, but the `# Errors` doc says "unset" and would need to say "unset or empty".
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is not a dependency this one wants: heavyweight, and pulling it in for one function would
+/// make every `core/sdk` change re-run this crate's server-spawning tests, per `Cargo.toml`'s own
Review Comment:
nit: the `core/sdk` half of this is stale. `gateways/kafka/Cargo.toml:37` depends on `iggy` directly now, so `core/sdk` changes already re-run these tests either way.
Also "per `Cargo.toml`'s own dependency-edge note" points at a note that is not there. The only comment in that file is about `kafka-protocol` default features.
The "heavyweight" half is still a good reason, so I would trim rather than delete.
##########
gateways/kafka/src/main.rs:
##########
@@ -186,15 +222,22 @@ async fn shutdown_signal() {
#[cfg(test)]
mod tests {
+ use serial_test::serial;
+
use super::{parse_positive, reject_unknown_kafka_env_vars};
- /// Sequential (not two separate `#[test]` fns) so the two env-var mutations can't race
- /// against each other under the test harness's default parallel execution - env vars are
- /// process-global state.
+ /// Sequential (not two separate `#[test]` fns), and `#[serial]` (unkeyed - the whole binary's
+ /// default group, shared with `bridge::config`'s and `server`'s env-touching tests).
Review Comment:
nit: the parenthetical says this shares the binary's default serial group with `bridge::config`'s and `server`'s tests. It does not. `main.rs` compiles into the bin test binary and those compile into the lib one, and `#[serial]` uses a process-local mutex, so the group never spans the two.
Nothing is unsound, the `# Safety` note below already scopes itself to "in this binary" and this is the only `#[serial]` test here. `server.rs:893` makes the mirror-image claim.
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
Review Comment:
nit: "so a bridge call fails in bounded time" overstates it. `CONNECT_TIMEOUT` bounds the initial connect only. `ensure_stream_and_topic` and `high_watermark` have no deadline (see the warning on `iggy_bridge.rs:151`).
The line above does say "the whole connect attempt", so a careful reader recovers it, but this sentence on its own reads like a general guarantee.
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. See `IggyBridge::connect`'s doc comment.
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
+still fall back to the default rule.
+
+### Provisioning and idempotency
+
+`ensure_stream_and_topic(kafka_topic, partition_count)` creates the mapped Iggy stream and topic
+if either is missing. Idempotent when repeated with the *same* `partition_count`: a no-op if both
+already exist with that count, and a `NameAlreadyExists` race against a concurrent caller creating
+the same stream/topic is treated as success, not an error - the goal is "it exists," not "this
+call created it." A *different* `partition_count` against an already-existing topic returns
+`BridgeError::PartitionCountMismatch` rather than silently keeping the old count or growing it -
+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. Nothing is bounding retention until it's configured explicitly (Iggy's own topic options,
+outside this bridge today); repointing a Kafka app that assumes bounded retention onto this bridge
+will accumulate data indefinitely unless you set that up yourself.
+
+### Error mapping
+
+`BridgeError::to_kafka_error_code()` maps Iggy failures to Kafka wire error codes - stream/topic
+not found → `UNKNOWN_TOPIC_OR_PARTITION` (3), auth/credential failures →
+`TOPIC_AUTHORIZATION_FAILED` (29), connection-shaped failures → `NOT_LEADER_OR_FOLLOWER` (6, the
+same retriable code the foundation's own stubs send, so a client backs off and retries),
+`PartitionCountMismatch` → `TOPIC_ALREADY_EXISTS` (36, not `INVALID_PARTITIONS` - that code's own
+text is "below 1", a different condition), anything else → `UNKNOWN_SERVER_ERROR` (-1).
Review Comment:
nit: this list never mentions `REQUEST_TIMED_OUT` (7), which `error.rs:129` sends for `TransientNotCommitted`. So the closing "anything else -> UNKNOWN_SERVER_ERROR (-1)" is not true.
##########
gateways/kafka/src/lib.rs:
##########
@@ -17,6 +17,7 @@
//! Kafka wire protocol gateway foundation for Apache Iggy.
+pub mod bridge;
Review Comment:
nit: `bridge` gets no crate-root re-export while `server` gets two, so the two modules need different import styles.
Honestly the crate is already mixed on this (`main.rs:27-28` imports from both paths for `server` alone, and `protocol` has no root re-export at all with seven test files reaching through the module path), so take it or leave it. Just noting the inconsistency.
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. See `IggyBridge::connect`'s doc comment.
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
+still fall back to the default rule.
+
+### Provisioning and idempotency
+
+`ensure_stream_and_topic(kafka_topic, partition_count)` creates the mapped Iggy stream and topic
+if either is missing. Idempotent when repeated with the *same* `partition_count`: a no-op if both
+already exist with that count, and a `NameAlreadyExists` race against a concurrent caller creating
+the same stream/topic is treated as success, not an error - the goal is "it exists," not "this
+call created it." A *different* `partition_count` against an already-existing topic returns
+`BridgeError::PartitionCountMismatch` rather than silently keeping the old count or growing it -
+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
Review Comment:
nit: retention is documented here, durability is not, and that is the one with teeth. `TopicCreateOptions::default()` gives `Durability::Replicated`, documented as "quorum commit without an additional stable-storage barrier", and the disk write is threshold-gated at 1024 messages / 1 MiB.
Same posture as Kafka's own default so it is not wrong, but on a single node both can lose an acked write to a power cut and an operator should read that here rather than dig into `durability.rs`.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
Four small ones on this signature:
1. `kafka_topic` never goes through `validate_identifier_name`, so a padded name creates a padded Iggy topic. The config path rejects exactly that name at `topic_map.rs:47`, so the two paths disagree. `high_watermark` at `:337-339` has the same gap. (An empty name does get caught, by `Identifier::named`.)
2. `partition_count == 0` is accepted and creates a topic nothing can produce to. The server allows it by design (`core/server/src/rewrite.rs:205-207`) and the CreateTopics stub already rejects it at `protocol/responses.rs:285`, so this is just defense in depth.
3. Nothing memoizes provisioned topics, so every call pays two round trips. I would only document once-per-topic calling rather than add a cache: a cache breaks `ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate` at `tests:655-705`.
4. Kafka sends `num_partitions` as `i32` where -1 means "broker default". `protocol/responses.rs:267-282` checks for -1 but never resolves it. Worth deciding now. Note `TopicCreateOptions::partitions_count` is `Option<u32>` where `None` gives 1.
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
Review Comment:
nit: `RECONNECTION_RETRIES` is named but its value (3) is not, while `CONNECT_TIMEOUT`'s is right there on the next line. Neither is settable, so an operator reading this cannot act on the name alone.
Also `:84` sends the reader to `IggyBridge::connect`'s doc comment, whose rustdoc links point at private items and will not render for them.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
Review Comment:
nit: `IggyError::PartitionNotFound` is missing from this arm, so it falls to -1 while the bridge's own equivalent maps to 3.
Unreachable from this PR, since the bridge only calls `get_stream`, `create_stream`, `get_topic` and `create_topic`, and the server only raises it on poll/send (`core/server/src/responses.rs:494`). But Produce and Fetch do hit it, so worth landing before those handlers.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
Review Comment:
nit, not about this line: the PR description's error table says `INVALID_PARTITIONS` (37) for a partition count mismatch, in two places. The code sends 36 here, and it is right to, since `INVALID_PARTITIONS`'s own text is "Number of partitions is below 1."
The README and the test at `:247` already agree with the code. Only the PR description is out of date.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
Review Comment:
**warning**
This is not "the first test pays for a build". `BINARY_PATH` is a process-local `OnceLock`, and nextest runs every test in its own process, so it memoizes nothing. All ten tests that spawn a server run `cargo build --package server` again, and each one faces the 300s hard kill on its own (`.config/nextest.toml:59-60`, and `[profile.ci]` only overrides `retries`, so it inherits the timeout). When it trips, the only output is `(test timed out)`, which points nowhere near the real cause.
The justification at `:194-199` is also wrong. `Command::cargo_bin` does not fail because the binary belongs to another package. It falls back to `legacy_cargo_bin`, which derives the dir from `current_exe()` and returns any binary sitting there. That is exactly why `core/integration/src/harness/handle/server.rs:944` works with no `server` dependency (`core/integration/Cargo.toml` lists only `assert_cmd`). The `CARGO_TARGET_DIR` worry at `:201-204` misses for the same reason: `legacy_cargo_bin` guesses no path.
CI happens to pre-build `iggy-server` in the same composite step, so the real exposure is a cold local run. Still, use `Command::cargo_bin("iggy-server")` like the rest of the repo and drop the stale reason.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected
+ | IggyError::EmptyResponse
+ | IggyError::Unauthenticated
+ | IggyError::StaleClient
+ | IggyError::NotConnected
+ | IggyError::CannotEstablishConnection
+ | IggyError::TcpError
+ | IggyError::TransientNotAccepted => ERROR_NOT_LEADER_OR_FOLLOWER,
+ IggyError::TransientNotCommitted => ERROR_REQUEST_TIMED_OUT,
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use iggy::prelude::Identifier;
+
+ #[test]
Review Comment:
nit on the test block below: all seventeen of these compare `to_kafka_error_code` against the same `ERROR_*` constants the function returns. So they pin the routing, which is good, but a wrong wire number would still pass every one of them.
I checked all twelve constants in `protocol/api.rs` against `Errors.java` and they are all correct today. Nothing in the crate holds them there.
`kafka-protocol` 0.18.0 is already a dependency and ships `error::ResponseError` with `code()`, which covers eleven of the twelve (not `ERROR_NONE`). Asserting against that would make these tests actually load-bearing.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape (an
+ /// unrecognized field - e.g. a `[topic.x]` typo for `[topics.x]` - is rejected here rather
+ /// than silently parsing to an empty override map), if `default_stream` or any override's
+ /// `stream`/`topic` is empty, has leading/trailing whitespace, or exceeds
+ /// `MAX_IDENTIFIER_LEN`, or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)) - in every validation case, letting it through here would
+ /// otherwise fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, with no link
+ /// back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ validate_identifier_name("topic mapping's default_stream", &mapping.default_stream)?;
+
+ let mut targets = HashSet::with_capacity(mapping.topics.len());
+ for (kafka_topic, over) in &mapping.topics {
+ validate_identifier_name(
+ &format!("topic mapping override for '{kafka_topic}''s stream"),
Review Comment:
nit: doubled apostrophe. This renders as `topic mapping override for 'orders''s stream`. Same at `:129`.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape (an
+ /// unrecognized field - e.g. a `[topic.x]` typo for `[topics.x]` - is rejected here rather
+ /// than silently parsing to an empty override map), if `default_stream` or any override's
+ /// `stream`/`topic` is empty, has leading/trailing whitespace, or exceeds
+ /// `MAX_IDENTIFIER_LEN`, or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)) - in every validation case, letting it through here would
+ /// otherwise fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, with no link
+ /// back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ validate_identifier_name("topic mapping's default_stream", &mapping.default_stream)?;
+
+ let mut targets = HashSet::with_capacity(mapping.topics.len());
+ for (kafka_topic, over) in &mapping.topics {
+ validate_identifier_name(
+ &format!("topic mapping override for '{kafka_topic}''s stream"),
+ &over.stream,
+ )?;
+ validate_identifier_name(
+ &format!("topic mapping override for '{kafka_topic}''s topic"),
+ &over.topic,
+ )?;
+
+ let target = (over.stream.clone(), over.topic.clone());
Review Comment:
nit: clones both strings into the set for every entry. Config load over a handful of overrides, so not a real cost, but `HashSet<(&str, &str)>` compiles fine here (I checked the later move of `mapping` does not conflict with the borrow).
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
Review Comment:
nit on the return type: this is `u64`, but the `ListOffsets` field it exists to fill is `int64` (`ListOffsetsResponse.json`). Returning `i64` saves the future handler a cast at the wire boundary. Tradeoff is that it moves the lossy conversion into the bridge at `:377`, since `Partition::current_offset` is `u64`.
No test breaks either way, the assertions use untyped literals.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ // `TryFrom<GetTopicResponse> for TopicDetails` (wire_conversions.rs) sorts `partitions` by
+ // `id` on every decode, so a binary search is correct here, not just faster than the
+ // linear scan it replaces - for a 1000-partition topic, the difference is O(log n) vs
+ // O(n) probes on every high_watermark call.
+ let partition_details = match details
+ .partitions
+ .binary_search_by_key(&partition, |p| p.id)
+ {
+ Ok(index) => &details.partitions[index],
+ Err(_) => {
+ return Err(BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the
+ // wrong (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ });
+ }
+ };
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
+ 0
+ } else {
+ partition_details.current_offset + 1
Review Comment:
nit: `current_offset + 1` on a wire-decoded `u64`. A corrupt `u64::MAX` panics in debug (overflow checks are on by default and the root `Cargo.toml` does not override them) and wraps to 0 in release. `saturating_add(1)` costs nothing here.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
Review Comment:
nit: a missing *stream* also makes `get_topic` return `Ok(None)` (`core/server/src/responses.rs:1225`), so this reports `TopicNameNotFound` when the stream is the thing that is gone.
Both map to the same Kafka code, so no client can tell, it is only the log text. I would widen the message rather than add a stream lookup, since that would cost an extra round trip on a future per-partition path.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is not a dependency this one wants: heavyweight, and pulling it in for one function would
+/// make every `core/sdk` change re-run this crate's server-spawning tests, per `Cargo.toml`'s own
+/// dependency-edge note). A bare SIGKILL skips `iggy-server`'s shutdown path entirely, which is a
+/// materially different exit than what the binary is actually built to do on `SIGTERM` -
+/// `.kill()` alone bypassed that in every test run before this fix.
+const SIGTERM_TIMEOUT: Duration = Duration::from_secs(5);
+const SIGKILL_POLL_INTERVAL: Duration = Duration::from_millis(50);
+
+fn graceful_kill(child: &mut Child) {
+ let pid = child.id() as libc::pid_t;
+ // Safety: `pid` is this process's own live child, obtained from `Child::id` immediately
+ // above; sending it a signal is exactly what `Child::kill` itself does internally.
+ unsafe {
+ libc::kill(pid, libc::SIGTERM);
+ }
+
+ let deadline = std::time::Instant::now() + SIGTERM_TIMEOUT;
+ while std::time::Instant::now() < deadline {
+ match child.try_wait() {
+ Ok(None) => std::thread::sleep(SIGKILL_POLL_INTERVAL),
+ Ok(Some(_)) | Err(_) => return,
+ }
+ }
+
+ let _ = child.kill();
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ graceful_kill(&mut self.child);
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("second call is a no-op against the now-existing stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("third call is still a no-op");
+
+ // Read back real state, not just three Oks: proves the second and third calls were actually
+ // no-ops against the one topic the first call created, not e.g. three independent topics
+ // that all happen to satisfy Ok(()) individually.
+ let raw = raw_client(&server).await;
+ let topics = raw
+ .get_topics(&Identifier::named("kafka").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(topics.len(), 1, "must be exactly one topic, not three");
+ assert_eq!(topics[0].name, "orders");
+ assert_eq!(topics[0].partitions_count, 3);
+}
+
+/// Regression test for coverage: nothing previously exercised `PartitionCountMismatch` on a real
+/// server - only unit tests constructed the variant directly.
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_rejects_a_second_call_with_a_different_partition_count() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the topic with 3 partitions");
+
+ let err = bridge
+ .ensure_stream_and_topic("orders", 5)
+ .await
+ .expect_err(
+ "a different partition count against an existing topic must not silently succeed",
+ );
+ match err {
+ BridgeError::PartitionCountMismatch {
+ topic,
+ existing,
+ requested,
+ } => {
+ assert_eq!(topic, "orders", "must report the Kafka-side name");
+ assert_eq!(existing, 3);
+ assert_eq!(requested, 5);
+ }
+ other => panic!("expected PartitionCountMismatch, got {other:?}"),
+ }
+}
+
+/// Regression test for coverage: every other test uses an empty `TopicMapping` (`HashMap::new()`),
+/// so the Kafka-name-vs-Iggy-name distinction `ensure_topic`/`high_watermark` deliberately
+/// maintain in their error paths (`kafka_topic`, not the resolved `topic_name`) can never actually
+/// differ and so can never be caught wrong. This test maps a Kafka topic to a differently-named
+/// Iggy stream/topic and checks both the happy path and the error paths report the Kafka-side
+/// name a real caller (a future handler) would recognize.
+#[tokio::test]
+#[serial]
+async fn bridge_operations_report_the_kafka_side_name_through_a_real_topic_mapping_override() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let mut config = server.test_config();
+ config.topic_mapping.topics.insert(
+ "orders".to_string(),
+ TopicOverride {
+ stream: "billing".to_string(),
+ topic: "orders_v2".to_string(),
+ },
+ );
+ let bridge = IggyBridge::connect(config)
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("must create the mapped Iggy stream/topic, not one named after the Kafka topic");
+
+ // The Iggy-side resources are named differently from the Kafka topic - confirms the mapping
+ // actually took effect, not that resolve() was a no-op that happened to pass either way.
+ let raw = raw_client(&server).await;
+ let billing_topics = raw
+ .get_topics(&Identifier::named("billing").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(billing_topics.len(), 1);
+ assert_eq!(billing_topics[0].name, "orders_v2");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("must resolve through the mapping, not fail looking for a stream named 'orders'");
+ assert_eq!(watermark, 0);
+
+ let out_of_range = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(
+ matches!(
+ &out_of_range,
+ BridgeError::PartitionOutOfRange { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {out_of_range:?}"
+ );
+
+ let mismatch = bridge
+ .ensure_stream_and_topic("orders", 2)
+ .await
+ .expect_err("different partition count against the mapped topic must not silently succeed");
+ assert!(
+ matches!(
+ &mismatch,
+ BridgeError::PartitionCountMismatch { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {mismatch:?}"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_is_zero_for_a_fresh_empty_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("fresh topic must report a watermark, not an error");
+ assert_eq!(
+ watermark, 0,
+ "a freshly created, empty partition's high watermark must be 0"
+ );
+}
+
+/// Pins the exact semantics of `Iggy::Partition::current_offset` (offset of the *last written*
+/// message, not Kafka's "next offset to produce") against a real server - a test that only
+/// checked the empty-topic case would pass under either interpretation and hide an off-by-one.
+#[tokio::test]
+#[serial]
+async fn high_watermark_reflects_produced_messages() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before producing");
+
+ let stream_id = Identifier::named("kafka").expect("valid stream name");
+ let topic_id = Identifier::named("orders").expect("valid topic name");
+ let mut messages: Vec<IggyMessage> = (0..3)
+ .map(|i| IggyMessage::from(format!("message-{i}")))
+ .collect();
+ let client = raw_client(&server).await;
+ client
+ .send_messages(
+ &stream_id,
+ &topic_id,
+ &Partitioning::partition_id(0),
+ &mut messages,
+ )
+ .await
+ .expect("send 3 messages");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("topic must report a watermark after producing");
+ assert_eq!(
+ watermark, 3,
+ "high watermark after 3 messages (offsets 0, 1, 2) must be 3, not the last offset (2)"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_rejects_out_of_range_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let err = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(matches!(err, BridgeError::PartitionOutOfRange { .. }));
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_for_a_numeric_topic_name() {
+ // Regression test: Identifier::try_from/FromStr parses an all-digit string as a numeric ID,
+ // not a name - a second call for the same numeric-named topic would look it up by the wrong
+ // resource kind and fail with StreamIdNotFound/TopicIdNotFound despite the topic existing.
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("first call creates the numeric-named stream and topic");
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("second call must still find the numeric-named topic by name, not by ID");
+}
+
+/// Regression test: `ensure_stream` used to hand `ensure_topic` the stream's *numeric* id
+/// (`Identifier::numeric`), and streams are backed by a recycled slab (freed keys are reused by
+/// the next created stream) - a stream deleted and recreated between the two calls would leave
+/// `ensure_topic` writing into whatever stream now holds that recycled numeric key, not the one
+/// `ensure_stream_and_topic`'s caller actually resolved. The fix threads the *named* `Identifier`
+/// through instead. This does not (cannot, from a black-box test) hit the exact `await` window the
+/// bug lived in, but it does prove the name, not a captured numeric id, is what actually governs:
+/// delete the stream, recreate it under the same name, and the very next call must still land the
+/// topic on the live incarnation.
+#[tokio::test]
+#[serial]
+async fn ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("first call creates the default stream and topic");
+
+ let raw = raw_client(&server).await;
+ let stream_name = Identifier::named("kafka").expect("valid stream name");
+ let original = raw
+ .get_stream(&stream_name)
+ .await
+ .expect("get_stream call")
+ .expect("stream exists after ensure_stream_and_topic");
+ raw.delete_stream(&Identifier::numeric(original.id).expect("numeric id"))
+ .await
+ .expect("delete the stream (and its topic with it)");
+ let recreated = raw
+ .create_stream("kafka")
+ .await
+ .expect("recreate a stream under the same name");
+ if recreated.id == original.id {
+ // Not guaranteed by any API contract, but the metadata slab does reuse freed low
+ // indices - confirms this run actually exercised the recycled-key scenario, not just a
+ // coincidentally-fresh one.
+ eprintln!(
+ "recreated stream reused the original numeric id {}",
+ recreated.id
+ );
+ }
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("must create the topic under the live stream, not a stale numeric id");
+
+ let topic = raw
+ .get_topic(
+ &stream_name,
+ &Identifier::named("orders").expect("valid topic name"),
+ )
+ .await
+ .expect("get_topic call")
+ .expect("topic exists under the recreated stream");
+ assert_eq!(topic.partitions_count, 1);
+}
+
+/// Finding: the SDK's connection-string parser splits on `@` then `:`, so a password containing
+/// either character breaks unless credentials are passed as already-separated fields.
+#[tokio::test]
+#[serial]
+async fn connect_succeeds_with_password_containing_special_characters() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+ let password = "p@ss:word";
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.path().display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", password);
+ let mut child = command.spawn().expect("spawn iggy-server");
Review Comment:
nit: this one spawns a server with no `Drop` guard, so a panic before `:752` orphans a process still holding the port. `PortGuard` releases its flock on unwind but the server keeps the socket, so the next test to draw that slot fails to bind.
Line 752 also uses the bare `child.kill()` that the comment at `:338-344` argues against.
Giving `TestServer::spawn` a password argument fixes both and drops about 35 lines. Nine call sites gain one arg, and `test_config` at `:329` hardcodes the password too.
##########
.config/nextest.toml:
##########
@@ -39,6 +39,23 @@ max-threads = 1
filter = 'package(integration) and test(/connectors::elasticsearch::/)'
test-group = "elasticsearch"
+# Each test in this binary spawns its own real iggy-server subprocess (isolated data dir, port
+# from PortGuard's own flock, so no two ever share a port). #[serial] on them is a dead letter
+# under nextest - nextest runs every test as its own process, and #[serial]'s mutex only excludes
+# within one process (nextest does not support #[serial] macro, same gap the workaround above
+# documents). Without this override, nextest's default scheduler runs several of these processes
+# at once, and every one of them inherits this workspace's cpu_allocation = "numa:auto" /
Review Comment:
nit: the `pin_cores = true` half of this is already stale. The test file sets `IGGY_SHARDING_PIN_CORES=false` at `bridge_iggy_integration_tests.rs:271`.
The `cpu_allocation = "numa:auto"` half still holds, nothing sets `IGGY_SHARDING_CPU_ALLOCATION`, so every spawned server still sizes its shard pool to the whole box.
Keep `max-threads = 1` regardless. I measured it: two concurrent no-op `cargo build` runs on one target dir block on "file lock on package cache" and "file lock on artifact directory". Dropping the serialization while the tests still shell out to cargo puts ten of those on one lock, each burning its own 300s budget. Just fix the comment.
##########
gateways/kafka/Cargo.toml:
##########
@@ -51,11 +54,15 @@ tokio = { workspace = true, features = [
"signal",
] }
tokio-util = { workspace = true, features = ["rt"] }
+toml = { workspace = true }
tracing = { workspace = true }
tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true }
[dev-dependencies]
Review Comment:
nit: there is no dev-dependency edge to `server`, so `cargo rail plan --since origin/master` never puts `package(iggy-gateway-kafka)` in `NEXTEST_FILTER` for a `core/server` change. A server change never runs this suite, even though these tests spawn a real `iggy-server` and depend on its env var handling.
Adding `rust-server` to `rust-gateway`'s `depends_on` in `.github/config/components.yml` would not help, by the way. `rust-gateway` defines no `tasks`, so `_detect.yml:250-254` drops it into `skippedComponents` and it never makes a job. The fix has to go where cargo-rail sees the edge.
##########
gateways/kafka/Cargo.toml:
##########
@@ -34,11 +34,14 @@ path = "src/main.rs"
[dependencies]
bytes = { workspace = true }
+iggy = { workspace = true }
Review Comment:
nit: this gateway only talks TCP (`with_tcp()` at `iggy_bridge.rs:95`) but pulls `quinn`, `reqwest` and `tokio-tungstenite` in through the SDK.
Nothing to do here though, `core/sdk/Cargo.toml` has no `[features]` section at all, so those three are mandatory rather than default-on and `default-features = false` would not help. Flagging it as something to raise with the maintainers rather than a change for this PR.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is not a dependency this one wants: heavyweight, and pulling it in for one function would
+/// make every `core/sdk` change re-run this crate's server-spawning tests, per `Cargo.toml`'s own
+/// dependency-edge note). A bare SIGKILL skips `iggy-server`'s shutdown path entirely, which is a
+/// materially different exit than what the binary is actually built to do on `SIGTERM` -
+/// `.kill()` alone bypassed that in every test run before this fix.
+const SIGTERM_TIMEOUT: Duration = Duration::from_secs(5);
+const SIGKILL_POLL_INTERVAL: Duration = Duration::from_millis(50);
+
+fn graceful_kill(child: &mut Child) {
+ let pid = child.id() as libc::pid_t;
Review Comment:
nit: `wait_ready` at `:304` calls `try_wait()`, which reaps the child, and then panics. That unwinds into `Drop for TestServer`, which lands here and signals a PID that is already free.
Near-unreachable in practice and the same raw `libc::kill` pattern already exists at `core/integration/src/harness/handle/common.rs:138-144`, so this is house style rather than something new. Worth noting the safety comment above is wrong about std though: `Child::kill` already short-circuits on a stored status, so it is not missing the guard, it has one.
An early return when `try_wait()` gives `Ok(Some(_))` covers it.
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. See `IggyBridge::connect`'s doc comment.
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
Review Comment:
nit: two rules an operator needs are missing from this section.
A map file has to set `default_stream`. It is a required serde field (no `#[serde(default)]`, unlike `topics`), so an override-only file just fails to load.
And the file wins over `IGGY_KAFKA_IGGY_STREAM`. That rule only lives in `config.rs:71-75` right now, and the env var table at `:77` reads like the two compose.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001647918
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. See `IggyBridge::connect`'s doc comment.
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
+still fall back to the default rule.
+
+### Provisioning and idempotency
+
+`ensure_stream_and_topic(kafka_topic, partition_count)` creates the mapped Iggy stream and topic
+if either is missing. Idempotent when repeated with the *same* `partition_count`: a no-op if both
+already exist with that count, and a `NameAlreadyExists` race against a concurrent caller creating
+the same stream/topic is treated as success, not an error - the goal is "it exists," not "this
+call created it." A *different* `partition_count` against an already-existing topic returns
+`BridgeError::PartitionCountMismatch` rather than silently keeping the old count or growing it -
+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
Review Comment:
**Fixed** - added the durability paragraph with the flush-threshold numbers and the power-loss caveat, matching Kafka's own posture
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001637974
##########
gateways/kafka/Cargo.toml:
##########
@@ -34,11 +34,14 @@ path = "src/main.rs"
[dependencies]
bytes = { workspace = true }
+iggy = { workspace = true }
Review Comment:
**Agreed**, with the finding- nothing actionable here without SDK feature-gating that doesn't exist yet. Will raise it separately with the SDK maintainers rather than carry it in this PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001491954
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
Review Comment:
**Fixed** by widening the comment/message rather than adding a lookup, as you suggested - not worth the extra round trip for a log-text-only distinction.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001598442
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape (an
+ /// unrecognized field - e.g. a `[topic.x]` typo for `[topics.x]` - is rejected here rather
+ /// than silently parsing to an empty override map), if `default_stream` or any override's
+ /// `stream`/`topic` is empty, has leading/trailing whitespace, or exceeds
+ /// `MAX_IDENTIFIER_LEN`, or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)) - in every validation case, letting it through here would
+ /// otherwise fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, with no link
+ /// back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ validate_identifier_name("topic mapping's default_stream", &mapping.default_stream)?;
+
+ let mut targets = HashSet::with_capacity(mapping.topics.len());
+ for (kafka_topic, over) in &mapping.topics {
+ validate_identifier_name(
+ &format!("topic mapping override for '{kafka_topic}''s stream"),
Review Comment:
Fixed at both spots
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020296944
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
+
+/// Wraps a single Iggy client call in [`REQUEST_TIMEOUT`]. See that constant's doc for why every
+/// bridge method needs this, not just [`IggyBridge::connect`].
+async fn with_request_timeout<T>(
+ op: impl Future<Output = Result<T, IggyError>>,
+) -> Result<T, BridgeError> {
+ tokio::time::timeout(REQUEST_TIMEOUT, op)
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)
+}
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+///
+/// One `IggyClient`, shared across every Kafka connection this gateway serves - and the SDK's TCP
+/// transport is lockstep, one request in flight at a time (`tcp_client.rs`: "the connection is
+/// lockstep", its stream mutex held across write, flush, and read). Every concurrent Kafka
+/// connection ends up serialized behind whichever single Iggy request is in flight; the Kafka
+/// side's own connection limit does nothing to relieve this. No pooling exists yet - `close`
+/// already takes `self` by value, which anticipates an eventual `Arc`-shared bridge, but nothing
+/// wires that up today. Documented here and in the README rather than silently discovered under
+/// load once `#3535`/`#3536` land.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ with_request_timeout(client.connect()).await?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown), or if it takes longer than
+ /// `REQUEST_TIMEOUT`.
+ pub async fn close(self) -> Result<(), BridgeError> {
+ with_request_timeout(self.client.shutdown()).await
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// Ensures the stream before the topic, so a topic-creation failure (a different
+ /// `partition_count`, a transient error) can leave a stream that now exists with no topic in
+ /// it yet - a retry heals this (idempotent on the stream half too), and no rollback is
+ /// attempted: `TopicMapping::resolve` sends every *unmapped* Kafka topic to the same
+ /// `default_stream`, so deleting a stream on a topic-creation failure risks deleting another
+ /// topic's data that happens to share it, and this call has no way to tell whether it was the
+ /// one that created the stream in the first place.
+ ///
+ /// `partition_count` is `u32`, so it cannot carry Kafka's own `CreateTopics` sentinel
+ /// (`num_partitions == -1`, KIP-464 "use the broker default" - `protocol/responses.rs`
+ /// already accepts that sentinel at the wire-validation layer). Resolving *what* the broker
+ /// default should be for this bridge is a decision for whichever of `#3535`/`#3536` first
+ /// calls this with a real Kafka request in hand, not one to invent here ahead of that need.
+ ///
+ /// No caching: every call pays a `get_stream` and a `get_topic` (two round trips once both
+ /// already exist), even for a topic this same bridge already confirmed a moment ago. A cache
+ /// keyed on `kafka_topic` would remove that cost, but would also have to answer "how does a
+ /// cache entry ever get invalidated" - the topic being deleted and recreated with a different
+ /// partition count out from under a stale cache entry is exactly
+ /// `ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate`'s own
+ /// scenario, and a naive cache breaks that guarantee to save two round trips. Whatever wires
+ /// this into `#3535`/`#3536` should call it once per topic and remember that it did, rather
+ /// than once per Produce/Fetch - the cost belongs at the call site's discretion, not hidden
+ /// (and potentially made wrong) inside this method.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidKafkaTopicName`] if `kafka_topic` fails Kafka's own
+ /// topic-naming rules. Returns [`BridgeError::Iggy`] for connectivity/auth failures, or if a
+ /// call takes longer than `REQUEST_TIMEOUT`. Returns [`BridgeError::PartitionCountMismatch`]
+ /// if the topic already exists with a different partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ validate_kafka_topic_name("kafka_topic", kafka_topic)?;
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(stream_name).await?;
+ self.ensure_topic(&stream_id, topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if with_request_timeout(self.client.get_stream(&identifier))
+ .await?
+ .is_some()
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match with_request_timeout(self.client.create_stream(stream_name)).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(BridgeError::Iggy(IggyError::StreamNameAlreadyExists(_))) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(err),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - the same numeric-name ambiguity
+ /// [`Self::ensure_stream`]'s doc comment describes for stream names applies to topic names.
+ ///
+ /// `partition_count == 0` is accepted here as defense in depth, not the primary guard: the
+ /// server allows it by design (`rewrite.rs`), and the `CreateTopics` stub already rejects it
+ /// at the wire level (`protocol/responses.rs`) before any bridge call would be reachable.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) =
+ with_request_timeout(self.client.get_topic(stream_id, &identifier)).await?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match with_request_timeout(self.client.create_topic(stream_id, topic_name, &options)).await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ // Lost a create race - re-verify by name rather than trusting the race outcome alone.
+ // The winner may have created it with a different partition count than this call
+ // requested, so this needs the same mismatch check the existing-topic branch above
+ // makes - skipping it here would let two concurrent ensure_topic(N) / ensure_topic(M)
+ // calls for the same topic both return Ok(()).
+ //
+ // Untested: reaching this arm needs a real concurrent second caller mid-race, and
+ // `IggyBridge` holds a concrete `IggyClient` with no seam for a fake that returns
+ // `TopicNameAlreadyExists` on demand. A test that spins up two real concurrent callers
+ // would hit it only sometimes - flaky, and passing wouldn't prove this arm ran. Left
+ // as a known gap until something introduces a client seam.
+ Err(BridgeError::Iggy(IggyError::TopicNameAlreadyExists(_, _))) => {
+ let existing = with_request_timeout(self.client.get_topic(stream_id, &identifier))
+ .await?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.to_string(),
+ stream_id.to_string(),
+ ))
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(err),
+ }
+ }
+
+ /// Returns the high watermark (one past the highest *committed* offset - see
+ /// `Partition::offset_frontier`'s own definition) for every partition in `partitions` of the
+ /// Iggy topic `kafka_topic` maps to, in one round trip.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler) only ever has the Kafka-side name, and a
+ /// topic with a mapping override would silently query the wrong Iggy resource if this took
+ /// Iggy-space names directly instead.
+ ///
+ /// One call to `get_topic`, not one per partition: a single Kafka `ListOffsets` request asks
+ /// about many partitions of one topic at once (`ListOffsetsRequest.json`'s
+ /// `Topics[] -> Partitions[]`), and `get_topic`'s decode already rebuilds and sorts the whole
+ /// partition vector regardless of how many of them the caller wants
+ /// (`wire_conversions.rs`) - a naive one-call-per-partition wrapper around a
+ /// single-partition method would turn one Kafka request into N round trips and N times the
+ /// decode work. Returns results in the same order as `partitions`.
+ ///
+ /// `i64`, not `u64`: the `ListOffsets` response field this exists to fill is `int64`
+ /// (`ListOffsetsResponse.json`), so a future handler needs no cast at the wire boundary - the
+ /// lossy conversion happens once, here (`Partition::current_offset` is `u64`; converted via
+ /// `i64::try_from`, saturating to `i64::MAX` on the practically-unreachable overflow case
+ /// rather than panicking or wrapping).
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty. This is
+ /// still not exact: a partition whose *only* message, at offset 0, gets trimmed by the same
+ /// retention pass reports `(messages_count, current_offset) == (0, 0)` too, so its watermark
+ /// would read `1` then drop back to `0` - a real Kafka watermark never moves backward. Narrow
+ /// (needs retention to fully empty a partition that only ever held one message) and not
+ /// fixable client-side (`PartitionResponse` carries no frontier field to disambiguate it), but
+ /// worth having on the record rather than only implicitly true of the check below.
+ ///
+ /// Not the same value as `Partition::mint_frontier` (the offset the *next* mint will take):
+ /// after a crash-recovery reservation, the append point can sit above the committed frontier
+ /// by the reservation's lease block, and neither value is on the wire to tell them apart. This
+ /// is still correct for `ListOffsets` LATEST (defined in terms of the committed offset), but a
+ /// future Produce handler must not use it to predict a base offset for a write in flight.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidKafkaTopicName`] if `kafka_topic` fails Kafka's own
+ /// topic-naming rules. Returns [`BridgeError::Iggy`] if the mapped stream doesn't exist (see
+ /// the note above on which resource is actually missing), or if the call takes longer than
+ /// `REQUEST_TIMEOUT`. Returns [`BridgeError::PartitionOutOfRange`] if any requested
+ /// partition is beyond the topic's partition count.
+ pub async fn high_watermarks(
+ &self,
+ kafka_topic: &str,
+ partitions: &[u32],
+ ) -> Result<Vec<(u32, i64)>, BridgeError> {
Review Comment:
Fixed. high_watermarks now returns Vec<(u32, Result<i64, BridgeError>)> — one bad partition no longer discards the rest.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020511351
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Locates the already-built `iggy-server` binary. Does not build it - see this crate's
+/// `docs/TEST_SUITE.md` for the prerequisite, the same one `core/integration`'s own
+/// server-spawning tests already carry.
+///
+/// `assert_cmd::cargo::cargo_bin`, matching `core/integration`'s own
+/// `harness::handle::server::start` - not a from-scratch `cargo build` invocation. An earlier
+/// version of this function drove `cargo build --package server --bin iggy-server` directly,
+/// reasoning that `Command::cargo_bin` "only resolves `CARGO_BIN_EXE_*` for binaries owned by
+/// *this* package" - true of the `CARGO_BIN_EXE_*` env-var lookup alone, but `cargo_bin` falls
+/// back to `legacy_cargo_bin` when that's unset, which derives the target directory from
+/// `env::current_exe()` (this test binary's own path) and looks for a same-named file there -
+/// correct under `CARGO_TARGET_DIR`, `--release`, or a `--target` triple subdirectory precisely
+/// because it reads back from where cargo actually placed *this* binary, not a guessed path. That
+/// version also re-ran a `cargo build` from every one of this file's server-spawning tests
+/// (nextest runs each as its own process, so the `OnceLock` memoized nothing across them),
+/// serialized by `.config/nextest.toml`'s `kafka_bridge` test-group but still real, avoidable
+/// per-test overhead this version has none of.
+fn iggy_server_binary() -> PathBuf {
+ assert_cmd::cargo::cargo_bin("iggy-server")
Review Comment:
Replaced assert_cmd::cargo::cargo_bin with a self-contained path walk — removed assert_cmd dev-dep entirely (was now unused, would've failed cargo machete).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020473994
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,526 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Kafka's own topic-name cap (`Topic.MAX_NAME_LENGTH` in Kafka's own source) - smaller than
+/// [`MAX_IDENTIFIER_LEN`], so a Kafka-side name needs its own limit, not Iggy's.
+const MAX_KAFKA_TOPIC_NAME_LEN: usize = 249;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path. For a Kafka-side topic name (a TOML key, or a `kafka_topic` argument), use
+/// [`validate_kafka_topic_name`] instead - Kafka's own limits and legal characters differ from
+/// Iggy's.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Rejects a Kafka topic name that fails Kafka's own naming rules: empty, leading/trailing
+/// whitespace, over [`MAX_KAFKA_TOPIC_NAME_LEN`] bytes, or containing a byte outside
+/// `[A-Za-z0-9._-]` (Kafka's own `Topic.legalChars`).
+///
+/// Used both for TOML mapping-file keys (`from_toml_str`) and for the `kafka_topic` argument
+/// `IggyBridge::ensure_stream_and_topic`/`high_watermark` take directly - the two paths must agree,
+/// or a name the config file would reject can still reach Iggy unvalidated through the second
+/// path. A whitespace-padded key is the sharpest failure mode this catches: `resolve`'s lookup is
+/// an exact `HashMap::get`, so a padded key parses out of the TOML file cleanly and then matches
+/// nothing at runtime, silently falling through to the default stream instead of erroring - the
+/// one place in this module that would otherwise fail silently instead of loudly.
+///
+/// `field` is `"topic mapping key"` or `"kafka_topic"` in current callers, not a generic template -
+/// kept as a parameter (like [`validate_identifier_name`]) so the message names the actual site.
+pub(crate) fn validate_kafka_topic_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not be empty"),
+ });
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not have leading or trailing whitespace"),
+ });
+ }
+ if value.len() > MAX_KAFKA_TOPIC_NAME_LEN {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!(
+ "{field} is {} bytes, over Kafka's {MAX_KAFKA_TOPIC_NAME_LEN}-byte topic name limit",
+ value.len()
+ ),
+ });
+ }
+ if let Some(illegal) = value
Review Comment:
Reject "."/".." (Kafka's own special case).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5569422516
@krishvishal - I am back from my travel and ready with PR #4043 for the Kafka gateway.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967920300
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
+const PORT_LOCK_BAND_SLOTS: u16 = 200;
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, nothing ever binds the port on this side, so there is no TOCTOU window between
+/// picking it and `iggy-server` binding it: the lock, not a socket, is the allocator.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..PORT_LOCK_BAND_SLOTS {
+ let port = PORT_LOCK_BAND_START + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{PORT_LOCK_BAND_START}, {}]",
+ PORT_LOCK_BAND_START + PORT_LOCK_BAND_SLOTS - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_SYSTEM_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ async fn wait_ready(&self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
Review Comment:
Covered the gaps
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001487117
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
Review Comment:
Reply: Fixed - dropped the inaccurate comparison.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001650509
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
Review Comment:
**Fixed** - stated the value (3) directly and reworded the pointer to acknowledge the rustdoc is private rather than implying it's a clickable link.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001643188
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. See `IggyBridge::connect`'s doc comment.
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
Review Comment:
**Fixed** - both rules are now stated explicitly in the README's topic mapping section.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001642074
##########
gateways/kafka/src/main.rs:
##########
@@ -186,15 +222,22 @@ async fn shutdown_signal() {
#[cfg(test)]
mod tests {
+ use serial_test::serial;
+
use super::{parse_positive, reject_unknown_kafka_env_vars};
- /// Sequential (not two separate `#[test]` fns) so the two env-var mutations can't race
- /// against each other under the test harness's default parallel execution - env vars are
- /// process-global state.
+ /// Sequential (not two separate `#[test]` fns), and `#[serial]` (unkeyed - the whole binary's
+ /// default group, shared with `bridge::config`'s and `server`'s env-touching tests).
Review Comment:
**Fixed** both this one and the mirror-image claim on server.rs:init_tracing_is_idempotent has the same bug in reverse - corrected both to state their actual (and different) serial-group membership.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001448410
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected
+ | IggyError::EmptyResponse
+ | IggyError::Unauthenticated
+ | IggyError::StaleClient
+ | IggyError::NotConnected
+ | IggyError::CannotEstablishConnection
+ | IggyError::TcpError
+ | IggyError::TransientNotAccepted => ERROR_NOT_LEADER_OR_FOLLOWER,
+ IggyError::TransientNotCommitted => ERROR_REQUEST_TIMED_OUT,
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
Review Comment:
**Partially fixed**. TooManyPartitions now maps to ERROR_INVALID_PARTITIONS (37), with a new test (too_many_partitions_maps_to_invalid_partitions). InvalidIdentifier was deliberately left on the catch-all - to be cautios , the server also raises it for an absent partition id, and a blanket arm to INVALID_TOPIC_EXCEPTION would mislabel that case. Didn't see a safe narrower mapping without a stream-name-vs-partition-id lookup this method has no basis for, but open to a suggestion .
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3977665213
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count` as segments are dropped
+ /// (`core/partitions/src/iggy_partition.rs::decrement_messages_count`) but never rewinds
+ /// `current_offset` - a fully-retention-purged partition that has produced messages reports
+ /// `messages_count == 0` with `current_offset` still at its high value. Treating that as
+ /// "empty" would report high watermark `0` for a partition that has, in fact, produced past
+ /// offset `0`; a future `ListOffsets` (`#3537`) LATEST built on this would rewind instead of
+ /// pointing at the true next-write position.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ let partition_details = details
+ .partitions
+ .iter()
+ .find(|p| p.id == partition)
+ .ok_or_else(|| BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the wrong
+ // (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ })?;
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
Review Comment:
the wire response during that window is byte-identical to a genuinely empty partition, so there's no signal telling this client whether to trust the 0 or retry — and Kafka doesn't have to solve this at all, since a Kafka broker's knowledge of a partition is its local log directly, so an unauthoritative broker returns NOT_LEADER_OR_FOLLOWER instead of guessing. **Real fix** is
server-side (an explicit signal or error during rebuild), out of scope here. Will include in the known gap list.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3954378533
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthenticated
+ | IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected | IggyError::CannotEstablishConnection => {
+ ERROR_NOT_LEADER_OR_FOLLOWER
+ }
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
Review Comment:
**CRITICAL.** The Kafka error map doesn't match what the SDK returns.
The SDK's retriable set is at `tcp_client.rs:215-224`: `Disconnected | EmptyResponse | Unauthenticated | StaleClient | NotConnected | CannotEstablishConnection | TcpError`. This map covers two of seven; the rest fall to `_ => ERROR_UNKNOWN_SERVER_ERROR`, which `kafka-protocol-0.18.0/src/error.rs:183` marks `retriable=false`. A producer drops the batch instead of retrying. Two of the missing five are common: `send_raw` returns `NotConnected` for any call during a reconnect (`tcp_client.rs:1234-1241`), and an Iggy view change raises `TransientNotAccepted` (58), doc string "retry, on any replica".
Opposite problem in the same match: `Unauthenticated` maps to 29, also `retriable=false`, but `binary_auth.rs:27` shows it's the window before auto-sign-in completes. A reconnect kills a consumer with "Not authorized to access topics", pointing at ACLs this gateway doesn't have.
Fix: use the SDK's list; `Unauthenticated` to 6; keep `ClientShutdown` on `-1`. `TransientNotCommitted` means unknown outcome, so retry risks a duplicate; use `REQUEST_TIMED_OUT` (7), not 6, to make that explicit. `unauthenticated_maps_to_topic_authorization_failed` asserts the old mapping and needs updating.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
Review Comment:
**CRITICAL.** `close()` doesn't close.
`disconnect()` (`client.rs:993-995`) never touches `heartbeat_handle`; only `Drop for IggyClient` (`:933-943`) aborts it. Five seconds later the heartbeat pings, gets `NotConnected` (in the retriable set), and `sign_in_credentials()` still returns the configured `AutoLogin`, so it redials and re-authenticates. Dropping the bridge is safer than closing it.
Fix: `self.client.shutdown()`, and take `self` by value. Costs: `shutdown()` is terminal and can `Err` on a live socket; `close(self)` can't be called through an `Arc`.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
Review Comment:
**CRITICAL.** `connect()` has no dial timeout, and `README.md:79-82` repeats this claim.
`tcp_client.rs:1144`: `if candidates.len() < 2 { return self.establish(...) }` skips `FAILOVER_DIAL_TIMEOUT`, and `establish` (`:1034`) is a bare `TcpStream::connect`. A bridge config has one address. Against a firewall that DROPs, that's 4 passes at the kernel SYN timeout, roughly 8.5 min, not "a few seconds". The test dials an unbound loopback port, which RSTs instantly, so it only covers the easy case.
Fix: `tokio::time::timeout`, and put the real bound in the doc. Set it above p99 handshake, not 2s, or slow-but-alive servers start failing.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,204 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::TopicMapping;
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches the Iggy server's own default root user - not a made-up example, the same default
+/// every fresh `iggy-server` and every CLI quick-start in this repo uses.
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+const DEFAULT_IGGY_PASSWORD: &str = "iggy";
Review Comment:
**CRITICAL.** This comment is wrong.
`args.rs:109-120` shows `--with-default-root-credentials` defaults to `false` and is labelled "INSECURE - FOR DEVELOPMENT ONLY!"; otherwise the server generates a random password (`credentials.rs:112-118`). The gateway quietly runs as root on any dev-flagged Iggy, with the credential in no config file and no log.
Fix: drop `DEFAULT_IGGY_PASSWORD`, require `IGGY_KAFKA_IGGY_PASSWORD`, fix the comment. `helm/.../deployment.yaml:120-143` already has the `secretKeyRef` pattern. Quick-starts then need two env vars, which is cheap now and not later.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
Review Comment:
**CRITICAL.** This passes `ensure_topic` a reusable slab key.
The doc at `:125-130` argues for `Identifier::named` over numeric, then converts to numeric anyway, while `high_watermark:275` resolves by name. `stream.rs:1595-1599` says keys are recycled on delete. Delete and recreate a stream between the two round trips and `create_topic` writes into the wrong stream, returning `Ok(())`.
Fix: pass the `Identifier::named(stream_name)` already built at `:132`. Nothing breaks, and it removes three dead `.map_err` (`Identifier::numeric` is infallible) plus the `:226` error that prints a slab key where a stream name belongs.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
+const PORT_LOCK_BAND_SLOTS: u16 = 200;
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, nothing ever binds the port on this side, so there is no TOCTOU window between
+/// picking it and `iggy-server` binding it: the lock, not a socket, is the allocator.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..PORT_LOCK_BAND_SLOTS {
+ let port = PORT_LOCK_BAND_START + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{PORT_LOCK_BAND_START}, {}]",
+ PORT_LOCK_BAND_START + PORT_LOCK_BAND_SLOTS - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_SYSTEM_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ async fn wait_ready(&self) {
Review Comment:
**CRITICAL.** This harness reimplements the existing one, minus the safety parts.
`.config/nextest.toml:24-26` says in-repo that nextest ignores `#[serial]`, and no `threads-required` override was added. So up to 4 tests run at once, each spawning a server that inherits `cpu_allocation = "numa:auto"` and `pin_cores = true` (`config.toml:873,883`) - `harness/handle/server.rs:311-319` overrides both because pinned shards of concurrent tests starve each other. `wait_ready` never calls `try_wait()`, so a server that dies at boot gives a 30s spin and "did not become ready", naming the wrong cause. `Drop` SIGKILLs where `graceful_kill` exists. Hits every CI run, x3 with `retries`.
Fix: set the two sharding env vars, add `try_wait()`, capture child stdio. A 1-shard server stops covering multi-shard dispatch, which this file covers by accident today.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(_) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count` as segments are dropped
+ /// (`core/partitions/src/iggy_partition.rs::decrement_messages_count`) but never rewinds
+ /// `current_offset` - a fully-retention-purged partition that has produced messages reports
+ /// `messages_count == 0` with `current_offset` still at its high value. Treating that as
+ /// "empty" would report high watermark `0` for a partition that has, in fact, produced past
+ /// offset `0`; a future `ListOffsets` (`#3537`) LATEST built on this would rewind instead of
+ /// pointing at the true next-write position.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ let partition_details = details
+ .partitions
+ .iter()
+ .find(|p| p.id == partition)
+ .ok_or_else(|| BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the wrong
+ // (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ })?;
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
Review Comment:
This `(0,0)` check conflates five states. `responses.rs:1436` `map_or((0,0,0))` returns zeros for a partition the shard hasn't materialized, so one holding 1M messages reports HW 0. Not fixable client-side: `offset_frontier()` (`iggy_partition.rs:1274-1280`) has the right answer but it isn't on the wire. The code matches `iggy_partition.rs:2681-2683`, so it's defensible; the doc at `:250-263` claims a correctness it doesn't have, and #3537 shouldn't build on it as written.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
Review Comment:
`TopicCreateOptions::default()` gives `message_expiry: ServerDefault`, which `segment_cleaner.rs:93,98` treats as never expire. Kafka defaults to 7 days. Nothing is frozen on disk (`max_topic_size: ServerDefault` re-resolves at enforcement), but it surprises anyone repointing a Kafka app.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,204 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::TopicMapping;
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches the Iggy server's own default root user - not a made-up example, the same default
+/// every fresh `iggy-server` and every CLI quick-start in this repo uses.
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+const DEFAULT_IGGY_PASSWORD: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
+ /// surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in `core/configs`, so the
+ /// central provider's own typo-detection doesn't cover this namespace either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root credentials.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_TOPIC_MAP_PATH` is set but the file
+ /// is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD")
+ .unwrap_or_else(|_| DEFAULT_IGGY_PASSWORD.to_string());
+ let stream_env = std::env::var("IGGY_KAFKA_IGGY_STREAM").ok();
+ // Caught here, not left to TopicMapping::from_toml_str's own empty check: that
+ // validation only runs when IGGY_KAFKA_TOPIC_MAP_PATH is set, since the no-file branch
+ // below builds a TopicMapping directly rather than through the validating constructor.
+ // An explicitly-empty (not merely absent) IGGY_KAFKA_IGGY_STREAM would otherwise pass
+ // from_env cleanly and only fail much later, deep in the first ensure_stream_and_topic
+ // call, as an opaque Identifier::named("") error.
+ if let Some(ref stream) = stream_env
+ && stream.trim().is_empty()
+ {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_STREAM must not be empty".to_string(),
+ ));
+ }
+ let topic_map_path = std::env::var("IGGY_KAFKA_TOPIC_MAP_PATH").ok();
+
+ let topic_mapping = match topic_map_path {
+ Some(path) => {
+ if stream_env.is_some() {
+ warn!(
+ "IGGY_KAFKA_IGGY_STREAM is set but ignored: IGGY_KAFKA_TOPIC_MAP_PATH's \
+ own default_stream takes precedence"
+ );
+ }
+ TopicMapping::from_file(Path::new(&path))?
+ }
+ None => TopicMapping {
+ default_stream: stream_env.unwrap_or_else(|| "kafka".to_string()),
+ topics: std::collections::HashMap::new(),
+ },
+ };
+
+ Ok(Self {
+ address,
+ username,
+ password: SecretString::from(password),
+ topic_mapping,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serial_test::serial;
+
+ use super::*;
+
+ fn test_config() -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: "127.0.0.1:8090".to_string(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: std::collections::HashMap::new(),
+ },
+ }
+ }
+
+ #[test]
+ fn debug_output_does_not_expose_password() {
+ // A distinctive value, not the shared fixture's "iggy" - that string also appears as the
+ // username and inside the struct's own name, which would make a substring check here
+ // pass trivially regardless of whether the password field itself is actually redacted.
+ let mut config = test_config();
+ config.password = SecretString::from("correct-horse-battery-staple");
+ let debug_output = format!("{config:?}");
+ assert!(
+ !debug_output.contains("correct-horse-battery-staple"),
+ "Debug output must not expose the plaintext password: {debug_output}"
+ );
+ }
+
+ #[test]
+ #[serial]
+ fn from_env_rejects_missing_topic_map_file() {
+ // Safety: single-threaded within this function; no other test in this crate touches
+ // IGGY_KAFKA_TOPIC_MAP_PATH.
+ unsafe {
Review Comment:
`unsafe { set_var }` races a concurrent `getenv`: `server.rs:891` `init_tracing_is_idempotent` calls `EnvFilter::try_from_default_env()`, has no `#[serial]`, same lib test binary. Real under `cargo test`, invisible under nextest. The three `# Safety` comments state the wrong condition - edition 2024's rule is process-wide.
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
Review Comment:
`PartitionCountMismatch` maps to `INVALID_PARTITIONS (37)`, whose Kafka text is "Number of partitions is below 1". `TOPIC_ALREADY_EXISTS (36)` fits.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
Review Comment:
`resolve` isn't injective: `[topics.orders] stream="kafka", topic="orders_v2"` silently merges Kafka topics `orders` and `orders_v2` into one Iggy topic. That's the main reason anyone writes an override file.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
Review Comment:
No `#[serde(deny_unknown_fields)]`, no `version` key. A singular `[topic.orders]` typo parses fine, gives an empty map, and everything falls back to the default stream. Also `TopicMapping` derives `Default`, giving `default_stream: ""` - exactly what `from_toml_str:68-72` rejects.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967803549
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape, if
+ /// `default_stream` is empty, or if any `[topics.*]` override has an empty `stream`/`topic` -
+ /// in every case, an empty Iggy stream/topic name would otherwise pass config loading
+ /// cleanly and only fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, as
+ /// an opaque `Identifier::named("")` error with no link back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ if mapping.default_stream.trim().is_empty() {
Review Comment:
Trimming at validate-time and storing the raw string creates a name with leading/trailing space that later `.trim()` would silently re-point.
Replaced trim-and-store with reject-on-whitespace, plus a 255-byte cap matching Identifier::named's own limit — shared validate_identifier_name helper used by both topic_map.rs and config.rs (the same bug
existed in IGGY_KAFKA_IGGY_STREAM handling).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3968220924
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
Deferred, will look into when a PR for 3535 is raised..
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001460882
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
+ &self,
+ kafka_topic: &str,
+ partition: u32,
+ ) -> Result<u64, BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = Identifier::named(&stream_name).map_err(BridgeError::Iggy)?;
+ let topic_id = Identifier::named(&topic_name).map_err(BridgeError::Iggy)?;
+ let details = self
+ .client
+ .get_topic(&stream_id, &topic_id)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.clone(),
+ stream_name.clone(),
+ ))
+ })?;
+
+ // `TryFrom<GetTopicResponse> for TopicDetails` (wire_conversions.rs) sorts `partitions` by
+ // `id` on every decode, so a binary search is correct here, not just faster than the
+ // linear scan it replaces - for a 1000-partition topic, the difference is O(log n) vs
+ // O(n) probes on every high_watermark call.
+ let partition_details = match details
+ .partitions
+ .binary_search_by_key(&partition, |p| p.id)
+ {
+ Ok(index) => &details.partitions[index],
+ Err(_) => {
+ return Err(BridgeError::PartitionOutOfRange {
+ // The Kafka-side name a caller (a future ListOffsets handler) actually asked
+ // about, not `topic_name` - a mapping override would otherwise quote the
+ // wrong (Iggy-side) name back at a Kafka client that never heard of it.
+ topic: kafka_topic.to_string(),
+ partition,
+ partitions_count: details.partitions_count,
+ });
+ }
+ };
+
+ Ok(
+ if partition_details.messages_count == 0 && partition_details.current_offset == 0 {
Review Comment:
Acknowledged, no code change - not fixable from this side, (PartitionResponse has no frontier field). Documented explicitly in the doc comment so it's on the record.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001452428
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthorized
+ | IggyError::InvalidCredentials
+ | IggyError::InvalidUsername
+ | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED,
+ IggyError::Disconnected
+ | IggyError::EmptyResponse
+ | IggyError::Unauthenticated
+ | IggyError::StaleClient
+ | IggyError::NotConnected
+ | IggyError::CannotEstablishConnection
+ | IggyError::TcpError
+ | IggyError::TransientNotAccepted => ERROR_NOT_LEADER_OR_FOLLOWER,
+ IggyError::TransientNotCommitted => ERROR_REQUEST_TIMED_OUT,
+ _ => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use iggy::prelude::Identifier;
+
+ #[test]
Review Comment:
**Fixed**. Added every_sent_error_code_matches_kafka_protocols_own_table, iterating every (ours, theirs) pair against kafka_protocol::error:: ResponseError::<Variant>.code() - 8 pairs, covering every constant bridge::error actually emits (the other 4 of the 12 total constants in protocol/api.rs belong to the protocol/stub layer, not this module, so they're correctly out of scope for this particular test).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001624234
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is not a dependency this one wants: heavyweight, and pulling it in for one function would
+/// make every `core/sdk` change re-run this crate's server-spawning tests, per `Cargo.toml`'s own
+/// dependency-edge note). A bare SIGKILL skips `iggy-server`'s shutdown path entirely, which is a
+/// materially different exit than what the binary is actually built to do on `SIGTERM` -
+/// `.kill()` alone bypassed that in every test run before this fix.
+const SIGTERM_TIMEOUT: Duration = Duration::from_secs(5);
+const SIGKILL_POLL_INTERVAL: Duration = Duration::from_millis(50);
+
+fn graceful_kill(child: &mut Child) {
+ let pid = child.id() as libc::pid_t;
+ // Safety: `pid` is this process's own live child, obtained from `Child::id` immediately
+ // above; sending it a signal is exactly what `Child::kill` itself does internally.
+ unsafe {
+ libc::kill(pid, libc::SIGTERM);
+ }
+
+ let deadline = std::time::Instant::now() + SIGTERM_TIMEOUT;
+ while std::time::Instant::now() < deadline {
+ match child.try_wait() {
+ Ok(None) => std::thread::sleep(SIGKILL_POLL_INTERVAL),
+ Ok(Some(_)) | Err(_) => return,
+ }
+ }
+
+ let _ = child.kill();
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ graceful_kill(&mut self.child);
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("second call is a no-op against the now-existing stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("third call is still a no-op");
+
+ // Read back real state, not just three Oks: proves the second and third calls were actually
+ // no-ops against the one topic the first call created, not e.g. three independent topics
+ // that all happen to satisfy Ok(()) individually.
+ let raw = raw_client(&server).await;
+ let topics = raw
+ .get_topics(&Identifier::named("kafka").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(topics.len(), 1, "must be exactly one topic, not three");
+ assert_eq!(topics[0].name, "orders");
+ assert_eq!(topics[0].partitions_count, 3);
+}
+
+/// Regression test for coverage: nothing previously exercised `PartitionCountMismatch` on a real
+/// server - only unit tests constructed the variant directly.
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_rejects_a_second_call_with_a_different_partition_count() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the topic with 3 partitions");
+
+ let err = bridge
+ .ensure_stream_and_topic("orders", 5)
+ .await
+ .expect_err(
+ "a different partition count against an existing topic must not silently succeed",
+ );
+ match err {
+ BridgeError::PartitionCountMismatch {
+ topic,
+ existing,
+ requested,
+ } => {
+ assert_eq!(topic, "orders", "must report the Kafka-side name");
+ assert_eq!(existing, 3);
+ assert_eq!(requested, 5);
+ }
+ other => panic!("expected PartitionCountMismatch, got {other:?}"),
+ }
+}
+
+/// Regression test for coverage: every other test uses an empty `TopicMapping` (`HashMap::new()`),
+/// so the Kafka-name-vs-Iggy-name distinction `ensure_topic`/`high_watermark` deliberately
+/// maintain in their error paths (`kafka_topic`, not the resolved `topic_name`) can never actually
+/// differ and so can never be caught wrong. This test maps a Kafka topic to a differently-named
+/// Iggy stream/topic and checks both the happy path and the error paths report the Kafka-side
+/// name a real caller (a future handler) would recognize.
+#[tokio::test]
+#[serial]
+async fn bridge_operations_report_the_kafka_side_name_through_a_real_topic_mapping_override() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let mut config = server.test_config();
+ config.topic_mapping.topics.insert(
+ "orders".to_string(),
+ TopicOverride {
+ stream: "billing".to_string(),
+ topic: "orders_v2".to_string(),
+ },
+ );
+ let bridge = IggyBridge::connect(config)
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("must create the mapped Iggy stream/topic, not one named after the Kafka topic");
+
+ // The Iggy-side resources are named differently from the Kafka topic - confirms the mapping
+ // actually took effect, not that resolve() was a no-op that happened to pass either way.
+ let raw = raw_client(&server).await;
+ let billing_topics = raw
+ .get_topics(&Identifier::named("billing").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(billing_topics.len(), 1);
+ assert_eq!(billing_topics[0].name, "orders_v2");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("must resolve through the mapping, not fail looking for a stream named 'orders'");
+ assert_eq!(watermark, 0);
+
+ let out_of_range = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(
+ matches!(
+ &out_of_range,
+ BridgeError::PartitionOutOfRange { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {out_of_range:?}"
+ );
+
+ let mismatch = bridge
+ .ensure_stream_and_topic("orders", 2)
+ .await
+ .expect_err("different partition count against the mapped topic must not silently succeed");
+ assert!(
+ matches!(
+ &mismatch,
+ BridgeError::PartitionCountMismatch { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {mismatch:?}"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_is_zero_for_a_fresh_empty_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("fresh topic must report a watermark, not an error");
+ assert_eq!(
+ watermark, 0,
+ "a freshly created, empty partition's high watermark must be 0"
+ );
+}
+
+/// Pins the exact semantics of `Iggy::Partition::current_offset` (offset of the *last written*
+/// message, not Kafka's "next offset to produce") against a real server - a test that only
+/// checked the empty-topic case would pass under either interpretation and hide an off-by-one.
+#[tokio::test]
+#[serial]
+async fn high_watermark_reflects_produced_messages() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before producing");
+
+ let stream_id = Identifier::named("kafka").expect("valid stream name");
+ let topic_id = Identifier::named("orders").expect("valid topic name");
+ let mut messages: Vec<IggyMessage> = (0..3)
+ .map(|i| IggyMessage::from(format!("message-{i}")))
+ .collect();
+ let client = raw_client(&server).await;
+ client
+ .send_messages(
+ &stream_id,
+ &topic_id,
+ &Partitioning::partition_id(0),
+ &mut messages,
+ )
+ .await
+ .expect("send 3 messages");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("topic must report a watermark after producing");
+ assert_eq!(
+ watermark, 3,
+ "high watermark after 3 messages (offsets 0, 1, 2) must be 3, not the last offset (2)"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_rejects_out_of_range_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let err = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(matches!(err, BridgeError::PartitionOutOfRange { .. }));
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_for_a_numeric_topic_name() {
+ // Regression test: Identifier::try_from/FromStr parses an all-digit string as a numeric ID,
+ // not a name - a second call for the same numeric-named topic would look it up by the wrong
+ // resource kind and fail with StreamIdNotFound/TopicIdNotFound despite the topic existing.
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("first call creates the numeric-named stream and topic");
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("second call must still find the numeric-named topic by name, not by ID");
+}
+
+/// Regression test: `ensure_stream` used to hand `ensure_topic` the stream's *numeric* id
+/// (`Identifier::numeric`), and streams are backed by a recycled slab (freed keys are reused by
+/// the next created stream) - a stream deleted and recreated between the two calls would leave
+/// `ensure_topic` writing into whatever stream now holds that recycled numeric key, not the one
+/// `ensure_stream_and_topic`'s caller actually resolved. The fix threads the *named* `Identifier`
+/// through instead. This does not (cannot, from a black-box test) hit the exact `await` window the
+/// bug lived in, but it does prove the name, not a captured numeric id, is what actually governs:
+/// delete the stream, recreate it under the same name, and the very next call must still land the
+/// topic on the live incarnation.
+#[tokio::test]
+#[serial]
+async fn ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("first call creates the default stream and topic");
+
+ let raw = raw_client(&server).await;
+ let stream_name = Identifier::named("kafka").expect("valid stream name");
+ let original = raw
+ .get_stream(&stream_name)
+ .await
+ .expect("get_stream call")
+ .expect("stream exists after ensure_stream_and_topic");
+ raw.delete_stream(&Identifier::numeric(original.id).expect("numeric id"))
+ .await
+ .expect("delete the stream (and its topic with it)");
+ let recreated = raw
+ .create_stream("kafka")
+ .await
+ .expect("recreate a stream under the same name");
+ if recreated.id == original.id {
+ // Not guaranteed by any API contract, but the metadata slab does reuse freed low
+ // indices - confirms this run actually exercised the recycled-key scenario, not just a
+ // coincidentally-fresh one.
+ eprintln!(
+ "recreated stream reused the original numeric id {}",
+ recreated.id
+ );
+ }
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("must create the topic under the live stream, not a stale numeric id");
+
+ let topic = raw
+ .get_topic(
+ &stream_name,
+ &Identifier::named("orders").expect("valid topic name"),
+ )
+ .await
+ .expect("get_topic call")
+ .expect("topic exists under the recreated stream");
+ assert_eq!(topic.partitions_count, 1);
+}
+
+/// Finding: the SDK's connection-string parser splits on `@` then `:`, so a password containing
+/// either character breaks unless credentials are passed as already-separated fields.
+#[tokio::test]
+#[serial]
+async fn connect_succeeds_with_password_containing_special_characters() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+ let password = "p@ss:word";
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.path().display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", password);
+ let mut child = command.spawn().expect("spawn iggy-server");
Review Comment:
**Fixed** - gave TestServer::spawn a spawn_with_password sibling and moved this test onto it, so it gets the same Drop/graceful_kill/ PortGuard protection as everything else instead of a separate, Drop-less spawn.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001656488
##########
gateways/kafka/src/lib.rs:
##########
@@ -17,6 +17,7 @@
//! Kafka wire protocol gateway foundation for Apache Iggy.
+pub mod bridge;
Review Comment:
**Agreed** it's inconsistent, left as-is per "take it or leave it" suggestion - didn't want to make an unrelated API-surface call in this PR given protocol has the same asymmetry. Will do a follow-up that picks one convention crate-wide.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001397302
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
Review Comment:
**Fixed** (documented, not pooled). Went with documenting per your suggested fallback: IggyBridge's own doc comment now states the lockstep-transport ceiling directly (citing tcp_client.rs's own "lockstep" comment), and the README gained a "Concurrency ceiling" section saying the same for operators. Pooling is flagged as a known gap to close before #3535/#3536, not attempted here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001601864
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape (an
+ /// unrecognized field - e.g. a `[topic.x]` typo for `[topics.x]` - is rejected here rather
+ /// than silently parsing to an empty override map), if `default_stream` or any override's
+ /// `stream`/`topic` is empty, has leading/trailing whitespace, or exceeds
+ /// `MAX_IDENTIFIER_LEN`, or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)) - in every validation case, letting it through here would
+ /// otherwise fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, with no link
+ /// back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ validate_identifier_name("topic mapping's default_stream", &mapping.default_stream)?;
+
+ let mut targets = HashSet::with_capacity(mapping.topics.len());
+ for (kafka_topic, over) in &mapping.topics {
+ validate_identifier_name(
+ &format!("topic mapping override for '{kafka_topic}''s stream"),
+ &over.stream,
+ )?;
+ validate_identifier_name(
+ &format!("topic mapping override for '{kafka_topic}''s topic"),
+ &over.topic,
+ )?;
+
+ let target = (over.stream.clone(), over.topic.clone());
Review Comment:
Acknowledged, no code change - this isn't a real cost at config-load scale, left as HashSet<(String, String)> for simplicity.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001595905
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
Review Comment:
Fixed - resolve now returns (&str, &str). Agreed this is the signature Produce will be calling, worth getting right now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001334492
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ IggyError::Unauthorized
+ | IggyError::InvalidCredentials
Review Comment:
**Fixed**. Those three now fall through to ERROR_UNKNOWN_SERVER_ERROR; Unauthorized alone stays on 29. Added invalid_credentials_maps_to_unknown_server_error_not_authorization_failed (+ username/password variants) plus an end-to-end regression test against a real server (connect_with_wrong_password_maps_to_unknown_server_error_not_authorization_failed) asserting the actual wire code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020491462
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,526 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Kafka's own topic-name cap (`Topic.MAX_NAME_LENGTH` in Kafka's own source) - smaller than
+/// [`MAX_IDENTIFIER_LEN`], so a Kafka-side name needs its own limit, not Iggy's.
+const MAX_KAFKA_TOPIC_NAME_LEN: usize = 249;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path. For a Kafka-side topic name (a TOML key, or a `kafka_topic` argument), use
+/// [`validate_kafka_topic_name`] instead - Kafka's own limits and legal characters differ from
+/// Iggy's.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Rejects a Kafka topic name that fails Kafka's own naming rules: empty, leading/trailing
+/// whitespace, over [`MAX_KAFKA_TOPIC_NAME_LEN`] bytes, or containing a byte outside
+/// `[A-Za-z0-9._-]` (Kafka's own `Topic.legalChars`).
+///
+/// Used both for TOML mapping-file keys (`from_toml_str`) and for the `kafka_topic` argument
+/// `IggyBridge::ensure_stream_and_topic`/`high_watermark` take directly - the two paths must agree,
+/// or a name the config file would reject can still reach Iggy unvalidated through the second
+/// path. A whitespace-padded key is the sharpest failure mode this catches: `resolve`'s lookup is
+/// an exact `HashMap::get`, so a padded key parses out of the TOML file cleanly and then matches
+/// nothing at runtime, silently falling through to the default stream instead of erroring - the
+/// one place in this module that would otherwise fail silently instead of loudly.
+///
+/// `field` is `"topic mapping key"` or `"kafka_topic"` in current callers, not a generic template -
+/// kept as a parameter (like [`validate_identifier_name`]) so the message names the actual site.
+pub(crate) fn validate_kafka_topic_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not be empty"),
+ });
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not have leading or trailing whitespace"),
+ });
+ }
+ if value.len() > MAX_KAFKA_TOPIC_NAME_LEN {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!(
+ "{field} is {} bytes, over Kafka's {MAX_KAFKA_TOPIC_NAME_LEN}-byte topic name limit",
+ value.len()
+ ),
+ });
+ }
+ if let Some(illegal) = value
+ .bytes()
+ .find(|b| !(b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')))
+ {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!(
+ "{field} contains {:?}, outside Kafka's legal topic-name characters \
+ (letters, digits, '.', '_', '-')",
+ illegal as char
+ ),
+ });
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// Fields are private and every value is validated (empty/whitespace/length/injectivity - see
+/// [`new`](Self::new)) on the only two ways to build one: [`new`](Self::new) and
+/// [`from_toml_str`](Self::from_toml_str) (which deserializes into a private, unchecked
+/// `RawTopicMapping` first, then calls `new`). Public fields plus `#[derive(Deserialize)]`
+/// directly on this type would let any caller construct or mutate one straight from TOML or a
+/// literal, skipping every check below - which is exactly what happened before this type had a
+/// checked constructor: `bridge::config`'s no-file path built one by hand and needed its own
+/// separate validation call to make up for it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TopicMapping {
+ default_stream: String,
+ topics: HashMap<String, TopicOverride>,
+}
+
+/// Unchecked shadow of [`TopicMapping`], `Deserialize`'s only target - never constructed by hand,
+/// never exposed. `TopicMapping::from_toml_str` is the sole path from TOML to a validated
+/// `TopicMapping`, by deserializing into this first and then calling
+/// [`TopicMapping::new`](TopicMapping::new).
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawTopicMapping {
+ default_stream: String,
+ #[serde(default)]
+ topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Builds a validated `TopicMapping` from already-parsed parts - the checked constructor the
+ /// no-file `IGGY_KAFKA_IGGY_STREAM` path in `bridge::config` uses, and the sole validation
+ /// gate `from_toml_str` also funnels through.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `default_stream` or any override's `stream`/
+ /// `topic` is empty, has leading/trailing whitespace, or exceeds `MAX_IDENTIFIER_LEN`; if any
+ /// override key fails Kafka's own topic-naming rules (see
+ /// `validate_kafka_topic_name`); or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)).
+ pub fn new(
+ default_stream: String,
+ topics: HashMap<String, TopicOverride>,
+ ) -> Result<Self, BridgeError> {
+ validate_identifier_name("topic mapping's default_stream", &default_stream)?;
+
+ let mut targets = HashSet::with_capacity(topics.len());
+ for (kafka_topic, over) in &topics {
+ validate_kafka_topic_name("topic mapping key", kafka_topic)?;
Review Comment:
Fixed. Bad mapping-file keys now return InvalidConfig (-1), not InvalidKafkaTopicName (17) — matches the doc's own promise. │
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5688600481
/ready
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4020267980
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
Review Comment:
Fixed.Traced full mechanism in tcp_client.rs (detached tokio::spawn holds stream mutex, cancel can't abort it).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3977883639
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
+/// seconds rather than hanging.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, or
+ /// authentication is rejected - this is the boundary [`BridgeError::to_kafka_error_code`]
+ /// exists for: a handler calling this must map the error to a wire response, never panic or
+ /// unwrap, since an unreachable Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ client.connect().await.map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Disconnects the underlying Iggy client.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the client reports a disconnect failure.
+ pub async fn close(&self) -> Result<(), BridgeError> {
+ self.client.disconnect().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Looks up (or creates) the stream named `stream_name`.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Identifier::numeric(existing.id).map_err(BridgeError::Iggy);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Identifier::numeric(created.id).map_err(BridgeError::Iggy)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - re-verify by name (the identifier this arm already has,
+ // fixed above) rather than trusting the race outcome alone.
+ let existing = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| IggyError::StreamNameNotFound(stream_name.to_string()))?;
+ Identifier::numeric(existing.id).map_err(BridgeError::Iggy)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ let options = TopicCreateOptions {
Review Comment:
Agreed it surprises anyone expecting Kafka’s 7-day default. `ServerDefault` here means Iggy’s cleaner “never expire”.
Documented in README (Iggy server default, not Kafka retention). Not inventing a 7-day expiry in the bridge this PR — that is a product default, and `max_topic_size: ServerDefault` already re-resolves at enforcement. If we later want Kafka-like retention it should be explicit config, not a silent `TopicCreateOptions` change. Will revisit in future and implement either with a config param or a Product road map decision.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967505414
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_INVALID_PARTITIONS,
Review Comment:
Kafka’s text for 37 is “number of partitions is below 1”, which is not this case.
Will map `PartitionCountMismatch` to `TOPIC_ALREADY_EXISTS` (36) and add `ERROR_TOPIC_ALREADY_EXISTS` in `protocol/api.rs`. Still not a perfect Kafka analogue (the topic exists, but with a *different* count); 36 is the closest code that does not lie about “< 1 partitions”. Readme updated
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3977763618
##########
gateways/kafka/src/main.rs:
##########
@@ -71,13 +76,20 @@ const KNOWN_KAFKA_ENV_VARS: &[&str] = &[
"IGGY_KAFKA_SHUTDOWN_DRAIN_TIMEOUT_SECS",
];
-/// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] - a typo (e.g.
-/// `IGGY_KAFKA_BIN_ADDR`) would otherwise be silently ignored: `core/configs`' central provider
-/// skips the whole `IGGY_KAFKA_` prefix, and this crate's own `env_var()` only ever looks up
-/// exact known names, so nothing reads the misspelled var and nothing warns either.
+/// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] or
+/// [`IggyBridgeConfig::KNOWN_ENV_VARS`] - a typo (e.g. `IGGY_KAFKA_BIN_ADDR`) would otherwise be
+/// silently ignored: `core/configs`' central provider skips the whole `IGGY_KAFKA_` prefix, and
+/// this crate's own `env_var()` only ever looks up exact known names, so nothing reads the
+/// misspelled var and nothing warns either. Checking both lists (not `IggyBridgeConfig`'s
+/// wiring into `main`) is deliberate: a user who exports a bridge var ahead of
+/// `#3535`/`#3536` landing must not see a spurious "unknown env var" rejection for a name this
+/// crate already recognizes.
fn reject_unknown_kafka_env_vars() -> Result<(), String> {
for (key, _) in std::env::vars() {
- if key.starts_with("IGGY_KAFKA_") && !KNOWN_KAFKA_ENV_VARS.contains(&key.as_str()) {
+ if key.starts_with("IGGY_KAFKA_")
+ && !KNOWN_KAFKA_ENV_VARS.contains(&key.as_str())
+ && !IggyBridgeConfig::KNOWN_ENV_VARS.contains(&key.as_str())
Review Comment:
fixed,
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3968189968
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_INVALID_PARTITIONS, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_TOPIC_AUTHORIZATION_FAILED,
+ ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
Review Comment:
Documented, not fixed at the root — can't be, from this crate. BridgeError::Iggy's Display now carries an explicit caution (error.rs:36-42) that a server-round-tripped IggyError may print a defaulted payload
(Identifier::default() = numeric 0, String::default() = ""), traced to IggyError::from_code (vsr.rs) reconstructing data-carrying variants from a bare wire status code with no payload to recover.
Considered and rejected: Didn't do it because the risk is general
to any IggyError that crosses the wire, not just the ones this bridge special-cases today — that would mean auditing every fallible SDK call for whether its error path can carry a defaulted payload. Root fix should be in the SDK in multiple ways.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3968312475
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,435 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping};
+
+/// First port of the local reservation band. `u16` has no room above the highest ephemeral
+/// ceiling in use (macOS: 49152-65535), so "clear of ephemeral" only leaves room below the
+/// lowest floor (Linux default: 32768) - picked here below `core/integration`'s own
+/// `port_reserver.rs` band too (20000 up to that floor), so a `bind(0)` call in an unrelated
+/// process, including that harness's own test servers, is never handed a port this band claims.
+const PORT_LOCK_BAND_START: u16 = 15000;
Review Comment:
Fixed — it was was overclaiming. Replaced the hardcoded 15000..15199 band with port_reserver.rs's own approach: reads /proc/sys/net/ipv4/ip_local_port_range (ephemeral_range(), Linux default 32768-60999 fallback
where there's no /proc, e.g. macOS), then picks a band clear of it — below the floor by preference, above the ceiling when the floor leaves no room, panics loudly if neither side has room (mirrors
port_reserver.rs's own "no degraded mode"). flock is still advisory as you said — the fix isn't making it exclusive, it's making sure the band it locks is actually outside the range an unrelated bind(0) could
land in, on a box tuned 1024 65535 or otherwise.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001345187
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,357 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// No `Default` impl: an empty `default_stream` is not a valid `TopicMapping` -
+/// [`from_toml_str`](Self::from_toml_str) rejects it, and a derived `Default` would silently
+/// produce exactly that.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicMapping {
+ pub default_stream: String,
+ #[serde(default)]
+ pub topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Resolves a Kafka topic name to `(iggy_stream, iggy_topic)`.
+ ///
+ /// Not injective: two distinct Kafka topics can resolve to the same Iggy stream/topic pair,
+ /// merging their messages. `from_toml_str` rejects the checkable cases (two overrides sharing
+ /// a target, or an override's target aliasing the default-path resolution of its own topic
+ /// name) at config load, but the space of *unlisted* Kafka topic names is unbounded, so a
+ /// collision against one that never gets an override entry can't be ruled out ahead of time.
+ #[must_use]
+ pub fn resolve(&self, kafka_topic: &str) -> (String, String) {
+ self.topics.get(kafka_topic).map_or_else(
+ || (self.default_stream.clone(), kafka_topic.to_string()),
+ |over| (over.stream.clone(), over.topic.clone()),
+ )
+ }
+
+ /// Parses a `TopicMapping` from a TOML document.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `raw` is not valid TOML for this shape (an
+ /// unrecognized field - e.g. a `[topic.x]` typo for `[topics.x]` - is rejected here rather
+ /// than silently parsing to an empty override map), if `default_stream` or any override's
+ /// `stream`/`topic` is empty, has leading/trailing whitespace, or exceeds
+ /// `MAX_IDENTIFIER_LEN`, or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)) - in every validation case, letting it through here would
+ /// otherwise fail much later, deep in `IggyBridge::ensure_stream`/`ensure_topic`, with no link
+ /// back to the config entry at fault.
+ pub fn from_toml_str(raw: &str) -> Result<Self, BridgeError> {
+ let mapping: Self = toml::from_str(raw)
+ .map_err(|e| BridgeError::InvalidConfig(format!("invalid topic mapping TOML: {e}")))?;
+ validate_identifier_name("topic mapping's default_stream", &mapping.default_stream)?;
+
+ let mut targets = HashSet::with_capacity(mapping.topics.len());
+ for (kafka_topic, over) in &mapping.topics {
Review Comment:
**Fixed**. TopicMapping::new now calls validate_kafka_topic_name("topic mapping key", kafka_topic) for every override key, using Kafka's own rules (249-byte cap, [A-Za-z0-9._-], no leading/trailing whitespace) - not validate_identifier_name's 255-byte Iggy-side bound, per your note. New test: ensure_stream_and_topic_rejects_a_padded_kafka_topic_name (real-server, plus a unit test on the mapping constructor).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001609397
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,287 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches `DEFAULT_ROOT_USERNAME` (`core/server/src/boot/credentials.rs`) - the root user's
+/// username is always `iggy` regardless of how its password was provisioned, so defaulting this
+/// one field is safe. The password is a different story - see why there is no
+/// `DEFAULT_IGGY_PASSWORD` at [`IggyBridgeConfig::from_env`].
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
Review Comment:
**Fixed** - corrected the comment to describe the actual (and correct) design in main.rs: two independently-checked lists, not one list two places need to stay in sync on.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001494037
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
Review Comment:
**Fixed** - documented the ordering and the no-rollback decision explicitly, including your point about a rollback risking another mapped topic's data via the shared default stream.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001629541
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is not a dependency this one wants: heavyweight, and pulling it in for one function would
+/// make every `core/sdk` change re-run this crate's server-spawning tests, per `Cargo.toml`'s own
Review Comment:
Fixed - trimmed to the still-valid "heavyweight for one function" reasoning and corrected the stale dependency-edge claim,
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001644718
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,79 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up the high watermark for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The connection retries a fixed, bounded number of times (`RECONNECTION_RETRIES`, not the Iggy SDK
+client's own default of unlimited retries, one dial per second, forever), and the whole connect
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so a bridge call
Review Comment:
**Fixed** both the wording and the actual gap it was overstating - REQUEST_TIMEOUT now really does cover every other bridge call (see the fix for your comment on iggy_bridge.rs:151), so the README statement is accurate now rather than aspirational.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001420765
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
Review Comment:
**Acknowledged**, no code change - pre-existing wire-response gap, as you noted. Documented in high_watermarks's doc comment (the (0,0) stats-registry-MISS-vs-genuinely-empty ambiguity, citing partition_reconciler.rs's settle_partition_stats and the server's own PartitionState::store_offset_range_error condition) so it's on record before #3537 inherits it, per your ask. No fix possible from this bridge - the field doesn't exist on the wire.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001424643
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
Review Comment:
**Fixed**. Rewrote both comments (here and the twin in protocol/api.rs) to state TimeoutException extends RetriableException and that a real broker sends 7 for the same unknown-outcome case, rather than claiming it halts retries. Also noted the duplicate-write exposure stays open until #3535 has an idempotent produce path, per your suggestion.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001497847
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
Review Comment:
**Agreed**, went with the comment-only fallback you suggested - no client seam exists for injecting the race, and a real-concurrency test would just be flaky. The arm now has an explicit note recording the gap.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5697970266
Thanks @krishvishal @mmodzelewski @hubcio
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001495606
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
Review Comment:
**Fixed** - both now return i64, matching ListOffsetsResponse.json's int64 field, with the lossy conversion handled inside the bridge.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001457302
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
Review Comment:
**All four addressed.** (1) kafka_topic now validated in both ensure_stream_and_topic and high_watermarks. (2) left partition_count == 0 as documented defense-in-depth, per your own framing. (3) documented once-per-topic calling instead of adding a cache - a cache would break the delete-and-recreate idempotency test, exactly as you'd expect. (4) the -1 sentinel is flagged as a deferred decision in the doc comment rather than resolved here, since nothing calls this with it yet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001450505
##########
gateways/kafka/src/bridge/error.rs:
##########
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::IggyError;
+use thiserror::Error;
+
+use crate::protocol::api::{
+ ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS,
+ ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+};
+
+/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls.
+#[derive(Debug, Error)]
+pub enum BridgeError {
+ /// Bridge config is structurally invalid (empty address, missing credentials, malformed
+ /// topic-mapping TOML) - caught before any connection attempt.
+ #[error("invalid bridge configuration: {0}")]
+ InvalidConfig(String),
+ /// The Iggy client could not connect or authenticate, or a call failed after connecting.
+ /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy.
+ ///
+ /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection
+ /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata
+ /// result), and the SDK reconstructs the full `IggyError` from just that code via
+ /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get
+ /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric
+ /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether
+ /// or not stream 0 is the one that actually failed. Locally-constructed variants (this
+ /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back
+ /// from an actual server rejection are affected.
+ #[error("Iggy client error: {0}")]
+ Iggy(#[from] IggyError),
+ /// `high_watermark` was asked about a partition index the topic doesn't have.
+ #[error(
+ "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)"
+ )]
+ PartitionOutOfRange {
+ topic: String,
+ partition: u32,
+ partitions_count: u32,
+ },
+ /// `ensure_topic` was asked to ensure a topic that already exists with a different partition
+ /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions
+ /// afterward" - silently keeping the old count and returning `Ok(())` would let two
+ /// concurrent callers requesting different counts for the same topic both believe they
+ /// succeeded.
+ #[error(
+ "topic '{topic}' already exists with {existing} partitions, but {requested} were requested"
+ )]
+ PartitionCountMismatch {
+ topic: String,
+ existing: u32,
+ requested: u32,
+ },
+}
+
+impl BridgeError {
+ /// Maps this error to the Kafka protocol error code a handler should answer with.
+ ///
+ /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code
+ /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries
+ /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to
+ /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to
+ /// `UNKNOWN_SERVER_ERROR` (-1).
+ #[must_use]
+ pub const fn to_kafka_error_code(&self) -> i16 {
+ match self {
+ Self::Iggy(err) => iggy_error_to_kafka_code(err),
+ Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+ Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS,
+ // Not a wire-response case in practice: an invalid bridge config is caught at
+ // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this
+ // is reachable only if a future caller starts constructing configs at request time.
+ // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way
+ // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would.
+ Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR,
+ }
+ }
+}
+
+/// Kept private so this association can change without touching call sites.
+///
+/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`,
+/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what
+/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry.
+/// A mapping that only covered some of these would send a permanent-looking Kafka error for a
+/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the
+/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for
+/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing
+/// and its auto-sign-in landing, not for a rejected login.
+///
+/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way.
+/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather
+/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of
+/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk
+/// a duplicate write.
+const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 {
+ match err {
+ IggyError::StreamIdNotFound(_)
Review Comment:
**Fixed**. Added IggyError::PartitionNotFound(_, _, _) to the UNKNOWN_TOPIC_OR_PARTITION group. New test: partition_not_found_maps_to_unknown_topic_or_partition.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001621874
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
+ static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
+ BINARY_PATH.get_or_init(|| {
+ let output = Command::new(env!("CARGO"))
+ .args([
+ "build",
+ "--package",
+ "server",
+ "--bin",
+ "iggy-server",
+ "--message-format=json",
+ ])
+ .output()
+ .expect("run cargo build for iggy-server");
+ assert!(
+ output.status.success(),
+ "cargo build --package server --bin iggy-server failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .find_map(|message| {
+ if message.get("reason")? == "compiler-artifact"
+ && message.get("target")?.get("name")? == "iggy-server"
+ {
+ message.get("executable")?.as_str().map(PathBuf::from)
+ } else {
+ None
+ }
+ })
+ .expect("cargo build --message-format=json reported no iggy-server executable")
+ })
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with an isolated temp data dir and a locked TCP port, then blocks
+ /// until a bridge connection succeeds or the startup budget is exhausted.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", "iggy");
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: HashMap::new(),
+ },
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is not a dependency this one wants: heavyweight, and pulling it in for one function would
+/// make every `core/sdk` change re-run this crate's server-spawning tests, per `Cargo.toml`'s own
+/// dependency-edge note). A bare SIGKILL skips `iggy-server`'s shutdown path entirely, which is a
+/// materially different exit than what the binary is actually built to do on `SIGTERM` -
+/// `.kill()` alone bypassed that in every test run before this fix.
+const SIGTERM_TIMEOUT: Duration = Duration::from_secs(5);
+const SIGKILL_POLL_INTERVAL: Duration = Duration::from_millis(50);
+
+fn graceful_kill(child: &mut Child) {
+ let pid = child.id() as libc::pid_t;
Review Comment:
**Fixed** the guard - early return on try_wait() already showing Some(_), same protection std::Child::kill has internally. On the std claim: checked the actual libstd source (sys/process/unix/unix.rs) rather than going on assumption - Process::kill does check a cached exit status and no-ops if already reaped, so the comment's claim holds. Let me know if you read that differently.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001423321
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,829 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Builds `iggy-server` (idempotent - a no-op rebuild once already current) and returns its path.
+///
+/// Not `assert_cmd::Command::cargo_bin`: that only resolves `CARGO_BIN_EXE_*` for binaries owned
+/// by *this* package (confirmed - it fails here with "available binary names are
+/// iggy-gateway-kafka"). `iggy-server` belongs to the separate `server` crate, and neither this
+/// crate nor `core/integration` (same `Command::cargo_bin` pattern) declares that crate as a
+/// dependency just to make its binary buildable. Driving `cargo build` directly sidesteps that
+/// entirely - no Cargo.toml dependency edge needed on a crate this one otherwise never touches.
+///
+/// Reads the artifact path from `--message-format=json` rather than guessing
+/// `target/debug/iggy-server`: a guessed path breaks under `CARGO_TARGET_DIR` (this workspace's
+/// own coverage CI sets it), `--release`, or a `--target` triple subdirectory, none of which
+/// `cargo build`'s own JSON output leaves to guesswork.
+fn iggy_server_binary() -> &'static PathBuf {
Review Comment:
**Fixed**. Replaced the self-building iggy_server_binary() with assert_cmd::cargo::cargo_bin("iggy-server"), matching core/integration's own harness::handle::server::start. Rewrote the doc comment to correct the reasoning you identified as wrong (cargo_bin falls back to legacy_cargo_bin, which derives the path from current_exe(), not from CARGO_BIN_EXE_* package ownership). docs/TEST_SUITE.md now states building iggy-server first is a prerequisite. Verified: full suite dropped from ~143s to ~25s.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001368547
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ tokio::time::timeout(CONNECT_TIMEOUT, client.connect())
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown).
+ pub async fn close(self) -> Result<(), BridgeError> {
+ self.client.shutdown().await.map_err(BridgeError::Iggy)
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] for connectivity/auth/invalid-name failures. Returns
+ /// [`BridgeError::PartitionCountMismatch`] if the topic already exists with a different
+ /// partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(&stream_name).await?;
+ self.ensure_topic(&stream_id, &topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if let Some(_existing) = self
+ .client
+ .get_stream(&identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match self.client.create_stream(stream_name).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(IggyError::StreamNameAlreadyExists(_)) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - see [`Self::ensure_stream`]'s doc
+ /// comment; the same numeric-name ambiguity applies to topic names.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match self
+ .client
+ .create_topic(stream_id, topic_name, &options)
+ .await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(IggyError::TopicNameAlreadyExists(_, _)) => {
+ // Lost a create race - re-verify by name rather than trusting the race outcome
+ // alone, the same way ensure_stream's arm does. The winner of the race may have
+ // created it with a different partition count than this call requested, so this
+ // needs the same mismatch check the existing-topic branch above makes - skipping
+ // it here would let two concurrent ensure_topic(N) / ensure_topic(M) calls for
+ // the same topic both return Ok(()).
+ let existing = self
+ .client
+ .get_topic(stream_id, &identifier)
+ .await
+ .map_err(BridgeError::Iggy)?
+ .ok_or_else(|| {
+ IggyError::TopicNameNotFound(topic_name.to_string(), stream_id.to_string())
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(BridgeError::Iggy(err)),
+ }
+ }
+
+ /// Returns the high watermark (offset the next produced message would receive) for one
+ /// partition of the Iggy topic `kafka_topic` maps to.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler ) only ever has the Kafka-side
+ /// name, and a topic with a mapping override would silently query the wrong Iggy resource
+ /// if this took Iggy-space names directly instead.
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the mapped stream/topic doesn't exist. Returns
+ /// [`BridgeError::PartitionOutOfRange`] if `partition` is beyond the topic's partition count.
+ pub async fn high_watermark(
Review Comment:
**Fixed**. Added high_watermarks(kafka_topic, partitions: &[u32]) - one get_topic call regardless of partition count, using binary_search_by_key per requested partition. high_watermark now delegates to it for a single partition. New test: high_watermarks_reports_every_requested_partition_from_one_round_trip (3-partition topic, distinct counts per partition, one call, order preserved).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001631127
##########
.config/nextest.toml:
##########
@@ -39,6 +39,23 @@ max-threads = 1
filter = 'package(integration) and test(/connectors::elasticsearch::/)'
test-group = "elasticsearch"
+# Each test in this binary spawns its own real iggy-server subprocess (isolated data dir, port
+# from PortGuard's own flock, so no two ever share a port). #[serial] on them is a dead letter
+# under nextest - nextest runs every test as its own process, and #[serial]'s mutex only excludes
+# within one process (nextest does not support #[serial] macro, same gap the workaround above
+# documents). Without this override, nextest's default scheduler runs several of these processes
+# at once, and every one of them inherits this workspace's cpu_allocation = "numa:auto" /
Review Comment:
**Fixed** - comment now justifies max-threads = 1 by the numa:auto contention alone, dropped the stale pin-cores reasoning. Kept the override itself,
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4001634571
##########
gateways/kafka/Cargo.toml:
##########
@@ -51,11 +54,15 @@ tokio = { workspace = true, features = [
"signal",
] }
tokio-util = { workspace = true, features = ["rt"] }
+toml = { workspace = true }
tracing = { workspace = true }
tracing-appender = { workspace = true }
tracing-subscriber = { workspace = true }
[dev-dependencies]
Review Comment:
**Agreed**, and agreed your own conclusion is right that this needs a cargo-rail-side fix, not something in this Cargo.toml. Left as a follow-up rather than guessing at the detection-side change in this PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "krishvishal (via GitHub)" <gi...@apache.org>.
krishvishal commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r4014632095
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
Review Comment:
warning: `REQUEST_TIMEOUT` is 15s and the SDK's own reply deadline is 30s (`core/sdk/src/tcp/tcp_client.rs:65`, applied as the read deadline at `:1271`). So this fires first on every slow reply rather than backstopping the SDK.
The part that bites is what it cancels. `send_raw_vsr_attempt` takes the connection's stream mutex at `tcp_client.rs:1420-1421` inside a `tokio::spawn`, and the handle is joined at `:1556`. When this timer fires the outer future drops, the `JoinHandle` drops with it, and the task detaches still holding that lock. With one `IggyClient` for the gateway that lock is the only path to Iggy, so the next bridge call queues behind an abandoned request until the SDK's own 30s runs out.
Raising the constant past 30s stops the cancellation, but a reconnect replay (`tcp_client.rs:279,308`) starts a fresh 30s budget, so any fixed number can still land mid-attempt. The clean version is to not cancel a post-connect call at all and let the SDK's read deadline do the bounding.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
+
+/// Wraps a single Iggy client call in [`REQUEST_TIMEOUT`]. See that constant's doc for why every
+/// bridge method needs this, not just [`IggyBridge::connect`].
+async fn with_request_timeout<T>(
+ op: impl Future<Output = Result<T, IggyError>>,
+) -> Result<T, BridgeError> {
+ tokio::time::timeout(REQUEST_TIMEOUT, op)
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
Review Comment:
warning: an elapsed deadline becomes `CannotEstablishConnection`, which `:146,148` routes to `ERROR_NOT_LEADER_OR_FOLLOWER` (6). Two things wrong with that.
The outcome is not a known non-delivery. The SDK writes, flushes and reads inside a detached `tokio::spawn` (`core/sdk/src/tcp/tcp_client.rs:1420`), so by the time this fires the bytes are most likely already on the socket. The doc at `:115-118` in this same file is the rule that an unknown-outcome failure must not take a code from the known-safe-to-retry set, which is why `TransientNotCommitted` goes to `ERROR_REQUEST_TIMED_OUT` at `:149`. The timeout path is the same shape and takes the code that rule excludes.
Code 6 is also an `InvalidMetadataException`, so a Kafka client refreshes metadata against a single-broker gateway and learns nothing from the trip.
A `BridgeError::Timeout` variant plus one arm in `to_kafka_error_code` covers it. No `IggyError` change and no wire numbering involved. Worth settling before #3535, since Produce will go through this same helper.
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,345 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches `DEFAULT_ROOT_USERNAME` (`core/server/src/boot/credentials.rs`) - the root user's
+/// username is always `iggy` regardless of how its password was provisioned, so defaulting this
+/// one field is safe. The password is a different story - see why there is no
+/// `DEFAULT_IGGY_PASSWORD` at [`IggyBridgeConfig::from_env`].
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. `main.rs`'s
+ /// `reject_unknown_kafka_env_vars` checks this list *and* its own separate
+ /// `KNOWN_KAFKA_ENV_VARS`, not one merged copy - a var added only here is already
+ /// recognized there with no corresponding edit needed, and vice versa. A var this module
+ /// reads still has to be listed *somewhere* the guard checks, or a typo silently no-ops
+ /// instead of surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in
+ /// `core/configs`, so the central provider's own typo-detection doesn't cover this namespace
+ /// either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root username.
+ ///
+ /// `IGGY_KAFKA_IGGY_PASSWORD` has no default and must be set explicitly. `iggy-server` only
+ /// provisions the well-known `iggy`/`iggy` root credentials when started with
+ /// `--with-default-root-credentials` (`args.rs`, itself documented "INSECURE - FOR DEVELOPMENT
+ /// ONLY!"); without that flag it generates a random password (`boot/credentials.rs`) that no
+ /// constant here could ever guess. Defaulting the password to `"iggy"` would make this bridge
+ /// silently authenticate as root, with the credential in no config file and no log, on any
+ /// server that does happen to run dev-flagged - the failure mode of getting it wrong is a
+ /// loud, immediate auth rejection instead.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_IGGY_PASSWORD` is unset or empty, if
+ /// `IGGY_KAFKA_IGGY_USERNAME` is set but empty, or if `IGGY_KAFKA_TOPIC_MAP_PATH` is set but
+ /// the file is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ // set-but-empty (`VAR=""`) is `Ok("")` from `env::var`, not `Err` - distinct from unset,
+ // and unchecked here would otherwise pass both cleanly through to a login attempt neither
+ // could ever satisfy.
+ if username.is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_USERNAME must not be empty".to_string(),
+ ));
+ }
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD").map_err(|_| {
+ BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_PASSWORD must be set - iggy-server generates a random root \
+ password unless started with --with-default-root-credentials, so there is no \
+ safe default to fall back to"
+ .to_string(),
+ )
+ })?;
+ if password.is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_PASSWORD must not be empty".to_string(),
+ ));
+ }
+ let stream_env = std::env::var("IGGY_KAFKA_IGGY_STREAM").ok();
+ // TopicMapping::new (below, on the no-file branch) validates default_stream too now, so
+ // removing this check wouldn't let an invalid value through uncaught - but its own message
+ // would say "topic mapping's default_stream", not IGGY_KAFKA_IGGY_STREAM, leaving whoever
+ // reads the error to work out which env var that phrase actually refers to. Checked here
+ // first so the message names the var an operator can actually go fix.
+ if let Some(ref stream) = stream_env {
Review Comment:
warning: this runs before the map-file branch at `:123`, so an empty or whitespace-padded `IGGY_KAFKA_IGGY_STREAM` hard-fails startup even when `IGGY_KAFKA_TOPIC_MAP_PATH` is set. `README.md:118-120` and the `warn!` at `:126` both tell the operator the var is ignored entirely in that case, so the failure contradicts the message it ships with.
Moving the check into the `None` arm fixes it and removes the duplicate, since `TopicMapping::new` at `topic_map.rs:178` already validates `default_stream` on that branch. That also retires the comment above, which exists only to explain the overlap.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
+
+/// Wraps a single Iggy client call in [`REQUEST_TIMEOUT`]. See that constant's doc for why every
+/// bridge method needs this, not just [`IggyBridge::connect`].
+async fn with_request_timeout<T>(
+ op: impl Future<Output = Result<T, IggyError>>,
+) -> Result<T, BridgeError> {
+ tokio::time::timeout(REQUEST_TIMEOUT, op)
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)
+}
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+///
+/// One `IggyClient`, shared across every Kafka connection this gateway serves - and the SDK's TCP
+/// transport is lockstep, one request in flight at a time (`tcp_client.rs`: "the connection is
+/// lockstep", its stream mutex held across write, flush, and read). Every concurrent Kafka
+/// connection ends up serialized behind whichever single Iggy request is in flight; the Kafka
+/// side's own connection limit does nothing to relieve this. No pooling exists yet - `close`
+/// already takes `self` by value, which anticipates an eventual `Arc`-shared bridge, but nothing
+/// wires that up today. Documented here and in the README rather than silently discovered under
+/// load once `#3535`/`#3536` land.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ with_request_timeout(client.connect()).await?;
+ info!("Iggy bridge connected to {}", config.address);
+
+ Ok(Self { client, config })
+ }
+
+ /// Tears down the underlying Iggy client, including its background heartbeat task.
+ ///
+ /// Not `IggyClient::disconnect`: that only tears down the transport
+ /// (`TcpClient::disconnect_transport`) and never touches `heartbeat_handle` - only
+ /// `IggyClient`'s own `Drop` aborts that task (`client.rs`). A `disconnect`ed-but-not-dropped
+ /// bridge would keep heartbeating on a schedule, hit `NotConnected` (itself in the SDK's
+ /// retriable set), and reconnect plus re-authenticate using the credentials `connect`
+ /// configured, so the "closed" client silently comes back. `shutdown` sets
+ /// `ClientState::Shutdown`, which the heartbeat loop's next `ping` observes as
+ /// `IggyError::ClientShutdown` and self-terminates on, and which `sign_in_credentials` never
+ /// dials past.
+ ///
+ /// Takes `self` by value: `shutdown` is terminal (no reconnect is coming back from it), so
+ /// nothing legitimate is left to call on this bridge afterward. This does mean a bridge shared
+ /// via `Arc` cannot call this directly (`Arc::try_unwrap` first) - not a concern before
+ /// `#3535`/`#3536` wire an owning caller in.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::Iggy`] if the underlying client reports a shutdown failure (e.g. the
+ /// socket was already in a state that rejects a clean shutdown), or if it takes longer than
+ /// `REQUEST_TIMEOUT`.
+ pub async fn close(self) -> Result<(), BridgeError> {
+ with_request_timeout(self.client.shutdown()).await
+ }
+
+ /// Ensures the Iggy stream and topic backing `kafka_topic` exist, creating either or both if
+ /// missing. Resolves `kafka_topic` through the configured [`TopicMapping`](crate::bridge::topic_map::TopicMapping).
+ ///
+ /// Idempotent when repeated with the *same* `partition_count`: a `get` before each `create`
+ /// means calling this twice for the same topic is a no-op the second time, and a
+ /// `NameAlreadyExists` race from a concurrent caller creating the same stream/topic between
+ /// this call's `get` and `create` is treated as success, not an error - the desired end state
+ /// (it exists) is what idempotency actually promises, not that this call was the one that
+ /// created it. A *different* `partition_count` against an already-existing topic is not
+ /// idempotent - see [`BridgeError::PartitionCountMismatch`].
+ ///
+ /// Ensures the stream before the topic, so a topic-creation failure (a different
+ /// `partition_count`, a transient error) can leave a stream that now exists with no topic in
+ /// it yet - a retry heals this (idempotent on the stream half too), and no rollback is
+ /// attempted: `TopicMapping::resolve` sends every *unmapped* Kafka topic to the same
+ /// `default_stream`, so deleting a stream on a topic-creation failure risks deleting another
+ /// topic's data that happens to share it, and this call has no way to tell whether it was the
+ /// one that created the stream in the first place.
+ ///
+ /// `partition_count` is `u32`, so it cannot carry Kafka's own `CreateTopics` sentinel
+ /// (`num_partitions == -1`, KIP-464 "use the broker default" - `protocol/responses.rs`
+ /// already accepts that sentinel at the wire-validation layer). Resolving *what* the broker
+ /// default should be for this bridge is a decision for whichever of `#3535`/`#3536` first
+ /// calls this with a real Kafka request in hand, not one to invent here ahead of that need.
+ ///
+ /// No caching: every call pays a `get_stream` and a `get_topic` (two round trips once both
+ /// already exist), even for a topic this same bridge already confirmed a moment ago. A cache
+ /// keyed on `kafka_topic` would remove that cost, but would also have to answer "how does a
+ /// cache entry ever get invalidated" - the topic being deleted and recreated with a different
+ /// partition count out from under a stale cache entry is exactly
+ /// `ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate`'s own
+ /// scenario, and a naive cache breaks that guarantee to save two round trips. Whatever wires
+ /// this into `#3535`/`#3536` should call it once per topic and remember that it did, rather
+ /// than once per Produce/Fetch - the cost belongs at the call site's discretion, not hidden
+ /// (and potentially made wrong) inside this method.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidKafkaTopicName`] if `kafka_topic` fails Kafka's own
+ /// topic-naming rules. Returns [`BridgeError::Iggy`] for connectivity/auth failures, or if a
+ /// call takes longer than `REQUEST_TIMEOUT`. Returns [`BridgeError::PartitionCountMismatch`]
+ /// if the topic already exists with a different partition count than `partition_count`.
+ pub async fn ensure_stream_and_topic(
+ &self,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ validate_kafka_topic_name("kafka_topic", kafka_topic)?;
+ let (stream_name, topic_name) = self.config.topic_mapping.resolve(kafka_topic);
+ let stream_id = self.ensure_stream(stream_name).await?;
+ self.ensure_topic(&stream_id, topic_name, kafka_topic, partition_count)
+ .await?;
+ Ok(())
+ }
+
+ /// Ensures the stream named `stream_name` exists, creating it if missing.
+ ///
+ /// `Identifier::named` - never `Identifier::try_from`/`FromStr` - because the latter parses
+ /// an all-digit string as a numeric Iggy ID rather than a name. A stream or topic named e.g.
+ /// `"42"` would otherwise resolve against the wrong resource on every call after the first:
+ /// the first `ensure_stream_and_topic("42", ...)` creates a stream *named* `"42"`, but a
+ /// second call would look it up *by ID* `42` instead, almost certainly finding nothing and
+ /// breaking the "idempotent on repeated calls" guarantee.
+ ///
+ /// Returns the same *named* `Identifier` it was given, not the numeric id the SDK hands back
+ /// from `get`/`create` - streams are backed by a recycled slab (`core/metadata`'s
+ /// `stm/stream.rs`: freed keys are reused by the next created stream), so a numeric id
+ /// captured here could point at a *different* stream by the time `ensure_topic` uses it, if
+ /// this stream is deleted and recreated in between. The name has no such window.
+ async fn ensure_stream(&self, stream_name: &str) -> Result<Identifier, BridgeError> {
+ let identifier = Identifier::named(stream_name).map_err(BridgeError::Iggy)?;
+ if with_request_timeout(self.client.get_stream(&identifier))
+ .await?
+ .is_some()
+ {
+ debug!("Iggy stream '{stream_name}' already exists");
+ return Ok(identifier);
+ }
+
+ match with_request_timeout(self.client.create_stream(stream_name)).await {
+ Ok(_created) => {
+ info!("created Iggy stream '{stream_name}'");
+ Ok(identifier)
+ }
+ Err(BridgeError::Iggy(IggyError::StreamNameAlreadyExists(_))) => {
+ // Lost a create race - the name now exists regardless of who won it.
+ Ok(identifier)
+ }
+ Err(err) => Err(err),
+ }
+ }
+
+ /// Looks up (or creates) the topic named `topic_name` under `stream_id`.
+ ///
+ /// `Identifier::named`, not `Identifier::try_from` - the same numeric-name ambiguity
+ /// [`Self::ensure_stream`]'s doc comment describes for stream names applies to topic names.
+ ///
+ /// `partition_count == 0` is accepted here as defense in depth, not the primary guard: the
+ /// server allows it by design (`rewrite.rs`), and the `CreateTopics` stub already rejects it
+ /// at the wire level (`protocol/responses.rs`) before any bridge call would be reachable.
+ async fn ensure_topic(
+ &self,
+ stream_id: &Identifier,
+ topic_name: &str,
+ kafka_topic: &str,
+ partition_count: u32,
+ ) -> Result<(), BridgeError> {
+ let identifier = Identifier::named(topic_name).map_err(BridgeError::Iggy)?;
+ if let Some(existing) =
+ with_request_timeout(self.client.get_topic(stream_id, &identifier)).await?
+ {
+ debug!("Iggy topic '{topic_name}' already exists");
+ // ensure_topic's contract is "the topic has partition_count partitions afterward" -
+ // a mismatch here means that's false. Returning Ok(()) anyway (even with a warn!)
+ // would let two concurrent callers requesting different counts for the same topic
+ // both believe they succeeded; growing partitions on the caller's behalf is also a
+ // bigger decision (CreatePartitions has its own semantics) than this method should
+ // make silently. Erring is the only response that keeps the postcondition honest.
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ // The Kafka-side name a caller actually asked about, not `topic_name` - see
+ // the identical note on `PartitionOutOfRange` in `high_watermark`.
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ return Ok(());
+ }
+
+ // message_expiry left at TopicCreateOptions::default() (None -> ServerDefault) means
+ // never-expire (segment_cleaner.rs treats ServerDefault the same as NeverExpire), not
+ // Kafka's own 7-day default - deliberate for now (imposing a retention policy is a product
+ // decision this bridge shouldn't make unasked), but a real surprise for anyone repointing
+ // a Kafka app that assumes bounded retention. Flagged in the README; revisit once there's
+ // a way to configure it (env var, topic-mapping field) rather than hardcoding a number.
+ let options = TopicCreateOptions {
+ partitions_count: Some(partition_count),
+ ..TopicCreateOptions::default()
+ };
+ match with_request_timeout(self.client.create_topic(stream_id, topic_name, &options)).await
+ {
+ Ok(created) => {
+ info!("created Iggy topic '{topic_name}' with {partition_count} partitions");
+ // Cheap: TopicDetails is already in hand, no extra round trip. `partitions_count`
+ // is a hard argument to create_topic (Some(partition_count), never None), so the
+ // server has no "resolve at admission" substitution to fall back on here - but
+ // checking anyway, the same way the other two branches check their own
+ // postcondition, means a future server-side clamp/cap fails loudly here instead
+ // of this method silently reporting success under a broken contract.
+ if created.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: created.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ // Lost a create race - re-verify by name rather than trusting the race outcome alone.
+ // The winner may have created it with a different partition count than this call
+ // requested, so this needs the same mismatch check the existing-topic branch above
+ // makes - skipping it here would let two concurrent ensure_topic(N) / ensure_topic(M)
+ // calls for the same topic both return Ok(()).
+ //
+ // Untested: reaching this arm needs a real concurrent second caller mid-race, and
+ // `IggyBridge` holds a concrete `IggyClient` with no seam for a fake that returns
+ // `TopicNameAlreadyExists` on demand. A test that spins up two real concurrent callers
+ // would hit it only sometimes - flaky, and passing wouldn't prove this arm ran. Left
+ // as a known gap until something introduces a client seam.
+ Err(BridgeError::Iggy(IggyError::TopicNameAlreadyExists(_, _))) => {
+ let existing = with_request_timeout(self.client.get_topic(stream_id, &identifier))
+ .await?
+ .ok_or_else(|| {
+ BridgeError::Iggy(IggyError::TopicNameNotFound(
+ topic_name.to_string(),
+ stream_id.to_string(),
+ ))
+ })?;
+ if existing.partitions_count != partition_count {
+ return Err(BridgeError::PartitionCountMismatch {
+ topic: kafka_topic.to_string(),
+ existing: existing.partitions_count,
+ requested: partition_count,
+ });
+ }
+ Ok(())
+ }
+ Err(err) => Err(err),
+ }
+ }
+
+ /// Returns the high watermark (one past the highest *committed* offset - see
+ /// `Partition::offset_frontier`'s own definition) for every partition in `partitions` of the
+ /// Iggy topic `kafka_topic` maps to, in one round trip.
+ ///
+ /// Takes `kafka_topic`, not raw Iggy stream/topic names, and resolves it through the same
+ /// [`TopicMapping`](crate::bridge::topic_map::TopicMapping) `ensure_stream_and_topic`
+ /// uses - a caller (a future `ListOffsets` handler) only ever has the Kafka-side name, and a
+ /// topic with a mapping override would silently query the wrong Iggy resource if this took
+ /// Iggy-space names directly instead.
+ ///
+ /// One call to `get_topic`, not one per partition: a single Kafka `ListOffsets` request asks
+ /// about many partitions of one topic at once (`ListOffsetsRequest.json`'s
+ /// `Topics[] -> Partitions[]`), and `get_topic`'s decode already rebuilds and sorts the whole
+ /// partition vector regardless of how many of them the caller wants
+ /// (`wire_conversions.rs`) - a naive one-call-per-partition wrapper around a
+ /// single-partition method would turn one Kafka request into N round trips and N times the
+ /// decode work. Returns results in the same order as `partitions`.
+ ///
+ /// `i64`, not `u64`: the `ListOffsets` response field this exists to fill is `int64`
+ /// (`ListOffsetsResponse.json`), so a future handler needs no cast at the wire boundary - the
+ /// lossy conversion happens once, here (`Partition::current_offset` is `u64`; converted via
+ /// `i64::try_from`, saturating to `i64::MAX` on the practically-unreachable overflow case
+ /// rather than panicking or wrapping).
+ ///
+ /// `Partition::current_offset` is the offset of the *last written* message, not "next offset
+ /// to produce" - confirmed against a live server (3 produced messages read back
+ /// `current_offset == 2`). An empty partition has no last-written offset at all, so this
+ /// needs a dedicated empty case rather than inferring it from `current_offset == 0` (also a
+ /// fresh partition's default value, indistinguishable from "one message at offset 0").
+ ///
+ /// That empty case is `messages_count == 0 && current_offset == 0`, not `messages_count == 0`
+ /// alone: retention cleanup decrements `messages_count`
+ /// (`iggy_partition.rs::decrement_messages_count`) without rewinding `current_offset`, so a
+ /// fully-purged but previously-produced-to partition would otherwise read as empty. This is
+ /// still not exact: a partition whose *only* message, at offset 0, gets trimmed by the same
+ /// retention pass reports `(messages_count, current_offset) == (0, 0)` too, so its watermark
+ /// would read `1` then drop back to `0` - a real Kafka watermark never moves backward. Narrow
+ /// (needs retention to fully empty a partition that only ever held one message) and not
+ /// fixable client-side (`PartitionResponse` carries no frontier field to disambiguate it), but
+ /// worth having on the record rather than only implicitly true of the check below.
+ ///
+ /// Not the same value as `Partition::mint_frontier` (the offset the *next* mint will take):
+ /// after a crash-recovery reservation, the append point can sit above the committed frontier
+ /// by the reservation's lease block, and neither value is on the wire to tell them apart. This
+ /// is still correct for `ListOffsets` LATEST (defined in terms of the committed offset), but a
+ /// future Produce handler must not use it to predict a base offset for a write in flight.
+ ///
+ /// Known remaining gap, not fixable client-side: `(0, 0)` is also what a stats-registry MISS
+ /// reports (`responses.rs`'s `PartitionResponse` builder), indistinguishable on the wire from
+ /// a genuinely empty partition. Narrow and self-healing - `partition_reconciler.rs`'s
+ /// `settle_partition_stats` opens this only on the teardown-for-rebuild path, closing once the
+ /// rebuild completes; deletes never open it. The real answer (`Partition::offset_frontier`)
+ /// stays server-side and isn't in this response. The check matches the server's own
+ /// `PartitionState::store_offset_range_error` condition, so it's not an invented heuristic - a
+ /// future `ListOffsets` (`#3537`) built on this inherits the same blind spot.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidKafkaTopicName`] if `kafka_topic` fails Kafka's own
+ /// topic-naming rules. Returns [`BridgeError::Iggy`] if the mapped stream doesn't exist (see
+ /// the note above on which resource is actually missing), or if the call takes longer than
+ /// `REQUEST_TIMEOUT`. Returns [`BridgeError::PartitionOutOfRange`] if any requested
+ /// partition is beyond the topic's partition count.
+ pub async fn high_watermarks(
+ &self,
+ kafka_topic: &str,
+ partitions: &[u32],
+ ) -> Result<Vec<(u32, i64)>, BridgeError> {
Review Comment:
warning: one `Result` for the whole batch. `ListOffsetsPartitionResponse` carries an error code per partition (`gateways/kafka/src/protocol/responses.rs:233`), so the first out-of-range index raised at `:454` throws away every watermark the call already resolved.
`Vec<(u32, Result<i64, BridgeError>)>` keeps the good ones and lets #3537 fill each partition's own `error_code` without falling back to one call per partition. This is the cheap moment for that change: after the handler lands it is a signature change plus a caller rewrite.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Locates the already-built `iggy-server` binary. Does not build it - see this crate's
+/// `docs/TEST_SUITE.md` for the prerequisite, the same one `core/integration`'s own
+/// server-spawning tests already carry.
+///
+/// `assert_cmd::cargo::cargo_bin`, matching `core/integration`'s own
+/// `harness::handle::server::start` - not a from-scratch `cargo build` invocation. An earlier
+/// version of this function drove `cargo build --package server --bin iggy-server` directly,
+/// reasoning that `Command::cargo_bin` "only resolves `CARGO_BIN_EXE_*` for binaries owned by
+/// *this* package" - true of the `CARGO_BIN_EXE_*` env-var lookup alone, but `cargo_bin` falls
+/// back to `legacy_cargo_bin` when that's unset, which derives the target directory from
+/// `env::current_exe()` (this test binary's own path) and looks for a same-named file there -
+/// correct under `CARGO_TARGET_DIR`, `--release`, or a `--target` triple subdirectory precisely
+/// because it reads back from where cargo actually placed *this* binary, not a guessed path. That
+/// version also re-ran a `cargo build` from every one of this file's server-spawning tests
+/// (nextest runs each as its own process, so the `OnceLock` memoized nothing across them),
+/// serialized by `.config/nextest.toml`'s `kafka_bridge` test-group but still real, avoidable
+/// per-test overhead this version has none of.
+fn iggy_server_binary() -> PathBuf {
+ assert_cmd::cargo::cargo_bin("iggy-server")
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ password: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with the default `iggy`/`iggy` root credentials. See
+ /// [`Self::spawn_with_password`] for the general form.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ Self::spawn_with_password(data_dir, "iggy").await
+ }
+
+ /// Spawns `iggy-server` with an isolated temp data dir, a locked TCP port, and the given root
+ /// password, then blocks until its listener is ready or the startup budget is exhausted.
+ ///
+ /// A dedicated password parameter (not just the `spawn()` default everywhere) lets a
+ /// password-shaped regression test (special characters, say) reuse this harness's
+ /// `PortGuard`/graceful-`Drop`/`wait_ready` machinery instead of hand-rolling a second,
+ /// `Drop`-less spawn: a `Drop`-less copy has no guard to run `graceful_kill` on a panic before
+ /// its assertions, orphaning a process that still holds its `PortGuard` slot, which then
+ /// fails the next test that draws that slot to bind.
+ async fn spawn_with_password(data_dir: &std::path::Path, password: &str) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
Review Comment:
warning: this takes the `pin_cores` half of `core/integration/src/harness/handle/server.rs:297-313` but not the `IGGY_SHARDING_CPU_ALLOCATION` half. `core/server/config.toml:712` defaults to `numa:auto`, so every server spawned here still sizes its shard pool to the whole machine, alongside unrelated packages' tests in the same nextest run.
The integration harness caps each spawned server at a small core range, and that cap is what lets its own tests run in parallel. Setting it here is what would let the `kafka_bridge` group run wider than one thread.
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::future::Future;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::validate_kafka_topic_name;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent.
+///
+/// This bounds the *count*, not the *wall-clock time*, of that inner retry loop - see
+/// [`CONNECT_TIMEOUT`] for the latter.
+const RECONNECTION_RETRIES: u32 = 3;
+
+/// Wall-clock ceiling on the whole `client.connect()` call in [`IggyBridge::connect`], including
+/// every attempt [`RECONNECTION_RETRIES`] makes internally.
+///
+/// Without this, an unreachable-but-not-refusing address hangs far longer than "a few seconds":
+/// `TcpClient::establish_bounded` only applies its own `FAILOVER_DIAL_TIMEOUT` (2s) when at least
+/// two failover candidates are configured (`tcp_client.rs`) - a bridge always configures exactly
+/// one address, so that guard never engages, and the plain `TcpStream::connect` underneath has no
+/// deadline of its own. Against a firewall that drops SYN packets instead of refusing them, each
+/// of the up to `RECONNECTION_RETRIES + 1` dial attempts pays the kernel's own SYN-retry timeout
+/// (minutes, not seconds) rather than the `reconnection_interval` between attempts - a closed port
+/// (instant RST) never exercises this path, so the failure mode only shows up in production.
+/// 15s comfortably covers a slow-but-alive server's handshake (well above p99 login latency) while
+/// still failing well short of the pathological multi-minute case.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Ceiling on a single Iggy client call made *after* [`IggyBridge::connect`] already succeeded -
+/// `get_stream`, `create_stream`, `get_topic`, `create_topic`, and `shutdown`.
+///
+/// [`CONNECT_TIMEOUT`] alone only bounds the *initial* connect. `TcpClient::send_raw_with_response`
+/// (`tcp_client.rs`) reconnects internally on any transport error, mid-call, through the exact
+/// same undead-lined `TcpStream::connect` path `CONNECT_TIMEOUT` exists to bound - so a bridge
+/// call made after a successful `connect()` (a later network partition, Iggy moved to a new
+/// address) could still hang on the kernel's own SYN-retry window with nothing here to stop it.
+/// Same value as `CONNECT_TIMEOUT`: both bound the same underlying dial, just entered from a
+/// different call site.
+const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;
+
+/// Wraps a single Iggy client call in [`REQUEST_TIMEOUT`]. See that constant's doc for why every
+/// bridge method needs this, not just [`IggyBridge::connect`].
+async fn with_request_timeout<T>(
+ op: impl Future<Output = Result<T, IggyError>>,
+) -> Result<T, BridgeError> {
+ tokio::time::timeout(REQUEST_TIMEOUT, op)
+ .await
+ .map_err(|_elapsed| BridgeError::Iggy(IggyError::CannotEstablishConnection))?
+ .map_err(BridgeError::Iggy)
+}
+
+/// Owns one connected `IggyClient` and resolves Kafka topics against it.
+///
+/// Produce/Fetch handler wiring is a separate, later change (`#3535`/`#3536`) - this type is the
+/// shared plumbing those handlers will call into, exercised standalone here via its own tests and
+/// an integration test against a real `iggy-server`.
+///
+/// One `IggyClient`, shared across every Kafka connection this gateway serves - and the SDK's TCP
+/// transport is lockstep, one request in flight at a time (`tcp_client.rs`: "the connection is
+/// lockstep", its stream mutex held across write, flush, and read). Every concurrent Kafka
+/// connection ends up serialized behind whichever single Iggy request is in flight; the Kafka
+/// side's own connection limit does nothing to relieve this. No pooling exists yet - `close`
+/// already takes `self` by value, which anticipates an eventual `Arc`-shared bridge, but nothing
+/// wires that up today. Documented here and in the README rather than silently discovered under
+/// load once `#3535`/`#3536` land.
+pub struct IggyBridge {
+ client: IggyClient,
+ config: IggyBridgeConfig,
+}
+
+impl IggyBridge {
+ /// Connects to Iggy using `config` and authenticates.
+ ///
+ /// Builds the client through the SDK's fluent TCP builder rather than hand-assembling an
+ /// `iggy://user:pass@host` connection string: that string format splits on `@` then `:`, so a
+ /// password containing either character (`p@ss:word`) would be misparsed into a garbled
+ /// address instead of failing with a diagnosable config error. The fluent builder passes
+ /// `username`/`password` as already-separated fields, sidestepping the ambiguity entirely.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `config.address` is empty. Returns
+ /// [`BridgeError::Iggy`] if the address is malformed, the TCP connection fails, connecting
+ /// takes longer than `CONNECT_TIMEOUT` (an unreachable-and-silently-dropping address, not
+ /// just a refused one, is covered - see that constant's doc), or authentication is rejected -
+ /// this is the boundary [`BridgeError::to_kafka_error_code`] exists for: a handler calling
+ /// this must map the error to a wire response, never panic or unwrap, since an unreachable
+ /// Iggy backend is an expected runtime condition, not a bug.
+ pub async fn connect(config: IggyBridgeConfig) -> Result<Self, BridgeError> {
+ if config.address.trim().is_empty() {
+ return Err(BridgeError::InvalidConfig(
+ "Iggy address must not be empty".to_string(),
+ ));
+ }
+
+ let credentials =
+ Credentials::UsernamePassword(config.username.clone(), config.password.clone());
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(config.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(credentials))
+ .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
+ .build()
+ .map_err(BridgeError::Iggy)?;
+ with_request_timeout(client.connect()).await?;
Review Comment:
warning: now that every call goes through `with_request_timeout`, `CONNECT_TIMEOUT` bounds nothing on its own. Its only references are its own definition, `const REQUEST_TIMEOUT: Duration = CONNECT_TIMEOUT;` at `:69`, and doc comments. `README.md:84-88` still describes the two as separate bounds applied at separate places.
Values are equal today so behaviour is unchanged, but the names now claim a distinction the code does not make. Either apply `CONNECT_TIMEOUT` here and `REQUEST_TIMEOUT` everywhere else, or keep one constant and say so in the README.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,526 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Kafka's own topic-name cap (`Topic.MAX_NAME_LENGTH` in Kafka's own source) - smaller than
+/// [`MAX_IDENTIFIER_LEN`], so a Kafka-side name needs its own limit, not Iggy's.
+const MAX_KAFKA_TOPIC_NAME_LEN: usize = 249;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path. For a Kafka-side topic name (a TOML key, or a `kafka_topic` argument), use
+/// [`validate_kafka_topic_name`] instead - Kafka's own limits and legal characters differ from
+/// Iggy's.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Rejects a Kafka topic name that fails Kafka's own naming rules: empty, leading/trailing
+/// whitespace, over [`MAX_KAFKA_TOPIC_NAME_LEN`] bytes, or containing a byte outside
+/// `[A-Za-z0-9._-]` (Kafka's own `Topic.legalChars`).
+///
+/// Used both for TOML mapping-file keys (`from_toml_str`) and for the `kafka_topic` argument
+/// `IggyBridge::ensure_stream_and_topic`/`high_watermark` take directly - the two paths must agree,
+/// or a name the config file would reject can still reach Iggy unvalidated through the second
+/// path. A whitespace-padded key is the sharpest failure mode this catches: `resolve`'s lookup is
+/// an exact `HashMap::get`, so a padded key parses out of the TOML file cleanly and then matches
+/// nothing at runtime, silently falling through to the default stream instead of erroring - the
+/// one place in this module that would otherwise fail silently instead of loudly.
+///
+/// `field` is `"topic mapping key"` or `"kafka_topic"` in current callers, not a generic template -
+/// kept as a parameter (like [`validate_identifier_name`]) so the message names the actual site.
+pub(crate) fn validate_kafka_topic_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not be empty"),
+ });
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not have leading or trailing whitespace"),
+ });
+ }
+ if value.len() > MAX_KAFKA_TOPIC_NAME_LEN {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!(
+ "{field} is {} bytes, over Kafka's {MAX_KAFKA_TOPIC_NAME_LEN}-byte topic name limit",
+ value.len()
+ ),
+ });
+ }
+ if let Some(illegal) = value
Review Comment:
warning: `.` is in the allowed byte set, so `.` and `..` clear every check in this function. Kafka's own `Topic.validate` rejects exactly those two names, and the doc at `:68` says this applies Kafka's rules.
Not a traversal risk, since Iggy builds on-disk paths from numeric ids, but it is the one place this validator diverges from the rules it claims to implement. Two lines before the character scan.
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,526 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Upper bound `Identifier::named` itself enforces (`identifier/mod.rs`). Checked here too so a
+/// too-long name in the mapping file fails at config load with a message that names the file and
+/// field at fault, instead of surfacing much later as an opaque `InvalidIdentifier` deep inside
+/// `IggyBridge::ensure_stream`/`ensure_topic`.
+const MAX_IDENTIFIER_LEN: usize = 255;
+
+/// Kafka's own topic-name cap (`Topic.MAX_NAME_LENGTH` in Kafka's own source) - smaller than
+/// [`MAX_IDENTIFIER_LEN`], so a Kafka-side name needs its own limit, not Iggy's.
+const MAX_KAFKA_TOPIC_NAME_LEN: usize = 249;
+
+/// Rejects an empty name, one with leading/trailing whitespace, or one over
+/// [`MAX_IDENTIFIER_LEN`] bytes.
+///
+/// Whitespace is rejected outright rather than trimmed and stored: silently trimming here (or
+/// adding that later) would change the resolved Iggy stream/topic name under an already-running
+/// deployment without the operator changing anything they can see in their own config file.
+///
+/// `pub(crate)`: also used by `bridge::config` for `IGGY_KAFKA_IGGY_STREAM`, which feeds
+/// `default_stream` through the same no-file path this module's own validation covers on the
+/// TOML-file path. For a Kafka-side topic name (a TOML key, or a `kafka_topic` argument), use
+/// [`validate_kafka_topic_name`] instead - Kafka's own limits and legal characters differ from
+/// Iggy's.
+pub(crate) fn validate_identifier_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not be empty"
+ )));
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} must not have leading or trailing whitespace: {value:?}"
+ )));
+ }
+ if value.len() > MAX_IDENTIFIER_LEN {
+ return Err(BridgeError::InvalidConfig(format!(
+ "{field} is {} bytes, over the {MAX_IDENTIFIER_LEN}-byte limit Identifier::named \
+ enforces: {value:?}",
+ value.len()
+ )));
+ }
+ Ok(())
+}
+
+/// Rejects a Kafka topic name that fails Kafka's own naming rules: empty, leading/trailing
+/// whitespace, over [`MAX_KAFKA_TOPIC_NAME_LEN`] bytes, or containing a byte outside
+/// `[A-Za-z0-9._-]` (Kafka's own `Topic.legalChars`).
+///
+/// Used both for TOML mapping-file keys (`from_toml_str`) and for the `kafka_topic` argument
+/// `IggyBridge::ensure_stream_and_topic`/`high_watermark` take directly - the two paths must agree,
+/// or a name the config file would reject can still reach Iggy unvalidated through the second
+/// path. A whitespace-padded key is the sharpest failure mode this catches: `resolve`'s lookup is
+/// an exact `HashMap::get`, so a padded key parses out of the TOML file cleanly and then matches
+/// nothing at runtime, silently falling through to the default stream instead of erroring - the
+/// one place in this module that would otherwise fail silently instead of loudly.
+///
+/// `field` is `"topic mapping key"` or `"kafka_topic"` in current callers, not a generic template -
+/// kept as a parameter (like [`validate_identifier_name`]) so the message names the actual site.
+pub(crate) fn validate_kafka_topic_name(field: &str, value: &str) -> Result<(), BridgeError> {
+ if value.is_empty() {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not be empty"),
+ });
+ }
+ if value.trim() != value {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!("{field} must not have leading or trailing whitespace"),
+ });
+ }
+ if value.len() > MAX_KAFKA_TOPIC_NAME_LEN {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!(
+ "{field} is {} bytes, over Kafka's {MAX_KAFKA_TOPIC_NAME_LEN}-byte topic name limit",
+ value.len()
+ ),
+ });
+ }
+ if let Some(illegal) = value
+ .bytes()
+ .find(|b| !(b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')))
+ {
+ return Err(BridgeError::InvalidKafkaTopicName {
+ kafka_topic: value.to_string(),
+ reason: format!(
+ "{field} contains {:?}, outside Kafka's legal topic-name characters \
+ (letters, digits, '.', '_', '-')",
+ illegal as char
+ ),
+ });
+ }
+ Ok(())
+}
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+///
+/// Fields are private and every value is validated (empty/whitespace/length/injectivity - see
+/// [`new`](Self::new)) on the only two ways to build one: [`new`](Self::new) and
+/// [`from_toml_str`](Self::from_toml_str) (which deserializes into a private, unchecked
+/// `RawTopicMapping` first, then calls `new`). Public fields plus `#[derive(Deserialize)]`
+/// directly on this type would let any caller construct or mutate one straight from TOML or a
+/// literal, skipping every check below - which is exactly what happened before this type had a
+/// checked constructor: `bridge::config`'s no-file path built one by hand and needed its own
+/// separate validation call to make up for it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TopicMapping {
+ default_stream: String,
+ topics: HashMap<String, TopicOverride>,
+}
+
+/// Unchecked shadow of [`TopicMapping`], `Deserialize`'s only target - never constructed by hand,
+/// never exposed. `TopicMapping::from_toml_str` is the sole path from TOML to a validated
+/// `TopicMapping`, by deserializing into this first and then calling
+/// [`TopicMapping::new`](TopicMapping::new).
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawTopicMapping {
+ default_stream: String,
+ #[serde(default)]
+ topics: HashMap<String, TopicOverride>,
+}
+
+impl TopicMapping {
+ /// Builds a validated `TopicMapping` from already-parsed parts - the checked constructor the
+ /// no-file `IGGY_KAFKA_IGGY_STREAM` path in `bridge::config` uses, and the sole validation
+ /// gate `from_toml_str` also funnels through.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `default_stream` or any override's `stream`/
+ /// `topic` is empty, has leading/trailing whitespace, or exceeds `MAX_IDENTIFIER_LEN`; if any
+ /// override key fails Kafka's own topic-naming rules (see
+ /// `validate_kafka_topic_name`); or if two override entries are not injective (see
+ /// [`resolve`](Self::resolve)).
+ pub fn new(
+ default_stream: String,
+ topics: HashMap<String, TopicOverride>,
+ ) -> Result<Self, BridgeError> {
+ validate_identifier_name("topic mapping's default_stream", &default_stream)?;
+
+ let mut targets = HashSet::with_capacity(topics.len());
+ for (kafka_topic, over) in &topics {
+ validate_kafka_topic_name("topic mapping key", kafka_topic)?;
Review Comment:
warning: a bad mapping-file key returns `InvalidKafkaTopicName`, which `error.rs:92` sends as `INVALID_TOPIC_EXCEPTION` (17). So an operator's TOML typo reaches a Kafka client as if the client had asked for a bad topic name.
This function's own `# Errors` section at `:169-173` promises `InvalidConfig` for exactly this case, and `InvalidConfig` falls to -1, which is the honest answer for a fault the client cannot see. Same mismatch between the doc and the returned variant at `:248`, `:264` and `config.rs:83-85`.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Locates the already-built `iggy-server` binary. Does not build it - see this crate's
+/// `docs/TEST_SUITE.md` for the prerequisite, the same one `core/integration`'s own
+/// server-spawning tests already carry.
+///
+/// `assert_cmd::cargo::cargo_bin`, matching `core/integration`'s own
+/// `harness::handle::server::start` - not a from-scratch `cargo build` invocation. An earlier
+/// version of this function drove `cargo build --package server --bin iggy-server` directly,
+/// reasoning that `Command::cargo_bin` "only resolves `CARGO_BIN_EXE_*` for binaries owned by
+/// *this* package" - true of the `CARGO_BIN_EXE_*` env-var lookup alone, but `cargo_bin` falls
+/// back to `legacy_cargo_bin` when that's unset, which derives the target directory from
+/// `env::current_exe()` (this test binary's own path) and looks for a same-named file there -
+/// correct under `CARGO_TARGET_DIR`, `--release`, or a `--target` triple subdirectory precisely
+/// because it reads back from where cargo actually placed *this* binary, not a guessed path. That
+/// version also re-ran a `cargo build` from every one of this file's server-spawning tests
+/// (nextest runs each as its own process, so the `OnceLock` memoized nothing across them),
+/// serialized by `.config/nextest.toml`'s `kafka_bridge` test-group but still real, avoidable
+/// per-test overhead this version has none of.
+fn iggy_server_binary() -> PathBuf {
+ assert_cmd::cargo::cargo_bin("iggy-server")
Review Comment:
warning: when the binary is missing, this panics with the `assert_cmd` internal message, not the one `gateways/kafka/docs/TEST_SUITE.md:35` promises. `missing_cargo_bin` (`assert_cmd` 2.2.2, `src/cargo.rs:251-273`) prints `CARGO_BIN_EXE_iggy-server` is unset plus the available binary names, because `CARGO_BIN_EXE_iggy-gateway-kafka` is set in this test binary. The documented `binary not found` text never prints.
A path existence check first, panicking with `cargo build --package server --bin iggy-server`, hands the reader the command instead of a Cargo internal.
##########
gateways/kafka/README.md:
##########
@@ -58,6 +58,120 @@ Before check-in, run the procedure in [docs/MANUAL_TESTING.md](docs/MANUAL_TESTI
See [docs/SCOPE.md](docs/SCOPE.md) for [#3421](https://github.com/apache/iggy/issues/3421) deliverables, supported API key/version table, and post-foundation TODO backlog.
+## Iggy bridge ([#3533](https://github.com/apache/iggy/issues/3533))
+
+`src/bridge/` is the SDK integration layer: connects to Iggy, maps Kafka topics to Iggy
+streams/topics, provisions them on demand, and looks up high watermarks (one or many partitions of
+a topic per call) for `ListOffsets`.
+**Not wired into the live Produce/Fetch dispatch path yet** - that lands with
+[#3535](https://github.com/apache/iggy/issues/3535)/[#3536](https://github.com/apache/iggy/issues/3536).
+Exercised today by `bridge`'s own unit tests and `tests/bridge_iggy_integration_tests.rs` (spawns a
+real `iggy-server`).
+
+### Connection config
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `IGGY_KAFKA_IGGY_ADDR` | `127.0.0.1:8090` | Address of the Iggy server to bridge to |
+| `IGGY_KAFKA_IGGY_USERNAME` | `iggy` | Iggy username |
+| `IGGY_KAFKA_IGGY_PASSWORD` | none - **required** | Iggy password. No default: `iggy-server` only uses the well-known `iggy`/`iggy` root credentials when started with `--with-default-root-credentials` (dev-only); otherwise it generates a random password, so a hardcoded default here could never be right and would invite running as root unnoticed |
+| `IGGY_KAFKA_IGGY_STREAM` | `kafka` | Default Iggy stream for a Kafka topic with no explicit mapping override |
+| `IGGY_KAFKA_TOPIC_MAP_PATH` | unset | Path to a topic-mapping TOML file (see below); omit to use only the default rule |
+
+The initial connect retries a fixed, bounded number of times (`RECONNECTION_RETRIES = 3`, not the
+Iggy SDK client's own default of unlimited retries, one dial per second, forever), and the whole
+attempt - retries included - is capped at `CONNECT_TIMEOUT` (15s) wall-clock, so `IggyBridge::connect`
+fails in bounded time whether the address refuses the connection or silently drops it, instead of
+blocking the calling task indefinitely. Every other bridge call (`ensure_stream_and_topic`,
+`high_watermark(s)`, `close`) carries its own `REQUEST_TIMEOUT` (same 15s bound) for the same
+reason: the SDK reconnects internally, mid-call, on a transport error, through the same
+undead-lined dial path - a bridge call made well after the initial connect can still hit this if
+Iggy becomes unreachable later. See `IggyBridge`'s own doc comment (its rustdoc is private, so
+this isn't a followable link outside the crate - read the source at `src/bridge/iggy_bridge.rs`).
+
+### Topic mapping
+
+Default rule, no config file needed: a Kafka topic `orders` maps to Iggy stream
+`IGGY_KAFKA_IGGY_STREAM` (default `kafka`), topic `orders` - the Kafka topic name carries over
+unchanged. Override specific topics with a TOML file:
+
+```toml
+default_stream = "kafka"
+
+[topics.orders]
+stream = "billing"
+topic = "orders_v2"
+
+# A Kafka topic name containing dots needs the key quoted, or TOML parses it as nested
+# tables ([topics.org] containing [apache] containing [kafka]) instead of one topic named
+# "org.apache.kafka.events".
+[topics."org.apache.kafka.events"]
+stream = "billing"
+topic = "kafka_events"
+```
+
+Point `IGGY_KAFKA_TOPIC_MAP_PATH` at the file to load it; topics not listed under `[topics.*]`
+still fall back to the default rule.
+
+`default_stream` is required in a map file - it has no `#[serde(default)]`, unlike `topics` -
+so an override-only file with no `default_stream` key fails to load rather than falling back to
+`kafka`. When both `IGGY_KAFKA_TOPIC_MAP_PATH` and `IGGY_KAFKA_IGGY_STREAM` are set, the file's own
+`default_stream` always wins and the env var is ignored entirely: a TOML file is a complete mapping
+document, not an overlay on top of the env var.
+
+### Provisioning and idempotency
+
+`ensure_stream_and_topic(kafka_topic, partition_count)` creates the mapped Iggy stream and topic
+if either is missing. Idempotent when repeated with the *same* `partition_count`: a no-op if both
+already exist with that count, and a `NameAlreadyExists` race against a concurrent caller creating
+the same stream/topic is treated as success, not an error - the goal is "it exists," not "this
+call created it." A *different* `partition_count` against an already-existing topic returns
+`BridgeError::PartitionCountMismatch` rather than silently keeping the old count or growing it -
+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. Nothing is bounding retention until it's configured explicitly (Iggy's own topic options,
+outside this bridge today); repointing a Kafka app that assumes bounded retention onto this bridge
+will accumulate data indefinitely unless you set that up yourself.
+
+They also use Iggy's default **durability**, `Durability::Replicated` - quorum commit without an
+additional stable-storage barrier, with the disk write itself threshold-gated (flushed at 1024
+messages or 1 MiB of unflushed data, whichever comes first). Kafka's own defaults take the same
+posture, so this isn't a wrong choice, but on a single node both can lose an acked write to a power
+cut before that threshold is reached - worth knowing rather than discovering later.
+
+### Concurrency ceiling
+
+One `IggyBridge` (one `IggyClient`) is meant to serve every Kafka connection this gateway handles,
+and the Iggy SDK's TCP transport is lockstep - one request in flight per client, its stream mutex
+held across write, flush, and read. Every concurrent Kafka connection ends up serialized behind
+whichever single Iggy request is in flight; the Kafka side's own connection limit
+(`IGGY_KAFKA_MAX_CONNECTIONS`) does nothing to relieve this. No connection pooling exists yet - it
+is a known gap to address before `#3535`/`#3536` put this on a hot path, not a design decision to
+rely on.
+
+### Error mapping
+
+`BridgeError::to_kafka_error_code()` maps Iggy failures to Kafka wire error codes:
+
+- Stream/topic/partition not found → `UNKNOWN_TOPIC_OR_PARTITION` (3)
+- A rejected *permission* (`Unauthorized`) → `TOPIC_AUTHORIZATION_FAILED` (29) - a real,
+ fixable-by-the-Kafka-operator ACL problem
+- A rejected *login* (the bridge's own `IGGY_KAFKA_IGGY_USERNAME`/`_PASSWORD` are wrong) →
+ `UNKNOWN_SERVER_ERROR` (-1), deliberately **not** 29 - the Kafka client can't fix a bridge-side
+ credential misconfiguration, and blaming its own ACLs for one is worse than an unexplained
+ fatal error
+- Connection-shaped failures → `NOT_LEADER_OR_FOLLOWER` (6, the same retriable code the
+ foundation's own stubs send, so a client backs off and retries)
+- An Iggy commit whose outcome is genuinely unknown (`TransientNotCommitted`) →
+ `REQUEST_TIMED_OUT` (7) - retriable in real Kafka too, chosen because it's what a real broker
+ sends for the same shape of failure, not to make a client stop retrying
+- An invalid Kafka-side topic name (empty, whitespace-padded, oversized, illegal characters) →
+ `INVALID_TOPIC_EXCEPTION` (17), checked before any Iggy call is made
+- `PartitionCountMismatch` → `TOPIC_ALREADY_EXISTS` (36, not `INVALID_PARTITIONS` - that code's
+ own text is "below 1", a different condition)
+- Anything else → `UNKNOWN_SERVER_ERROR` (-1)
Review Comment:
warning: the closing `Anything else` makes this list read as complete, and `TooManyPartitions` is missing from it. `error.rs:150` sends `INVALID_PARTITIONS` (37) for it and `error.rs:198-201` pins that with a test, so line 171 currently reads as if 37 is never sent at all.
It is reachable through `ensure_topic`: `core/server/src/rewrite.rs:218-220` raises `TooManyPartitions` above the partition cap.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
Review Comment:
warning: this locks its own directory, so it shares no state with `core/integration/src/harness/port_reserver.rs:158`. With an ephemeral floor of 10000 or below both reservers fall back above their ceilings, this band lands at 61000-61199 and the reserver's at 61000-65535, and two suites in the same workspace can hand out one port under two different locks.
`mod port_reserver;` at `core/integration/src/harness/mod.rs:51` is private today, so sharing the slot files needs a visibility change first. A disjoint band is the cheaper fix if that is not worth it.
##########
gateways/kafka/tests/bridge_iggy_integration_tests.rs:
##########
@@ -0,0 +1,918 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Integration tests for `IggyBridge` against a real `iggy-server` process - not the
+//! `KafkaGateway` under test elsewhere in this suite. `#3533` acceptance criteria this file
+//! exercises directly: `ensure_stream_and_topic` idempotent on repeated calls, and the bridge
+//! module invoked from a real (non-unit) test rather than only compiled.
+
+use std::collections::HashMap;
+use std::fs::{File, OpenOptions};
+use std::path::PathBuf;
+use std::process::{Child, Command};
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyMessage,
+ MessageClient, Partitioning, StreamClient, TopicClient,
+};
+use secrecy::SecretString;
+use serial_test::serial;
+
+use iggy_gateway_kafka::bridge::{
+ BridgeError, IggyBridge, IggyBridgeConfig, TopicMapping, TopicOverride,
+};
+
+/// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
+/// real ephemeral range leaves little room, but this crate never needs more than a handful live
+/// at once (this binary's own tests already run one at a time - see `.config/nextest.toml`'s
+/// `kafka_bridge` test-group).
+const DESIRED_SLOTS: u16 = 200;
+
+/// Lowest port `port_band()` will ever place its band at - clear of the well-known/privileged
+/// range (0-1023).
+const MIN_CANDIDATE_PORT: u16 = 10000;
+
+/// Ephemeral range assumed when the kernel's own can't be read (no `/proc` - e.g. macOS),
+/// matching the Linux default. Mirrors `core/integration`'s own `port_reserver.rs`.
+const DEFAULT_EPHEMERAL_RANGE: (u16, u16) = (32768, 60999);
+
+const IP_LOCAL_PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
+
+fn parse_ephemeral_range(range: &str) -> Option<(u16, u16)> {
+ let mut bounds = range.split_whitespace();
+ let floor: u16 = bounds.next()?.parse().ok()?;
+ let ceiling: u16 = bounds.next()?.parse().ok()?;
+ Some((floor, ceiling))
+}
+
+/// The range the kernel picks `bind(0)` ports from, read once.
+fn ephemeral_range() -> (u16, u16) {
+ static RANGE: OnceLock<(u16, u16)> = OnceLock::new();
+ *RANGE.get_or_init(|| {
+ std::fs::read_to_string(IP_LOCAL_PORT_RANGE)
+ .ok()
+ .as_deref()
+ .and_then(parse_ephemeral_range)
+ .unwrap_or(DEFAULT_EPHEMERAL_RANGE)
+ })
+}
+
+/// First port and slot count of a band clear of the kernel's ephemeral range: below the floor by
+/// preference (matches `core/integration`'s own `port_reserver.rs`), above the ceiling when the
+/// floor leaves no room there.
+///
+/// A *hardcoded* band, chosen once without reading the real range (this file's own prior version:
+/// `15000..15199`, on the unverified assumption that every real deployment's floor sits above
+/// it), is wrong on any box tuned wider - `net.ipv4.ip_local_port_range = "1024 65535"` swallows
+/// that whole band. `flock` alone doesn't save it either: it is advisory, so it only excludes
+/// another `PortGuard`-based process, never an unrelated `bind(0)` elsewhere on the box landing on
+/// the same number from the kernel's own ephemeral pool.
+fn port_band() -> (u16, u16) {
+ static BAND: OnceLock<(u16, u16)> = OnceLock::new();
+ *BAND.get_or_init(|| {
+ let (floor, ceiling) = ephemeral_range();
+ band_for(floor, ceiling)
+ })
+}
+
+/// Pure band-selection logic, split out from [`port_band`] so it's testable against synthetic
+/// ranges without needing to fake `/proc` contents.
+fn band_for(floor: u16, ceiling: u16) -> (u16, u16) {
+ if floor > MIN_CANDIDATE_PORT {
+ let room = floor - MIN_CANDIDATE_PORT;
+ return (MIN_CANDIDATE_PORT, room.min(DESIRED_SLOTS));
+ }
+ let Some(start) = ceiling.checked_add(1) else {
+ panic!(
+ "kernel ephemeral range [{floor}, {ceiling}] leaves no room for a test port band \
+ below {MIN_CANDIDATE_PORT} nor above {ceiling} - narrow the range, e.g. \
+ sysctl -w net.ipv4.ip_local_port_range='32768 60999'"
+ );
+ };
+ // start >= 1 (ceiling + 1), so this never overflows u16.
+ let room = u16::MAX - start + 1;
+ (start, room.min(DESIRED_SLOTS))
+}
+
+#[test]
+fn given_a_readable_range_when_parsed_should_take_both_bounds() {
+ assert_eq!(
+ parse_ephemeral_range("32768\t60999\n"),
+ Some((32768, 60999))
+ );
+ assert_eq!(parse_ephemeral_range("1024 65535"), Some((1024, 65535)));
+ assert_eq!(parse_ephemeral_range(""), None);
+ assert_eq!(parse_ephemeral_range("32768"), None);
+ assert_eq!(parse_ephemeral_range("garbage 60999"), None);
+}
+
+#[test]
+fn given_room_below_the_floor_when_choosing_a_band_should_take_it() {
+ let (start, slots) = band_for(32768, 60999);
+ assert_eq!(start, MIN_CANDIDATE_PORT);
+ assert!(
+ start + slots <= 32768,
+ "band [{start}, {}] runs into the ephemeral floor",
+ start + slots - 1
+ );
+}
+
+/// A box tuned `net.ipv4.ip_local_port_range = "1024 60999"` is exactly the case the prior
+/// hardcoded `15000..15199` band silently broke under: room below the floor down to
+/// `MIN_CANDIDATE_PORT` is gone, but the ceiling still leaves room above it.
+#[test]
+fn given_no_room_below_the_floor_when_choosing_a_band_should_fall_back_above_the_ceiling() {
+ let (start, slots) = band_for(1024, 60999);
+ assert!(slots > 0, "must find room above the ceiling, not just fail");
+ assert!(
+ start > 60999,
+ "band must start above the ephemeral ceiling, got {start}"
+ );
+}
+
+#[test]
+#[should_panic(expected = "leaves no room")]
+fn given_no_room_on_either_side_when_choosing_a_band_should_fail_loudly() {
+ band_for(1024, u16::MAX);
+}
+
+/// Exclusive claim on one port, released (and the port freed for reuse) when dropped - including
+/// on an unclean process exit, since the OS drops the `flock` with the file descriptor. Unlike
+/// bind-then-drop, this process itself never binds the port before `iggy-server` does; see
+/// `port_band`'s doc comment for the limits of that guarantee against *other* processes.
+struct PortGuard {
+ port: u16,
+ _lock: File,
+}
+
+impl PortGuard {
+ fn acquire() -> Self {
+ let (band_start, band_slots) = port_band();
+ let lock_dir = std::env::temp_dir().join("iggy-kafka-gateway-test-port-locks");
+ std::fs::create_dir_all(&lock_dir).expect("create port lock dir");
+ for offset in 0..band_slots {
+ let port = band_start + offset;
+ let path = lock_dir.join(format!("{port}.lock"));
+ let Ok(file) = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&path)
+ else {
+ continue;
+ };
+ if file.try_lock().is_ok() {
+ return Self { port, _lock: file };
+ }
+ }
+ panic!(
+ "no free port slot in [{band_start}, {}]",
+ band_start + band_slots - 1
+ );
+ }
+}
+
+/// Locates the already-built `iggy-server` binary. Does not build it - see this crate's
+/// `docs/TEST_SUITE.md` for the prerequisite, the same one `core/integration`'s own
+/// server-spawning tests already carry.
+///
+/// `assert_cmd::cargo::cargo_bin`, matching `core/integration`'s own
+/// `harness::handle::server::start` - not a from-scratch `cargo build` invocation. An earlier
+/// version of this function drove `cargo build --package server --bin iggy-server` directly,
+/// reasoning that `Command::cargo_bin` "only resolves `CARGO_BIN_EXE_*` for binaries owned by
+/// *this* package" - true of the `CARGO_BIN_EXE_*` env-var lookup alone, but `cargo_bin` falls
+/// back to `legacy_cargo_bin` when that's unset, which derives the target directory from
+/// `env::current_exe()` (this test binary's own path) and looks for a same-named file there -
+/// correct under `CARGO_TARGET_DIR`, `--release`, or a `--target` triple subdirectory precisely
+/// because it reads back from where cargo actually placed *this* binary, not a guessed path. That
+/// version also re-ran a `cargo build` from every one of this file's server-spawning tests
+/// (nextest runs each as its own process, so the `OnceLock` memoized nothing across them),
+/// serialized by `.config/nextest.toml`'s `kafka_bridge` test-group but still real, avoidable
+/// per-test overhead this version has none of.
+fn iggy_server_binary() -> PathBuf {
+ assert_cmd::cargo::cargo_bin("iggy-server")
+}
+
+struct TestServer {
+ child: Child,
+ address: String,
+ password: String,
+ _port_guard: PortGuard,
+}
+
+impl TestServer {
+ /// Spawns `iggy-server` with the default `iggy`/`iggy` root credentials. See
+ /// [`Self::spawn_with_password`] for the general form.
+ async fn spawn(data_dir: &std::path::Path) -> Self {
+ Self::spawn_with_password(data_dir, "iggy").await
+ }
+
+ /// Spawns `iggy-server` with an isolated temp data dir, a locked TCP port, and the given root
+ /// password, then blocks until its listener is ready or the startup budget is exhausted.
+ ///
+ /// A dedicated password parameter (not just the `spawn()` default everywhere) lets a
+ /// password-shaped regression test (special characters, say) reuse this harness's
+ /// `PortGuard`/graceful-`Drop`/`wait_ready` machinery instead of hand-rolling a second,
+ /// `Drop`-less spawn: a `Drop`-less copy has no guard to run `graceful_kill` on a panic before
+ /// its assertions, orphaning a process that still holds its `PortGuard` slot, which then
+ /// fails the next test that draws that slot to bind.
+ async fn spawn_with_password(data_dir: &std::path::Path, password: &str) -> Self {
+ let port_guard = PortGuard::acquire();
+ let address = format!("127.0.0.1:{}", port_guard.port);
+
+ let mut command = Command::new(iggy_server_binary());
+ command
+ .env("IGGY_PATH", data_dir.display().to_string())
+ .env("IGGY_TCP_ADDRESS", &address)
+ .env("IGGY_HTTP_ENABLED", "false")
+ .env("IGGY_QUIC_ENABLED", "false")
+ // WebSocket defaults to enabled on a fixed 127.0.0.1:8092 (config.toml), unlike TCP
+ // which reads a per-test port from PortGuard - every spawned server here would fight
+ // over that one port otherwise, and a bind failure aborts boot.
+ .env("IGGY_WEBSOCKET_ENABLED", "false")
+ // Matches core/integration's own spawned-server harness (harness/handle/server.rs):
+ // pinned shards (config.toml default: pin_cores = true) of concurrently running
+ // servers pile onto the same cores and starve each other. This crate's own tests are
+ // serialized against each other (.config/nextest.toml's kafka_bridge test-group -
+ // #[serial] alone does not survive nextest, which runs each test as its own process),
+ // but a spawned server here can still land alongside a pinned server from a different
+ // package's test in the same nextest run.
+ .env("IGGY_SHARDING_PIN_CORES", "false")
+ // `--with-default-root-credentials` is off by default (args.rs) - without these,
+ // a fresh server provisions no loginable root user at all, and every bridge connect
+ // attempt fails with "invalid credentials" no matter what this test passes.
+ .env("IGGY_ROOT_USERNAME", "iggy")
+ .env("IGGY_ROOT_PASSWORD", password);
+ let child = command.spawn().expect("spawn iggy-server");
+
+ let mut server = Self {
+ child,
+ address,
+ password: password.to_string(),
+ _port_guard: port_guard,
+ };
+ server.wait_ready().await;
+ server
+ }
+
+ /// Polls with a bare TCP connect, not a full `IggyBridge::connect`: the latter carries
+ /// `RECONNECTION_RETRIES` (3 dials at ~1s apart) on every failed attempt, so a poll loop built
+ /// on it pays several real seconds per iteration instead of running at its own 100ms cadence,
+ /// and a *successful* poll iteration would authenticate a client and then drop it without
+ /// `close()`, leaking a session server-side. A TCP accept slightly ahead of the app being
+ /// ready to authenticate is fine - every caller's own subsequent `IggyBridge::connect` already
+ /// retries a few times, which covers the last few hundred ms of that gap.
+ ///
+ /// Checks `try_wait()` every iteration: a server that fails at boot (bad config, a port
+ /// stolen between `PortGuard::acquire` and its own bind) exits almost immediately, and without
+ /// this check that reads as "still starting" for the full 30s budget - the eventual failure
+ /// names the wrong cause ("did not become ready") instead of the real one (exited early, with
+ /// whatever it printed before dying).
+ async fn wait_ready(&mut self) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Some(status) = self.child.try_wait().expect("poll child status") {
+ panic!(
+ "iggy-server at {} exited during startup with {status}",
+ self.address
+ );
+ }
+ if tokio::net::TcpStream::connect(self.address.as_str())
+ .await
+ .is_ok()
+ {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "iggy-server at {} did not become ready within the startup budget",
+ self.address
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ fn test_config(&self) -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: self.address.clone(),
+ username: "iggy".to_string(),
+ password: SecretString::from(self.password.clone()),
+ topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
+ .expect("valid mapping for this test's fixture data"),
+ }
+ }
+}
+
+/// SIGTERM, wait up to `SIGTERM_TIMEOUT`, then SIGKILL if it hasn't exited. Mirrors
+/// `core/integration`'s own `harness::handle::common::graceful_kill` (not reused directly - that
+/// crate is heavyweight, and pulling it in for one function isn't worth it; this crate already
+/// depends directly on `iggy`/`core/sdk`, so `core/integration` wouldn't add a *new*
+/// core/sdk-change-reruns-these-tests edge, just an unrelated dependency). A bare SIGKILL skips
+/// `iggy-server`'s shutdown path entirely, which is a materially different exit than what the
+/// binary is actually built to do on `SIGTERM` - `.kill()` alone bypassed that in every test run
+/// before this fix.
+const SIGTERM_TIMEOUT: Duration = Duration::from_secs(5);
+const SIGKILL_POLL_INTERVAL: Duration = Duration::from_millis(50);
+
+fn graceful_kill(child: &mut Child) {
+ // `wait_ready` calls `try_wait()` too (and panics on an early exit, unwinding into this via
+ // `Drop`) - if it already reaped the child, `child.id()` is a PID the OS is free to hand to an
+ // unrelated process by the time we get here, and a raw `libc::kill` (unlike `std::Child::kill`,
+ // which checks its own cached exit status first and no-ops instead) has no such guard against
+ // signaling that PID anyway. Checking here first closes the same gap `std` already closes for
+ // its own `kill`.
+ if matches!(child.try_wait(), Ok(Some(_))) {
+ return;
+ }
+
+ let pid = child.id() as libc::pid_t;
+ // Safety: `pid` is this process's own live child, confirmed by the `try_wait` check above;
+ // sending it a signal is exactly what `Child::kill` itself does internally.
+ unsafe {
+ libc::kill(pid, libc::SIGTERM);
+ }
+
+ let deadline = std::time::Instant::now() + SIGTERM_TIMEOUT;
+ while std::time::Instant::now() < deadline {
+ match child.try_wait() {
+ Ok(None) => std::thread::sleep(SIGKILL_POLL_INTERVAL),
+ Ok(Some(_)) | Err(_) => return,
+ }
+ }
+
+ let _ = child.kill();
+}
+
+impl Drop for TestServer {
+ fn drop(&mut self) {
+ graceful_kill(&mut self.child);
+ let _ = self.child.wait();
+ }
+}
+
+/// Builds and connects a raw `IggyClient` against `server` - for producing test data directly,
+/// independent of the `IggyBridge` under test. Uses the fluent builder, not a hand-built
+/// `iggy://user:pass@host` string: `ConnectionString` splits on `@` then `:`, which breaks for
+/// any password containing either character.
+async fn raw_client(server: &TestServer) -> IggyClient {
+ let client = IggyClientBuilder::new()
+ .with_tcp()
+ .with_server_address(server.address.clone())
+ .with_auto_sign_in(AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_string(),
+ SecretString::from("iggy"),
+ )))
+ .build()
+ .expect("build raw test client");
+ client.connect().await.expect("connect raw test client");
+ client
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("second call is a no-op against the now-existing stream and topic");
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("third call is still a no-op");
+
+ // Read back real state, not just three Oks: proves the second and third calls were actually
+ // no-ops against the one topic the first call created, not e.g. three independent topics
+ // that all happen to satisfy Ok(()) individually.
+ let raw = raw_client(&server).await;
+ let topics = raw
+ .get_topics(&Identifier::named("kafka").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(topics.len(), 1, "must be exactly one topic, not three");
+ assert_eq!(topics[0].name, "orders");
+ assert_eq!(topics[0].partitions_count, 3);
+}
+
+/// Regression test for coverage: nothing previously exercised `PartitionCountMismatch` on a real
+/// server - only unit tests constructed the variant directly.
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_rejects_a_second_call_with_a_different_partition_count() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 3)
+ .await
+ .expect("first call creates the topic with 3 partitions");
+
+ let err = bridge
+ .ensure_stream_and_topic("orders", 5)
+ .await
+ .expect_err(
+ "a different partition count against an existing topic must not silently succeed",
+ );
+ match err {
+ BridgeError::PartitionCountMismatch {
+ topic,
+ existing,
+ requested,
+ } => {
+ assert_eq!(topic, "orders", "must report the Kafka-side name");
+ assert_eq!(existing, 3);
+ assert_eq!(requested, 5);
+ }
+ other => panic!("expected PartitionCountMismatch, got {other:?}"),
+ }
+}
+
+/// Regression test for coverage: every other test uses an empty `TopicMapping` (`HashMap::new()`),
+/// so the Kafka-name-vs-Iggy-name distinction `ensure_topic`/`high_watermark` deliberately
+/// maintain in their error paths (`kafka_topic`, not the resolved `topic_name`) can never actually
+/// differ and so can never be caught wrong. This test maps a Kafka topic to a differently-named
+/// Iggy stream/topic and checks both the happy path and the error paths report the Kafka-side
+/// name a real caller (a future handler) would recognize.
+#[tokio::test]
+#[serial]
+async fn bridge_operations_report_the_kafka_side_name_through_a_real_topic_mapping_override() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let mut config = server.test_config();
+ let mut topics = HashMap::new();
+ topics.insert(
+ "orders".to_string(),
+ TopicOverride {
+ stream: "billing".to_string(),
+ topic: "orders_v2".to_string(),
+ },
+ );
+ config.topic_mapping = TopicMapping::new("kafka".to_string(), topics)
+ .expect("valid mapping for this test's fixture data");
+ let bridge = IggyBridge::connect(config)
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("must create the mapped Iggy stream/topic, not one named after the Kafka topic");
+
+ // The Iggy-side resources are named differently from the Kafka topic - confirms the mapping
+ // actually took effect, not that resolve() was a no-op that happened to pass either way.
+ let raw = raw_client(&server).await;
+ let billing_topics = raw
+ .get_topics(&Identifier::named("billing").expect("valid stream name"))
+ .await
+ .expect("get_topics call");
+ assert_eq!(billing_topics.len(), 1);
+ assert_eq!(billing_topics[0].name, "orders_v2");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("must resolve through the mapping, not fail looking for a stream named 'orders'");
+ assert_eq!(watermark, 0);
+
+ let out_of_range = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(
+ matches!(
+ &out_of_range,
+ BridgeError::PartitionOutOfRange { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {out_of_range:?}"
+ );
+
+ let mismatch = bridge
+ .ensure_stream_and_topic("orders", 2)
+ .await
+ .expect_err("different partition count against the mapped topic must not silently succeed");
+ assert!(
+ matches!(
+ &mismatch,
+ BridgeError::PartitionCountMismatch { topic, .. } if topic == "orders"
+ ),
+ "error must quote the Kafka topic name 'orders', not the Iggy name 'orders_v2': \
+ {mismatch:?}"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_is_zero_for_a_fresh_empty_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("fresh topic must report a watermark, not an error");
+ assert_eq!(
+ watermark, 0,
+ "a freshly created, empty partition's high watermark must be 0"
+ );
+}
+
+/// Pins the exact semantics of `Iggy::Partition::current_offset` (offset of the *last written*
+/// message, not Kafka's "next offset to produce") against a real server - a test that only
+/// checked the empty-topic case would pass under either interpretation and hide an off-by-one.
+#[tokio::test]
+#[serial]
+async fn high_watermark_reflects_produced_messages() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before producing");
+
+ let stream_id = Identifier::named("kafka").expect("valid stream name");
+ let topic_id = Identifier::named("orders").expect("valid topic name");
+ let mut messages: Vec<IggyMessage> = (0..3)
+ .map(|i| IggyMessage::from(format!("message-{i}")))
+ .collect();
+ let client = raw_client(&server).await;
+ client
+ .send_messages(
+ &stream_id,
+ &topic_id,
+ &Partitioning::partition_id(0),
+ &mut messages,
+ )
+ .await
+ .expect("send 3 messages");
+
+ let watermark = bridge
+ .high_watermark("orders", 0)
+ .await
+ .expect("topic must report a watermark after producing");
+ assert_eq!(
+ watermark, 3,
+ "high watermark after 3 messages (offsets 0, 1, 2) must be 3, not the last offset (2)"
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn high_watermark_rejects_out_of_range_partition() {
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("orders", 1)
+ .await
+ .expect("stream and topic must exist before checking the watermark");
+
+ let err = bridge
+ .high_watermark("orders", 5)
+ .await
+ .expect_err("partition 5 does not exist on a 1-partition topic");
+ assert!(matches!(err, BridgeError::PartitionOutOfRange { .. }));
+}
+
+#[tokio::test]
+#[serial]
+async fn ensure_stream_and_topic_is_idempotent_for_a_numeric_topic_name() {
+ // Regression test: Identifier::try_from/FromStr parses an all-digit string as a numeric ID,
+ // not a name - a second call for the same numeric-named topic would look it up by the wrong
+ // resource kind and fail with StreamIdNotFound/TopicIdNotFound despite the topic existing.
+ let data_dir = tempfile::tempdir().expect("tempdir");
+ let server = TestServer::spawn(data_dir.path()).await;
+ let bridge = IggyBridge::connect(server.test_config())
+ .await
+ .expect("bridge should connect to a ready server");
+
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("first call creates the numeric-named stream and topic");
+ bridge
+ .ensure_stream_and_topic("2024", 1)
+ .await
+ .expect("second call must still find the numeric-named topic by name, not by ID");
+}
+
+/// Regression test: `ensure_stream` used to hand `ensure_topic` the stream's *numeric* id
+/// (`Identifier::numeric`), and streams are backed by a recycled slab (freed keys are reused by
+/// the next created stream) - a stream deleted and recreated between the two calls would leave
+/// `ensure_topic` writing into whatever stream now holds that recycled numeric key, not the one
+/// `ensure_stream_and_topic`'s caller actually resolved. The fix threads the *named* `Identifier`
+/// through instead. This does not (cannot, from a black-box test) hit the exact `await` window the
+/// bug lived in, but it does prove the name, not a captured numeric id, is what actually governs:
+/// delete the stream, recreate it under the same name, and the very next call must still land the
+/// topic on the live incarnation.
+#[tokio::test]
+#[serial]
+async fn ensure_topic_targets_the_streams_live_incarnation_after_a_delete_and_recreate() {
Review Comment:
warning: this cannot fail on the regression the doc above it describes. The stream is deleted and recreated before the second `ensure_stream_and_topic`, so `ensure_stream` re-reads a live id on that call either way. An implementation that captured `details.id` and returned `Identifier::numeric(...)` passes every assertion at `:695-703`.
To make it bite, capture the first incarnation's numeric id, recreate under the same name so the new id differs, then assert the second call still lands on the live incarnation. As written it guards the happy path, not the bug.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3965784460
##########
gateways/kafka/src/bridge/iggy_bridge.rs:
##########
@@ -0,0 +1,310 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use iggy::prelude::{
+ AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
+ StreamClient, TopicClient, TopicCreateOptions,
+};
+use tracing::{debug, info};
+
+use crate::bridge::config::IggyBridgeConfig;
+use crate::bridge::error::BridgeError;
+
+/// Passes attempted, after the first, before [`IggyBridge::connect`] gives up and returns `Err`.
+///
+/// Not the SDK's own default (`TcpClientReconnectionConfig::default()` is `max_retries: None` -
+/// unlimited, one dial per second, forever). A Kafka client already retries at the wire-protocol
+/// level once a handler maps a bridge failure to a retriable error code; the bridge blocking a
+/// request task inside an unbounded internal reconnect loop would just add a second, invisible
+/// retry layer underneath that one instead of surfacing the failure so the mapped code can be
+/// sent. At the default `reconnection_interval` (1s), a fully unreachable address fails in a few
Review Comment:
`FAILOVER_DIAL_TIMEOUT` only applies when `candidates.len() >= 2`; a single-address config is a bare `TcpStream::connect`. The unreach test RSTs on unbound loopback, so it never exercised a DROP.
Will wrap `IggyClientBuilder` `connect()` in `tokio::time::timeout` with a bound above a slow-but-alive handshake (not 2s). README will state that bound and stop saying “a few seconds”.
The RST test stays as the fast-fail case; it will not be claimed as coverage of the timeout path.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3968276261
##########
gateways/kafka/src/bridge/config.rs:
##########
@@ -0,0 +1,204 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use secrecy::SecretString;
+use tracing::warn;
+
+use crate::bridge::error::BridgeError;
+use crate::bridge::topic_map::TopicMapping;
+
+const DEFAULT_IGGY_ADDR: &str = "127.0.0.1:8090";
+/// Matches the Iggy server's own default root user - not a made-up example, the same default
+/// every fresh `iggy-server` and every CLI quick-start in this repo uses.
+const DEFAULT_IGGY_USERNAME: &str = "iggy";
+const DEFAULT_IGGY_PASSWORD: &str = "iggy";
+
+/// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
+///
+/// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
+/// (`secrecy` crate) - never add a plain `String` credential field here without the same
+/// treatment (see `connector-pr-review` blocker B1 in the connectors subsystem for why).
+#[derive(Debug, Clone)]
+pub struct IggyBridgeConfig {
+ pub address: String,
+ pub username: String,
+ pub password: SecretString,
+ pub topic_mapping: TopicMapping,
+}
+
+impl IggyBridgeConfig {
+ /// The complete set of `IGGY_KAFKA_*` vars this module reads. Mirrors `main.rs`'s
+ /// `KNOWN_KAFKA_ENV_VARS` guard - add new vars to both, or a typo silently no-ops instead of
+ /// surfacing (`IGGY_KAFKA_` is a `DELEGATED_ENV_VAR_PREFIXES` entry in `core/configs`, so the
+ /// central provider's own typo-detection doesn't cover this namespace either).
+ pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+ "IGGY_KAFKA_IGGY_ADDR",
+ "IGGY_KAFKA_IGGY_USERNAME",
+ "IGGY_KAFKA_IGGY_PASSWORD",
+ "IGGY_KAFKA_IGGY_STREAM",
+ "IGGY_KAFKA_TOPIC_MAP_PATH",
+ ];
+
+ /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
+ /// out-of-the-box address and root credentials.
+ ///
+ /// `IGGY_KAFKA_IGGY_STREAM` and `IGGY_KAFKA_TOPIC_MAP_PATH` both influence the mapping's
+ /// default stream; when both are set, the TOML file's own `default_stream` wins and
+ /// `IGGY_KAFKA_IGGY_STREAM` is ignored entirely for the topics it covers (a TOML file is a
+ /// complete mapping document, not an overlay) - a `warn!` fires so that isn't silently
+ /// mysterious to whoever set the env var expecting it to matter.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`BridgeError::InvalidConfig`] if `IGGY_KAFKA_TOPIC_MAP_PATH` is set but the file
+ /// is missing or fails to parse.
+ pub fn from_env() -> Result<Self, BridgeError> {
+ let address =
+ std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
+ let username = std::env::var("IGGY_KAFKA_IGGY_USERNAME")
+ .unwrap_or_else(|_| DEFAULT_IGGY_USERNAME.to_string());
+ let password = std::env::var("IGGY_KAFKA_IGGY_PASSWORD")
+ .unwrap_or_else(|_| DEFAULT_IGGY_PASSWORD.to_string());
+ let stream_env = std::env::var("IGGY_KAFKA_IGGY_STREAM").ok();
+ // Caught here, not left to TopicMapping::from_toml_str's own empty check: that
+ // validation only runs when IGGY_KAFKA_TOPIC_MAP_PATH is set, since the no-file branch
+ // below builds a TopicMapping directly rather than through the validating constructor.
+ // An explicitly-empty (not merely absent) IGGY_KAFKA_IGGY_STREAM would otherwise pass
+ // from_env cleanly and only fail much later, deep in the first ensure_stream_and_topic
+ // call, as an opaque Identifier::named("") error.
+ if let Some(ref stream) = stream_env
+ && stream.trim().is_empty()
+ {
+ return Err(BridgeError::InvalidConfig(
+ "IGGY_KAFKA_IGGY_STREAM must not be empty".to_string(),
+ ));
+ }
+ let topic_map_path = std::env::var("IGGY_KAFKA_TOPIC_MAP_PATH").ok();
+
+ let topic_mapping = match topic_map_path {
+ Some(path) => {
+ if stream_env.is_some() {
+ warn!(
+ "IGGY_KAFKA_IGGY_STREAM is set but ignored: IGGY_KAFKA_TOPIC_MAP_PATH's \
+ own default_stream takes precedence"
+ );
+ }
+ TopicMapping::from_file(Path::new(&path))?
+ }
+ None => TopicMapping {
+ default_stream: stream_env.unwrap_or_else(|| "kafka".to_string()),
+ topics: std::collections::HashMap::new(),
+ },
+ };
+
+ Ok(Self {
+ address,
+ username,
+ password: SecretString::from(password),
+ topic_mapping,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serial_test::serial;
+
+ use super::*;
+
+ fn test_config() -> IggyBridgeConfig {
+ IggyBridgeConfig {
+ address: "127.0.0.1:8090".to_string(),
+ username: "iggy".to_string(),
+ password: SecretString::from("iggy"),
+ topic_mapping: TopicMapping {
+ default_stream: "kafka".to_string(),
+ topics: std::collections::HashMap::new(),
+ },
+ }
+ }
+
+ #[test]
+ fn debug_output_does_not_expose_password() {
+ // A distinctive value, not the shared fixture's "iggy" - that string also appears as the
+ // username and inside the struct's own name, which would make a substring check here
+ // pass trivially regardless of whether the password field itself is actually redacted.
+ let mut config = test_config();
+ config.password = SecretString::from("correct-horse-battery-staple");
+ let debug_output = format!("{config:?}");
+ assert!(
+ !debug_output.contains("correct-horse-battery-staple"),
+ "Debug output must not expose the plaintext password: {debug_output}"
+ );
+ }
+
+ #[test]
+ #[serial]
+ fn from_env_rejects_missing_topic_map_file() {
+ // Safety: single-threaded within this function; no other test in this crate touches
+ // IGGY_KAFKA_TOPIC_MAP_PATH.
+ unsafe {
Review Comment:
Fixed — it was overclaiming. Replaced the hardcoded 15000..15199 band with port_reserver.rs's own approach: reads /proc/sys/net/ipv4/ip_local_port_range (ephemeral_range(), Linux default 32768-60999 fallback
where there's no /proc, e.g. macOS), then picks a band clear of it — below the floor by preference, above the ceiling when the floor leaves no room, panics loudly if neither side has room (mirrors
port_reserver.rs's own "no degraded mode"). flock is still advisory as pointed— the fix isn't making it exclusive, it's making sure the band it locks is actually outside the range an unrelated bind(0) could land in, on a box tuned 1024 65535 or otherwise
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core (#3533) [iggy]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5519516467
## [Codecov](https://app.codecov.io/gh/apache/iggy/pull/4043?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 84.73%. Comparing base ([`ca0b578`](https://app.codecov.io/gh/apache/iggy/commit/ca0b578a225bf4b9169e4ae78844f3f0423a4e99?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`89e1c52`](https://app.codecov.io/gh/apache/iggy/commit/89e1c52e965c35af3c7b48ab18590262b7119bab?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #4043 +/- ##
============================================
- Coverage 85.17% 84.73% -0.45%
Complexity 1402 1402
============================================
Files 1237 1235 -2
Lines 181722 181474 -248
Branches 148015 147974 -41
============================================
- Hits 154783 153772 -1011
- Misses 22882 23637 +755
- Partials 4057 4065 +8
```
| [Components](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [Rust Core](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `86.11% <ø> (ø)` | |
| [Java SDK](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `67.29% <ø> (ø)` | |
| [C# SDK](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `75.39% <ø> (ø)` | |
| [Python SDK](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `90.06% <ø> (ø)` | |
| [PHP SDK](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `85.65% <ø> (ø)` | |
| [Node SDK](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `89.90% <ø> (-6.35%)` | :arrow_down: |
| [Go SDK](https://app.codecov.io/gh/apache/iggy/pull/4043/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `69.28% <ø> (ø)` | |
[see 54 files with indirect coverage changes](https://app.codecov.io/gh/apache/iggy/pull/4043/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on code in PR #4043:
URL: https://github.com/apache/iggy/pull/4043#discussion_r3967793382
##########
gateways/kafka/src/bridge/topic_map.rs:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use serde::Deserialize;
+
+use crate::bridge::error::BridgeError;
+
+/// Explicit Kafka-topic → Iggy stream/topic override. Absent entries fall back to
+/// [`TopicMapping::default_stream`] plus the Kafka topic name unchanged - see
+/// [`TopicMapping::resolve`].
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct TopicOverride {
+ pub stream: String,
+ pub topic: String,
+}
+
+/// Kafka topic name → Iggy stream/topic mapping, loaded from TOML.
+///
+/// Default rule (no override): the Iggy stream is [`default_stream`](Self::default_stream) and
+/// the Iggy topic name is the Kafka topic name unchanged. A gateway that fronts a single Kafka
+/// "cluster" for one Iggy stream never needs an override entry at all.
+#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq)]
Review Comment:
`#[derive(Default)]` produces `default_stream: ""`, which `from_toml_str` rejects. A `[topic.orders]` typo currently parses as an empty `topics` map.
(typo'd [topic.x] now fails loudly instead of silently parsing to an empty map); removed the unused, invalid-state-producing Default derive on TopicMapping.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gateways): Iggy Kafka bridge core — SDK client and stream/topic mapping [iggy]
Posted by "ryerraguntla (via GitHub)" <gi...@apache.org>.
ryerraguntla commented on PR #4043:
URL: https://github.com/apache/iggy/pull/4043#issuecomment-5569423914
Please review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org