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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to