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

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

Reply via email to