mixermt commented on code in PR #3111:
URL: https://github.com/apache/iceberg-rust/pull/3111#discussion_r4174351086


##########
crates/storage/opendal/src/hdfs_native.rs:
##########
@@ -0,0 +1,411 @@
+// 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.
+
+//! HDFS storage backend via OpenDAL's `services-hdfs-native` (pure Rust, no 
JNI).
+
+use std::collections::HashMap;
+use std::sync::{Arc, RwLock};
+
+use iceberg::io::{HDFS_HADOOP_CONF_PREFIX, HDFS_NAME_NODE};
+use iceberg::{Error, ErrorKind, Result};
+use opendal::Operator;
+use opendal::services::HdfsNativeConfig;
+use url::Url;
+
+use crate::utils::from_opendal_error;
+
+/// Parse iceberg properties to [`HdfsNativeConfig`].
+pub(crate) fn hdfs_native_config_parse(mut m: HashMap<String, String>) -> 
Result<HdfsNativeConfig> {
+    let mut cfg = HdfsNativeConfig::default();
+
+    // `Operator::from_config` bypasses the builder's empty-string guard, and
+    // `Some("")` would shadow the path-authority fallback below.
+    if let Some(name_node) = m
+        .remove(HDFS_NAME_NODE)
+        .map(|s| s.trim().trim_end_matches('/').to_string())
+        .filter(|s| !s.is_empty())
+    {
+        cfg.name_node = Some(name_node);
+    }
+
+    let options: HashMap<String, String> = m
+        .into_iter()
+        .filter_map(|(key, value)| {
+            key.strip_prefix(HDFS_HADOOP_CONF_PREFIX)
+                .map(|stripped| (stripped.to_string(), value))
+        })
+        .collect();
+    if !options.is_empty() {
+        cfg.options = Some(options);
+    }
+
+    Ok(cfg)
+}
+
+/// Parse an HDFS path into `Some("hdfs://<authority>")` (`None` when
+/// authority-less) and the relative path (no leading `/`, opendal style).
+pub(crate) fn hdfs_native_parse_path(path: &str) -> Result<(Option<String>, 
&str)> {
+    let url = Url::parse(path).map_err(|e| {
+        Error::new(
+            ErrorKind::DataInvalid,
+            format!("Invalid hdfs path: {path}: {e}"),
+        )
+    })?;
+    // Non-special schemes parse even without `//` (e.g. `hdfs:x` is a valid
+    // non-hierarchical URL), so require the literal prefix before slicing.
+    let (Some(after_scheme), "hdfs") = (path.strip_prefix("hdfs://"), 
url.scheme()) else {
+        return Err(Error::new(
+            ErrorKind::DataInvalid,
+            format!("Invalid hdfs path: {path}, expected scheme `hdfs://`"),
+        ));
+    };
+
+    let name_node = url.host_str().filter(|h| !h.is_empty()).map(|host| {
+        url.port()
+            .map(|port| format!("hdfs://{host}:{port}"))
+            .unwrap_or_else(|| format!("hdfs://{host}"))
+    });
+
+    // `url.path()` borrows from `url` and can't be returned with the input's
+    // lifetime. Slice the path component out of the original input instead;
+    // it starts after the first `/` following the `hdfs://` prefix. Opendal
+    // paths must not start with `/` (`Deleter::delete` rejects them).
+    let rel = match after_scheme.find('/') {
+        Some(i) => after_scheme[i..].trim_start_matches('/'),
+        None => "",
+    };
+
+    Ok((name_node, rel))
+}
+
+/// Resolves the effective NameNode for a path — the configured
+/// `hdfs.name-node` when set, else the path authority — plus the relative
+/// path. Both the operator cache and `delete_stream` batching key on this,
+/// so they cannot drift apart.
+pub(crate) fn hdfs_native_effective_name_node<'a>(
+    config: &HdfsNativeConfig,
+    path: &'a str,
+) -> Result<(String, &'a str)> {
+    let (authority_name_node, relative_path) = hdfs_native_parse_path(path)?;
+    let name_node = config
+        .name_node
+        .clone()
+        .or(authority_name_node)
+        .ok_or_else(|| {
+            Error::new(
+                ErrorKind::DataInvalid,
+                format!(
+                    "Invalid hdfs path: {path}, authority-less paths require 
the `{HDFS_NAME_NODE}` property"
+                ),
+            )
+        })?;
+    Ok((name_node, relative_path))
+}
+
+/// Operators cached per effective NameNode: each holds an `hdfs-native`
+/// client with live RPC connections, whose tasks run on the tokio runtime
+/// current when it was built.
+#[derive(Clone, Debug, Default)]
+pub struct HdfsNativeOperatorCache(Arc<RwLock<HashMap<String, Operator>>>);
+
+impl HdfsNativeOperatorCache {
+    fn get(&self, name_node: &str) -> Result<Option<Operator>> {
+        Ok(self.0.read().map_err(poisoned)?.get(name_node).cloned())
+    }
+
+    /// Inserts `op` unless a concurrent caller got there first, returning
+    /// whichever operator the cache now holds.
+    fn insert(&self, name_node: String, op: Operator) -> Result<Operator> {
+        Ok(self
+            .0
+            .write()
+            .map_err(poisoned)?
+            .entry(name_node)
+            .or_insert(op)
+            .clone())
+    }
+
+    #[cfg(test)]
+    fn len(&self) -> usize {
+        self.0.read().unwrap().len()
+    }
+}
+
+fn poisoned<T>(_: T) -> Error {
+    Error::new(ErrorKind::Unexpected, "HDFS operator cache lock poisoned")
+}
+
+/// Creates an operator for the path, reusing the cached one for its
+/// effective NameNode.
+pub(crate) fn hdfs_native_create_operator<'a>(
+    path: &'a str,
+    config: &HdfsNativeConfig,
+    operators: &HdfsNativeOperatorCache,
+) -> Result<(Operator, &'a str)> {
+    let (name_node, relative_path) = hdfs_native_effective_name_node(config, 
path)?;
+
+    if let Some(op) = operators.get(&name_node)? {
+        return Ok((op, relative_path));
+    }
+
+    // Built outside the lock: the build reads the Hadoop XML config
+    // synchronously. A racing first caller may build too; the loser is
+    // dropped before opening any connection.
+    let op = hdfs_native_operator_build(config, &name_node)?;
+    Ok((operators.insert(name_node, op)?, relative_path))
+}
+
+/// Returns the `delete_stream` grouping key for a path: the effective
+/// NameNode, so paths that resolve to different operators never share a
+/// deleter. Unresolvable paths key on themselves (as `hf_batch_key` does);
+/// `create_operator` then reports the real error.
+pub(crate) fn hdfs_native_batch_key(config: &HdfsNativeConfig, path: &str) -> 
String {
+    hdfs_native_effective_name_node(config, path)
+        .map(|(name_node, _)| name_node)
+        .unwrap_or_else(|_| path.to_string())
+}
+
+/// Build a new OpenDAL [`Operator`]: OpenDAL splits `name_node` on commas
+/// into a synthetic HA name service; `$HADOOP_CONF_DIR` XML still merges in.
+fn hdfs_native_operator_build(config: &HdfsNativeConfig, name_node: &str) -> 
Result<Operator> {
+    let mut cfg = config.clone();
+    cfg.name_node = Some(name_node.to_string());
+    Operator::from_config(cfg).map_err(from_opendal_error)

Review Comment:
   Measured it: with `HADOOP_CONF_DIR` set, `Operator::from_config` takes ~0.1 
ms (p90 116 µs, N=200), once per NameNode per storage thanks to the cache; a 
`spawn_blocking` round trip alone is ~10 µs. Nothing else runs at build, since 
connections are lazy and Kerberos setup is a no-op unless configured. The other 
backends here do comparable sync I/O on every `create_operator` call (HF reads 
the token file, fs stats the root), so I'd rather not add a tokio-specific 
offload for this one. I documented the cost at the build site instead; it will 
be in the next push together with the other fixes.



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to