timothyw553 commented on code in PR #18987: URL: https://github.com/apache/iceberg/pull/18987#discussion_r4726530457
########## core/src/main/java/org/apache/iceberg/io/canonicaluri/PathMapper.java: ########## @@ -0,0 +1,143 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.io.Serializable; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Sets; + +final class PathMapper implements Serializable { + enum UnmatchedPolicy { + PASSTHROUGH, + FAIL + } + + private final boolean enabled; + private final UnmatchedPolicy unmatchedPolicy; + private final List<MappingRule> canonicalRules; + private final List<MappingRule> physicalRules; + + PathMapper(boolean enabled, UnmatchedPolicy unmatchedPolicy, List<MappingRule> rules) { + this.enabled = enabled; + this.unmatchedPolicy = unmatchedPolicy; + validateRules(rules); + this.canonicalRules = Lists.newArrayList(rules); + this.canonicalRules.sort(Comparator.comparingInt(MappingRule::canonicalSpecificity).reversed()); + this.physicalRules = Lists.newArrayList(rules); + this.physicalRules.sort(Comparator.comparingInt(MappingRule::physicalSpecificity).reversed()); + } + + MappingResult toPhysical(String location, boolean rejectPhysicalAlias) { + if (!enabled) { + return MappingResult.unmatched(location); + } + + ParsedLocation parsed = ParsedLocation.parse(location, "canonical location"); Review Comment: this parses every location strictly before rule matching and even when `passthrough` is enabled, so existing S3 keys with spaces, raw `%`, or brackets, scheme-less paths like `/wh/table/data/a.parquet`, and `hdfs:///...` all fail (and `toCanonical` fails on raw S3 listing keys too). could we separate endpoint matching from key handling so unmatched locations and raw key suffixes pass through unchanged? careful not to escape every `%` to `%25` since that would alter already-escaped keys. ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/ParsedLocation.java: ########## @@ -0,0 +1,165 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.io.Serializable; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; +import java.util.Objects; + +final class ParsedLocation implements Serializable { + private final String original; + private final String scheme; + private final String authority; + private final String rawPath; + + private ParsedLocation(String original, String scheme, String authority, String rawPath) { + this.original = original; + this.scheme = scheme; + this.authority = authority; + this.rawPath = rawPath; + } + + static ParsedLocation parse(String location, String description) { + if (location == null || location.isEmpty()) { + throw new IllegalArgumentException("Invalid " + description + ": location is empty"); + } + + URI uri = toUri(location, description); + validateHierarchicalUri(uri, description); + + String normalizedScheme = uri.getScheme().toLowerCase(Locale.ROOT); + String rawAuthority = uri.getRawAuthority(); + String path = uri.getRawPath() == null ? "" : uri.getRawPath(); + String decodedPath = uri.getPath() == null ? "" : uri.getPath(); Review Comment: decoding before `validatePath` turns escaped partition data like `col=a%2F..%2Fb` into path separators and rejects locations that iceberg's default location provider can write. could we validate the raw path instead and update the rejection tests so encoded partition values and literal traversal segments are tested separately? ```diff String path = uri.getRawPath() == null ? "" : uri.getRawPath(); -String decodedPath = uri.getPath() == null ? "" : uri.getPath(); -validatePath(decodedPath, description); +validatePath(path, description); ``` ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/CanonicalUriFileIO.java: ########## @@ -0,0 +1,325 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.Function; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.hadoop.HadoopConfigurable; +import org.apache.iceberg.hadoop.SerializableConfiguration; +import org.apache.iceberg.io.BulkDeletionFailureException; +import org.apache.iceberg.io.DelegateFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.io.FileInfo; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.util.SerializableMap; +import org.apache.iceberg.util.SerializableSupplier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A FileIO that preserves canonical Iceberg locations while accessing translated storage URIs. + * + * <p>Rules use deterministic longest-prefix matching. Translation is syntactic and does not issue + * storage or catalog requests. + */ +public final class CanonicalUriFileIO implements DelegateFileIO, HadoopConfigurable { Review Comment: because `CanonicalUriFileIO` doesn't implement `SupportsStorageCredentials`, catalog and REST credential vending skips it and the delegate loads without credentials. should we implement credential storage and forwarding here, including credentials passed before init and later updates? we'd also need to define whether `StorageCredential.prefix()` uses canonical or physical prefixes and how to translate or reject ambiguous ones. ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/CanonicalSeekableInputStream.java: ########## @@ -0,0 +1,108 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.io.IOException; +import org.apache.iceberg.io.RangeReadable; +import org.apache.iceberg.io.SeekableInputStream; + +/** Retains a delegate stream without exposing it for downstream adapter unwrapping. */ +class CanonicalSeekableInputStream extends SeekableInputStream { + private final SeekableInputStream delegate; + + static SeekableInputStream wrap(SeekableInputStream delegate) { + return delegate instanceof RangeReadable + ? new CanonicalRangeReadableInputStream(delegate) + : new CanonicalSeekableInputStream(delegate); + } + + private CanonicalSeekableInputStream(SeekableInputStream delegate) { + this.delegate = delegate; + } + + @Override + public long getPos() throws IOException { + return delegate.getPos(); + } + + @Override + public void seek(long newPos) throws IOException { + delegate.seek(newPos); + } + + @Override + public int read() throws IOException { + return delegate.read(); + } + + @Override + public int read(byte[] buffer, int off, int len) throws IOException { + return delegate.read(buffer, off, len); + } + + @Override + public long skip(long length) throws IOException { + return delegate.skip(length); + } + + @Override + public int available() throws IOException { + return delegate.available(); + } + + @Override + public void mark(int readLimit) { + delegate.mark(readLimit); + } + + @Override + public void reset() throws IOException { + delegate.reset(); + } + + @Override + public boolean markSupported() { + return delegate.markSupported(); + } + + @Override + public void close() throws IOException { + delegate.close(); + } + + private static class CanonicalRangeReadableInputStream extends CanonicalSeekableInputStream + implements RangeReadable { Review Comment: this doesn't override `readVectored`, so direct-buffer calls hit `RangeReadable`'s default and throw `UnsupportedOperationException`, and heap buffers lose the delegate's vectored path. could we forward it and add tests for both direct and heap buffers? ```diff + @Override + public void readVectored(List<FileRange> ranges, IntFunction<ByteBuffer> allocate) + throws IOException { + rangeDelegate.readVectored(ranges, allocate); + } ``` ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/ParsedLocation.java: ########## @@ -0,0 +1,165 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.io.Serializable; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; +import java.util.Objects; + +final class ParsedLocation implements Serializable { + private final String original; + private final String scheme; + private final String authority; + private final String rawPath; + + private ParsedLocation(String original, String scheme, String authority, String rawPath) { + this.original = original; + this.scheme = scheme; + this.authority = authority; + this.rawPath = rawPath; + } + + static ParsedLocation parse(String location, String description) { + if (location == null || location.isEmpty()) { + throw new IllegalArgumentException("Invalid " + description + ": location is empty"); + } + + URI uri = toUri(location, description); + validateHierarchicalUri(uri, description); + + String normalizedScheme = uri.getScheme().toLowerCase(Locale.ROOT); + String rawAuthority = uri.getRawAuthority(); + String path = uri.getRawPath() == null ? "" : uri.getRawPath(); + String decodedPath = uri.getPath() == null ? "" : uri.getPath(); + validatePath(decodedPath, description); + + return new ParsedLocation(location, normalizedScheme, rawAuthority, path); + } + + private static URI toUri(String location, String description) { + try { + return new URI(location); + } catch (URISyntaxException e) { + throw new IllegalArgumentException( + "Invalid " + description + " URI: " + sanitize(location), e); + } + } + + private static void validateHierarchicalUri(URI uri, String description) { + if (!uri.isAbsolute() || uri.isOpaque()) { + throw new IllegalArgumentException( + "Invalid " + description + " URI: must be an absolute hierarchical URI"); + } + + if (uri.getRawQuery() != null) { + throw new IllegalArgumentException("Invalid " + description + " URI: query is not allowed"); + } + + if (uri.getRawFragment() != null) { + throw new IllegalArgumentException( + "Invalid " + description + " URI: fragment is not allowed"); + } + + String normalizedScheme = uri.getScheme().toLowerCase(Locale.ROOT); + String rawAuthority = uri.getRawAuthority(); + if (rawAuthority == null && !"file".equals(normalizedScheme)) { + throw new IllegalArgumentException("Invalid " + description + " URI: authority is required"); + } + + if (uri.getRawUserInfo() != null || (rawAuthority != null && rawAuthority.contains("@"))) { Review Comment: azure authorities use `container@account`, so this rejects `abfss://` and `wasbs://` both as mapping prefixes and as unmatched `passthrough` locations. should we allow `@` in the authority for `abfs`, `abfss`, `wasb`, and `wasbs` while keeping user-info checks for other schemes, and add azure tests? ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/CanonicalUriFileIO.java: ########## @@ -0,0 +1,325 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.Function; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.hadoop.HadoopConfigurable; +import org.apache.iceberg.hadoop.SerializableConfiguration; +import org.apache.iceberg.io.BulkDeletionFailureException; +import org.apache.iceberg.io.DelegateFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.io.FileInfo; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.util.SerializableMap; +import org.apache.iceberg.util.SerializableSupplier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A FileIO that preserves canonical Iceberg locations while accessing translated storage URIs. + * + * <p>Rules use deterministic longest-prefix matching. Translation is syntactic and does not issue + * storage or catalog requests. + */ +public final class CanonicalUriFileIO implements DelegateFileIO, HadoopConfigurable { + private static final Logger LOG = LoggerFactory.getLogger(CanonicalUriFileIO.class); + + private SerializableMap<String, String> properties = + SerializableMap.copyOf(Collections.emptyMap()); + private SerializableSupplier<Configuration> hadoopConf; + private PathAliasConfig config; + private PathAliasMetrics metrics = new PathAliasMetrics(false); + private transient volatile DelegateFileIO delegate; + private volatile boolean closed; + + /** Constructor used for dynamic FileIO loading. */ + public CanonicalUriFileIO() {} + + @Override + public InputFile newInputFile(String location) { + metrics.read(); + MappingResult mapped = translate(location, false, "read"); + InputFile physical = invoke(() -> delegate().newInputFile(mapped.location())); + return CanonicalInputFile.wrap(location, physical, metrics); + } + + @Override + public InputFile newInputFile(String location, long length) { + metrics.read(); + MappingResult mapped = translate(location, false, "read"); + InputFile physical = invoke(() -> delegate().newInputFile(mapped.location(), length)); + return CanonicalInputFile.wrap(location, physical, metrics); + } + + @Override + public OutputFile newOutputFile(String location) { + metrics.write(); + MappingResult mapped = translate(location, true, "write"); + OutputFile physical = invoke(() -> delegate().newOutputFile(mapped.location())); + return CanonicalOutputFile.wrap(location, physical, metrics); + } + + @Override + public void deleteFile(String location) { + metrics.delete(); + MappingResult mapped = translate(location, true, "delete"); + invokeVoid(() -> delegate().deleteFile(mapped.location())); + } + + @Override + public void deleteFiles(Iterable<String> pathsToDelete) throws BulkDeletionFailureException { + metrics.bulkDelete(); + List<String> physicalPaths = Lists.newArrayList(); + for (String path : pathsToDelete) { + physicalPaths.add(translate(path, true, "bulk-delete").location()); + } + + invokeVoid(() -> delegate().deleteFiles(physicalPaths)); + } + + @Override + public Iterable<FileInfo> listPrefix(String prefix) { + metrics.listPrefix(); + MappingResult mappedPrefix = translate(prefix, false, "list-prefix"); + Iterable<FileInfo> physicalFiles = invoke(() -> delegate().listPrefix(mappedPrefix.location())); + return () -> new CanonicalFileInfoIterator(physicalFiles.iterator(), mappedPrefix.rule()); + } + + @Override + public void deletePrefix(String prefix) { + metrics.deletePrefix(); + MappingResult mapped = translate(prefix, true, "delete-prefix"); + invokeVoid(() -> delegate().deletePrefix(mapped.location())); + } + + @Override + public Map<String, String> properties() { + return properties.immutableMap(); + } + + @Override + public synchronized void initialize(Map<String, String> newProperties) { + if (config != null) { + throw new IllegalStateException("CanonicalUriFileIO is already initialized"); + } + + PathAliasConfig newConfig = PathAliasConfig.from(newProperties); + if (getClass().getName().equals(newConfig.delegateImpl())) { + throw new IllegalArgumentException( + "Invalid pathalias.delegate.impl: CanonicalUriFileIO cannot delegate to itself"); + } + + closeDelegate(); + this.properties = SerializableMap.copyOf(newProperties); + this.config = newConfig; + this.metrics = new PathAliasMetrics(newConfig.metricsEnabled()); + this.closed = false; + + LOG.info( + "Initialized CanonicalUriFileIO with {} rules, delegate {}, enabled {}", + newConfig.mapper().ruleCount(), + newConfig.delegateImpl(), + newConfig.enabled()); + } + + /** + * Returns counters for translation and delegated operations. + * + * @return this instance's operation counters + */ + public PathAliasMetrics metrics() { + return metrics; + } + + @Override + public synchronized void close() { + closeDelegate(); + this.closed = true; + } + + @Override + public synchronized void setConf(Configuration conf) { + this.hadoopConf = conf == null ? null : new SerializableConfiguration(conf)::get; + if (delegate != null) { + CatalogUtil.configureHadoopConf(delegate, conf); + } + } + + @Override + public Configuration getConf() { + return hadoopConf == null ? null : hadoopConf.get(); + } + + @Override + public void serializeConfWith( + Function<Configuration, SerializableSupplier<Configuration>> confSerializer) { + this.hadoopConf = confSerializer.apply(getConf()); + } + + private MappingResult translate(String location, boolean rejectPhysicalAlias, String operation) { + ensureOpenAndInitialized(); + long start = System.nanoTime(); + try { + MappingResult result = config.mapper().toPhysical(location, rejectPhysicalAlias); + metrics.translated(result.mapped(), System.nanoTime() - start); + if (LOG.isDebugEnabled() && result.mapped()) { + if (config.debugLogPhysicalPaths()) { + LOG.debug( + "Mapped canonical location for {} using rule {}: canonical={}, physical={}", + operation, + result.rule().id(), + location, + result.location()); + } else { + LOG.debug( + "Mapped canonical location for {} using rule {}", operation, result.rule().id()); + } + } + + return result; + } catch (RuntimeException e) { + metrics.translationFailed(System.nanoTime() - start); + throw e; + } + } + + private String toCanonical(String location, MappingRule expectedRule) { + long start = System.nanoTime(); + try { + MappingResult result = config.mapper().toCanonical(location); + metrics.translated(result.mapped(), System.nanoTime() - start); + if (expectedRule != null && result.rule() != expectedRule) { + throw new IllegalStateException( + "Delegate returned a location outside the mapped physical prefix"); + } + + return result.location(); + } catch (RuntimeException e) { + metrics.translationFailed(System.nanoTime() - start); + throw e; + } + } + + private DelegateFileIO delegate() { + ensureOpenAndInitialized(); + DelegateFileIO current = delegate; + if (current == null) { + synchronized (this) { Review Comment: could a thread pass `ensureOpenAndInitialized()` here, wait for `close()`, and then create a delegate that never gets closed? we can recheck inside the lock and mark `closed = true` before `closeDelegate()`. ```diff public synchronized void close() { - closeDelegate(); this.closed = true; + closeDelegate(); } ``` ```diff synchronized (this) { + ensureOpenAndInitialized(); current = delegate; ``` ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/PathAliasProperties.java: ########## @@ -0,0 +1,73 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +/** Configuration properties for {@link CanonicalUriFileIO}. */ +public final class PathAliasProperties { + /** Enables or disables location mapping. */ + public static final String ENABLED = "pathalias.enabled"; + + /** Default value for {@link #ENABLED}. */ + public static final boolean ENABLED_DEFAULT = true; + + /** Prefix for indexed mapping-rule properties. */ + public static final String RULE_PREFIX = "pathalias.rule."; + + /** Delegate {@code FileIO} implementation class. */ + public static final String DELEGATE_IMPL = "pathalias.delegate.impl"; + + /** Default value for {@link #DELEGATE_IMPL}. */ + public static final String DELEGATE_IMPL_DEFAULT = "org.apache.iceberg.io.ResolvingFileIO"; + + /** Policy for locations that do not match a rule. */ + public static final String UNMATCHED = "pathalias.unmatched"; + + /** Default value for {@link #UNMATCHED}. */ + public static final String UNMATCHED_DEFAULT = "passthrough"; + + /** Write mapping policy. */ Review Comment: there are no user docs for `pathalias.*`, `write-mode` only accepts `strict`, `read-failover` only accepts `false`, and the PR claims relative-path support even though `ParsedLocation` and the test vectors reject them. could we remove the unimplemented switches (or mark them reserved), add a minimal config doc, and update the PR description? ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/PathMapper.java: ########## @@ -0,0 +1,143 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.io.Serializable; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Sets; + +final class PathMapper implements Serializable { + enum UnmatchedPolicy { + PASSTHROUGH, + FAIL + } + + private final boolean enabled; + private final UnmatchedPolicy unmatchedPolicy; + private final List<MappingRule> canonicalRules; + private final List<MappingRule> physicalRules; + + PathMapper(boolean enabled, UnmatchedPolicy unmatchedPolicy, List<MappingRule> rules) { + this.enabled = enabled; + this.unmatchedPolicy = unmatchedPolicy; + validateRules(rules); + this.canonicalRules = Lists.newArrayList(rules); + this.canonicalRules.sort(Comparator.comparingInt(MappingRule::canonicalSpecificity).reversed()); + this.physicalRules = Lists.newArrayList(rules); + this.physicalRules.sort(Comparator.comparingInt(MappingRule::physicalSpecificity).reversed()); + } + + MappingResult toPhysical(String location, boolean rejectPhysicalAlias) { + if (!enabled) { + return MappingResult.unmatched(location); + } + + ParsedLocation parsed = ParsedLocation.parse(location, "canonical location"); + for (MappingRule rule : canonicalRules) { + String mapped = rule.mapToPhysical(parsed); + if (mapped != null) { + return MappingResult.mapped(mapped, rule); + } + } + + if (rejectPhysicalAlias) { + for (MappingRule rule : physicalRules) { + if (rule.matchesPhysical(parsed)) { + throw new IllegalArgumentException( + "Invalid canonical location: physical alias is not allowed in strict mode"); + } + } + } + + if (unmatchedPolicy == UnmatchedPolicy.FAIL) { + throw new IllegalArgumentException( + "No path alias rule matches canonical location: " + location); + } + + return MappingResult.unmatched(location); + } + + MappingResult toCanonical(String location) { + if (!enabled) { + return MappingResult.unmatched(location); + } + + ParsedLocation parsed = ParsedLocation.parse(location, "physical location"); + for (MappingRule rule : physicalRules) { Review Comment: since nested canonical rules are allowed, a physical path can reverse-map through the parent rule and then forward-map through a nested child rule to a different location, while parent `listPrefix`/`deletePrefix` only visits the parent's physical prefix. should we reject nested canonical prefixes for now, or handle shadowed paths and child mappings explicitly? ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/MappingRule.java: ########## @@ -0,0 +1,147 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.io.Serializable; + +final class MappingRule implements Serializable { + private final String id; + private final ParsedLocation canonical; + private final ParsedLocation physical; + private final String canonicalBasePath; + private final String physicalBasePath; + + MappingRule(String id, String canonicalPrefix, String physicalPrefix) { + if (id == null || id.isEmpty()) { + throw new IllegalArgumentException("Invalid mapping rule: ID is empty"); + } + + this.id = id; + this.canonical = ParsedLocation.parse(canonicalPrefix, "canonical prefix for rule " + id); + this.physical = ParsedLocation.parse(physicalPrefix, "physical prefix for rule " + id); + this.canonicalBasePath = basePath(canonical.rawPath()); + this.physicalBasePath = basePath(physical.rawPath()); + } + + String id() { + return id; + } + + int canonicalSpecificity() { + return canonicalBasePath.length(); + } + + int physicalSpecificity() { + return physicalBasePath.length(); + } + + String canonicalKey() { + return key(canonical, canonicalBasePath); + } + + String physicalKey() { + return key(physical, physicalBasePath); + } + + boolean physicalOverlaps(MappingRule other) { + return physical.hasSameEndpoint(other.physical) + && pathsOverlap(physicalBasePath, other.physicalBasePath); + } + + boolean canonicalOverlapsPhysical(MappingRule other) { + return canonical.hasSameEndpoint(other.physical) + && pathsOverlap(canonicalBasePath, other.physicalBasePath); + } + + String mapToPhysical(ParsedLocation location) { + String suffix = suffix(canonical, canonicalBasePath, location); + return suffix == null ? null : physical.withRawPath(join(physicalBasePath, suffix, location)); + } + + String mapToCanonical(ParsedLocation location) { + String suffix = suffix(physical, physicalBasePath, location); + return suffix == null ? null : canonical.withRawPath(join(canonicalBasePath, suffix, location)); + } + + boolean matchesPhysical(ParsedLocation location) { + return suffix(physical, physicalBasePath, location) != null; + } + + private static String suffix( + ParsedLocation prefix, String prefixBasePath, ParsedLocation location) { + if (!prefix.hasSameEndpoint(location)) { + return null; + } + + String locationPath = location.rawPath(); + if (prefixBasePath.isEmpty()) { + return locationPath.startsWith("/") ? locationPath.substring(1) : locationPath; + } + + if (locationPath.equals(prefixBasePath)) { + return ""; + } + + String prefixWithSeparator = prefixBasePath + "/"; + return locationPath.startsWith(prefixWithSeparator) + ? locationPath.substring(prefixWithSeparator.length()) + : null; + } + + private static String join(String targetBasePath, String suffix, ParsedLocation sourceLocation) { + if (suffix.isEmpty()) { + if (sourceLocation.rawPath().endsWith("/") && !targetBasePath.endsWith("/")) { + return targetBasePath + "/"; + } + Review Comment: if the target root is `/` (`targetBasePath` is `""`) and `suffix` is empty, `withRawPath("")` produces `file:` without a path, and other mappings turn `file:///canon/x` into `file:/canon/x`. should we preserve `/` for a root target, standardize the `file` URI output form, and test exact roots with and without trailing slashes? ########## core/src/main/java/org/apache/iceberg/io/canonicaluri/CanonicalUriFileIO.java: ########## @@ -0,0 +1,325 @@ +/* + * 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. + */ +package org.apache.iceberg.io.canonicaluri; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.Function; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.hadoop.HadoopConfigurable; +import org.apache.iceberg.hadoop.SerializableConfiguration; +import org.apache.iceberg.io.BulkDeletionFailureException; +import org.apache.iceberg.io.DelegateFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.io.FileInfo; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.util.SerializableMap; +import org.apache.iceberg.util.SerializableSupplier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A FileIO that preserves canonical Iceberg locations while accessing translated storage URIs. + * + * <p>Rules use deterministic longest-prefix matching. Translation is syntactic and does not issue + * storage or catalog requests. + */ +public final class CanonicalUriFileIO implements DelegateFileIO, HadoopConfigurable { + private static final Logger LOG = LoggerFactory.getLogger(CanonicalUriFileIO.class); + + private SerializableMap<String, String> properties = + SerializableMap.copyOf(Collections.emptyMap()); + private SerializableSupplier<Configuration> hadoopConf; + private PathAliasConfig config; + private PathAliasMetrics metrics = new PathAliasMetrics(false); + private transient volatile DelegateFileIO delegate; + private volatile boolean closed; + + /** Constructor used for dynamic FileIO loading. */ + public CanonicalUriFileIO() {} + + @Override + public InputFile newInputFile(String location) { + metrics.read(); + MappingResult mapped = translate(location, false, "read"); + InputFile physical = invoke(() -> delegate().newInputFile(mapped.location())); + return CanonicalInputFile.wrap(location, physical, metrics); + } + + @Override + public InputFile newInputFile(String location, long length) { + metrics.read(); + MappingResult mapped = translate(location, false, "read"); + InputFile physical = invoke(() -> delegate().newInputFile(mapped.location(), length)); + return CanonicalInputFile.wrap(location, physical, metrics); + } + + @Override + public OutputFile newOutputFile(String location) { + metrics.write(); + MappingResult mapped = translate(location, true, "write"); + OutputFile physical = invoke(() -> delegate().newOutputFile(mapped.location())); + return CanonicalOutputFile.wrap(location, physical, metrics); + } + + @Override + public void deleteFile(String location) { + metrics.delete(); + MappingResult mapped = translate(location, true, "delete"); + invokeVoid(() -> delegate().deleteFile(mapped.location())); + } + + @Override + public void deleteFiles(Iterable<String> pathsToDelete) throws BulkDeletionFailureException { + metrics.bulkDelete(); + List<String> physicalPaths = Lists.newArrayList(); + for (String path : pathsToDelete) { + physicalPaths.add(translate(path, true, "bulk-delete").location()); + } + + invokeVoid(() -> delegate().deleteFiles(physicalPaths)); + } + + @Override + public Iterable<FileInfo> listPrefix(String prefix) { + metrics.listPrefix(); + MappingResult mappedPrefix = translate(prefix, false, "list-prefix"); + Iterable<FileInfo> physicalFiles = invoke(() -> delegate().listPrefix(mappedPrefix.location())); + return () -> new CanonicalFileInfoIterator(physicalFiles.iterator(), mappedPrefix.rule()); + } + + @Override + public void deletePrefix(String prefix) { + metrics.deletePrefix(); + MappingResult mapped = translate(prefix, true, "delete-prefix"); Review Comment: to my understanding, mapping checks directory boundaries while S3 prefix deletion matches raw string prefixes. with rules targeting `s3://phys/zz` and `s3://phys/zz2`, deleting the slashless root `zz` would also delete `zz2/g1`, and `listPrefix` has the same boundary mismatch. should we reject slashless prefixes at mapped rule roots unless they end in `/`? -- 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]
