varunarya002 commented on code in PR #3996:
URL: https://github.com/apache/polaris/pull/3996#discussion_r3069714595


##########
runtime/service/src/main/java/org/apache/polaris/service/storage/gcs/GcsStorageLocationPreparer.java:
##########
@@ -0,0 +1,367 @@
+/*
+ * 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.polaris.service.storage.gcs;
+
+import com.google.api.gax.rpc.AlreadyExistsException;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.cloud.storage.Bucket;
+import com.google.cloud.storage.BucketInfo;
+import com.google.cloud.storage.Storage;
+import com.google.cloud.storage.StorageOptions;
+import com.google.storage.control.v2.BucketName;
+import com.google.storage.control.v2.CreateFolderRequest;
+import com.google.storage.control.v2.StorageControlClient;
+import com.google.storage.control.v2.StorageControlSettings;
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.iceberg.TableProperties;
+import org.apache.polaris.core.entity.table.IcebergTableLikeEntity;
+import 
org.apache.polaris.core.storage.PolarisStorageConfigurationInfo.StorageType;
+import org.apache.polaris.core.storage.StorageUtil;
+import org.apache.polaris.service.storage.StorageLocationPreparer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * GCS implementation of {@link StorageLocationPreparer}. Detects whether the 
target bucket uses
+ * Hierarchical Namespace (HNS) and, if so, creates the full folder hierarchy 
required before
+ * Iceberg metadata and data files can be written. For flat-namespace buckets, 
this is a no-op.
+ *
+ * <p>The main flow uses an {@link Optional} pipeline pattern to replace 
imperative guard clauses
+ * with a declarative chain: parse location -> resolve HNS status -> create 
folders.
+ */
+public class GcsStorageLocationPreparer implements StorageLocationPreparer {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(GcsStorageLocationPreparer.class);
+  private static final String GCS_SCHEME_PREFIX = 
StorageType.GCS.getPrefixes().getFirst();
+  private static final Predicate<String> NOT_BLANK = 
Predicate.not(String::isEmpty);
+  private static final String PATH_SEPARATOR = "/";
+  private static final String TRAILING_SLASHES_REGEX = "/+$";
+  private static final String DEFAULT_METADATA_FOLDER = "metadata";
+  private static final String DEFAULT_DATA_FOLDER = "data";
+  private static final String GCS_STORAGE_LAYOUT = "_";
+
+  private final Supplier<GoogleCredentials> credentialsSupplier;
+
+  /** Represents a single folder that needs to be created, with its bucket and 
path. */
+  private record FolderToCreate(String bucketName, String folderPath) {}
+
+  public GcsStorageLocationPreparer(Supplier<GoogleCredentials> 
credentialsSupplier) {
+    this.credentialsSupplier = credentialsSupplier;
+  }
+
+  // ── Main Pipeline 
──────────────────────────────────────────────────────────
+
+  @Override
+  public void prepareTableLocation(String tableLocation, Map<String, String> 
tableProperties) {
+    if (tableLocation == null || !tableLocation.startsWith(GCS_SCHEME_PREFIX)) 
{
+      return;
+    }
+
+    List<FolderToCreate> allFolders = resolveAllFoldersToCreate(tableLocation, 
tableProperties);
+    if (allFolders.isEmpty()) {
+      return;
+    }
+
+    // Group folders by bucket and create only for HNS-enabled buckets
+    allFolders.stream()
+        .collect(Collectors.groupingBy(FolderToCreate::bucketName))
+        .forEach(this::createFoldersForBucketIfHnsEnabled);
+  }
+
+  // ── Multi-Bucket Folder Resolution ────────────────────────────────────────
+
+  /**
+   * Resolves all folders that need to be created across all buckets (table 
location + custom
+   * metadata/data paths). Each folder is tagged with its bucket for HNS 
checking and creation.
+   */
+  private List<FolderToCreate> resolveAllFoldersToCreate(
+      String tableLocation, Map<String, String> tableProperties) {
+    List<String> allPaths = resolveAllPaths(tableLocation, tableProperties);
+    List<FolderToCreate> allFolders = new ArrayList<>();
+
+    // Table location gets full hierarchy
+    allFolders.addAll(extractFoldersFromPath(tableLocation, true));
+
+    // Metadata and data paths get just their own folder
+    String metadataPath = allPaths.get(1); // Second element is metadata path
+    String dataPath = allPaths.get(2); // Third element is data path
+
+    if (!metadataPath.equals(tableLocation + PATH_SEPARATOR + 
DEFAULT_METADATA_FOLDER)) {
+      // Custom metadata path - create just this folder
+      allFolders.addAll(extractFoldersFromPath(metadataPath, false));
+    }
+
+    if (!dataPath.equals(tableLocation + PATH_SEPARATOR + 
DEFAULT_DATA_FOLDER)) {
+      // Custom data path - create just this folder
+      allFolders.addAll(extractFoldersFromPath(dataPath, false));
+    }
+
+    return allFolders;
+  }
+
+  /**
+   * Resolves all storage paths: table location + metadata path + data path. 
Custom write paths from
+   * table properties take precedence over defaults.
+   */
+  private List<String> resolveAllPaths(String tableLocation, Map<String, 
String> tableProperties) {
+    String metadataPath =
+        
Optional.ofNullable(tableProperties.get(TableProperties.WRITE_METADATA_LOCATION))
+            .or(
+                () ->
+                    Optional.ofNullable(
+                        tableProperties.get(
+                            
IcebergTableLikeEntity.USER_SPECIFIED_WRITE_METADATA_LOCATION_KEY)))

Review Comment:
   Extracted AbstractStorageLocationPreparer base class with generic URI 
parsing, hierarchy building, bucket grouping.



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