singhpk234 commented on code in PR #17457:
URL: https://github.com/apache/iceberg/pull/17457#discussion_r3754149542


##########
aws/src/main/java/org/apache/iceberg/aws/s3/S3FileIO.java:
##########
@@ -149,12 +153,16 @@ public S3FileIO(SerializableSupplier<S3Client> s3, 
SerializableSupplier<S3AsyncC
 
   @Override
   public InputFile newInputFile(String path) {
-    return S3InputFile.fromLocation(path, clientForStoragePath(path), metrics);
+    return HttpUrlSupport.isHttpUrl(path)
+        ? httpUrlSupport().newInputFile(path, metrics)

Review Comment:
   lets add assertion here that this http url belongs to s3, since this is 
s3FileIO



##########
core/src/main/java/org/apache/iceberg/io/http/HTTPInputFile.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.http;
+
+import java.io.IOException;
+import java.util.Locale;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.exceptions.RuntimeIOException;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.SeekableInputStream;
+import org.apache.iceberg.metrics.MetricsContext;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+
+/**
+ * An {@link InputFile} backed by an HTTP URL, typically a pre-signed 
object-store URL that encodes
+ * auth in its query parameters.
+ *
+ * <p>A known content length is returned directly; otherwise it is fetched 
lazily via a {@code GET
+ * Range: bytes=0-0} request, which (unlike HEAD) works with pre-signed GET 
URLs.
+ */
+class HTTPInputFile implements InputFile {
+  private static final long UNKNOWN_LENGTH = -1L;
+
+  private final CloseableHttpClient client;
+  private final String location;
+  private final String url;
+  private final MetricsContext metrics;
+
+  private long length;
+
+  HTTPInputFile(CloseableHttpClient client, String location, String url, 
MetricsContext metrics) {
+    this(client, location, url, UNKNOWN_LENGTH, metrics);
+  }
+
+  HTTPInputFile(
+      CloseableHttpClient client,
+      String location,
+      String url,
+      long length,
+      MetricsContext metrics) {
+    Preconditions.checkNotNull(client, "Invalid HTTP client: null");
+    Preconditions.checkNotNull(location, "Invalid location: null");
+    Preconditions.checkNotNull(url, "Invalid url: null");
+    Preconditions.checkNotNull(metrics, "Invalid metrics context: null");
+    this.client = client;
+    this.location = location;
+    this.url = url;
+    this.length = length;
+    this.metrics = metrics;
+  }
+
+  @Override
+  public long getLength() {
+    if (length == UNKNOWN_LENGTH) {
+      this.length = fetchContentLength();
+    }
+
+    return length;
+  }
+
+  @Override
+  public SeekableInputStream newStream() {
+    return new HTTPInputStream(client, location, url, metrics);
+  }
+
+  @Override
+  public String location() {
+    return location;
+  }
+
+  @Override
+  public boolean exists() {
+    try {
+      HttpGet request = new HttpGet(url);
+      request.setHeader(HttpHeaders.RANGE, "bytes=0-0");
+      int statusCode = client.execute(request, ClassicHttpResponse::getCode);
+      return statusCode == HttpStatus.SC_PARTIAL_CONTENT || statusCode == 
HttpStatus.SC_OK;
+    } catch (IOException e) {
+      throw new RuntimeIOException(e, "Failed to check existence of %s", 
location);
+    }
+  }
+
+  /**
+   * Fetches the content length via {@code GET Range: bytes=0-0}, reading the 
total from the {@code
+   * Content-Range} header. Works with pre-signed GET URLs, unlike a {@code 
HEAD} request.
+   */
+  private long fetchContentLength() {
+    try {
+      HttpGet request = new HttpGet(url);
+      request.setHeader(HttpHeaders.RANGE, "bytes=0-0");
+
+      return client.execute(
+          request,
+          response -> {
+            int statusCode = response.getCode();
+
+            if (statusCode == HttpStatus.SC_NOT_FOUND) {
+              throw new NotFoundException("Location does not exist: %s", 
location);
+            }
+
+            // 206 Partial Content: parse total from "Content-Range: bytes 
0-0/TOTAL"
+            if (statusCode == HttpStatus.SC_PARTIAL_CONTENT) {
+              Header contentRange = response.getFirstHeader("Content-Range");
+              if (contentRange != null) {
+                long total = 
parseTotalFromContentRange(contentRange.getValue());
+                if (total >= 0) {
+                  return total;
+                }
+              }
+
+              return UNKNOWN_LENGTH;
+            }
+
+            // 200 OK: server returned full content, use Content-Length
+            if (statusCode == HttpStatus.SC_OK) {
+              return parseLengthFrom200(response);
+            }
+
+            throw new IOException(
+                String.format(Locale.ROOT, "Unexpected HTTP %d for %s", 
statusCode, url));
+          });
+    } catch (IOException e) {
+      throw new RuntimeIOException(e, "Failed to fetch content length for %s", 
location);
+    }
+  }
+
+  /** Extracts content length from a 200 response via entity or {@code 
Content-Length} header. */
+  private static long parseLengthFrom200(ClassicHttpResponse response) {
+    long contentLength =
+        response.getEntity() != null ? response.getEntity().getContentLength() 
: UNKNOWN_LENGTH;
+    if (contentLength >= 0) {
+      return contentLength;
+    }
+
+    Header header = response.getFirstHeader("Content-Length");
+    if (header != null) {
+      try {
+        return Long.parseLong(header.getValue());
+      } catch (NumberFormatException e) {
+        // fall through to UNKNOWN_LENGTH
+      }
+    }
+
+    return UNKNOWN_LENGTH;
+  }

Review Comment:
   same as below, can we move this to utils class ?



##########
core/src/main/java/org/apache/iceberg/io/http/HTTPInputStream.java:
##########
@@ -0,0 +1,259 @@
+/*
+ * 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.http;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.util.Arrays;
+import java.util.Locale;
+import javax.net.ssl.SSLException;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.io.FileIOMetricsContext;
+import org.apache.iceberg.io.RangeReadable;
+import org.apache.iceberg.io.SeekableInputStream;
+import org.apache.iceberg.metrics.Counter;
+import org.apache.iceberg.metrics.MetricsContext;
+import org.apache.iceberg.metrics.MetricsContext.Unit;
+import 
org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Joiner;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link SeekableInputStream} that reads an HTTP URL via range GETs, for 
pre-signed object-store
+ * URLs that need no object-store credentials on the reader.
+ *
+ * <p>Sequential reads are served from a fixed-size in-memory chunk buffer, 
each chunk fetched with
+ * a single range GET fully consumed within the response handler so 
connections return to the pool.
+ * Positional reads ({@link #readFully}, {@link #readTail}) each issue their 
own range GET.
+ *
+ * <p>Transient socket/TLS errors and 5xx responses are retried up to {@value 
#MAX_RETRIES} times;
+ * any other unexpected status (e.g. an expired pre-signed URL) fails 
immediately.
+ */
+class HTTPInputStream extends SeekableInputStream implements RangeReadable {
+  private static final Logger LOG = 
LoggerFactory.getLogger(HTTPInputStream.class);
+
+  @VisibleForTesting static final int CHUNK_SIZE = 4 * 1024 * 1024; // 4 MB
+  private static final int MAX_RETRIES = 3;
+
+  private final StackTraceElement[] createStack;
+  private final CloseableHttpClient client;
+  private final String location;
+  private final String url;
+
+  private final Counter readBytes;
+  private final Counter readOperations;
+
+  /** Cached chunk buffer. {@code bufferFileStart} is the file offset of 
{@code buffer[0]}. */
+  private byte[] buffer;
+
+  private long bufferFileStart = -1L;
+  private int bufferLimit = 0;
+
+  private long next = 0;
+  private boolean closed = false;
+
+  HTTPInputStream(CloseableHttpClient client, String location, String url, 
MetricsContext metrics) {
+    this.client = client;
+    this.location = location;
+    this.url = url;
+    this.readBytes = metrics.counter(FileIOMetricsContext.READ_BYTES, 
Unit.BYTES);
+    this.readOperations = 
metrics.counter(FileIOMetricsContext.READ_OPERATIONS);
+    this.createStack = Thread.currentThread().getStackTrace();
+  }
+
+  @Override
+  public long getPos() {
+    return next;
+  }
+
+  @Override
+  public void seek(long newPos) {
+    Preconditions.checkState(!closed, "Cannot seek: already closed");
+    Preconditions.checkArgument(newPos >= 0, "position is negative: %s", 
newPos);
+    next = newPos;
+  }
+
+  @Override
+  public int read() throws IOException {
+    Preconditions.checkState(!closed, "Cannot read: already closed");
+    ensureBuffered();
+
+    if (buffer == null || !inBuffer(next)) {
+      return -1; // EOF
+    }
+
+    int bufPos = (int) (next - bufferFileStart);
+    next += 1;
+    readBytes.increment();
+    readOperations.increment();
+    return buffer[bufPos] & 0xFF;
+  }
+
+  @Override
+  public int read(byte[] b, int off, int len) throws IOException {
+    Preconditions.checkState(!closed, "Cannot read: already closed");
+    if (len == 0) {
+      return 0;
+    }
+
+    ensureBuffered();
+
+    if (buffer == null || !inBuffer(next)) {
+      return -1; // EOF
+    }
+
+    int bufPos = (int) (next - bufferFileStart);
+    int available = bufferLimit - bufPos;
+    int toCopy = Math.min(len, available);
+    System.arraycopy(buffer, bufPos, b, off, toCopy);
+    next += toCopy;
+    readBytes.increment(toCopy);
+    readOperations.increment();
+    return toCopy;
+  }
+
+  @Override
+  public void readFully(long position, byte[] out, int offset, int length) 
throws IOException {
+    Preconditions.checkPositionIndexes(offset, offset + length, out.length);
+    String range = String.format(Locale.ROOT, "bytes=%s-%s", position, 
position + length - 1);
+    byte[] data = fetchRange(range);
+    if (data.length < length) {
+      throw new EOFException(
+          "Reached end of " + location + " with " + (length - data.length) + " 
bytes left to read");
+    }
+
+    System.arraycopy(data, 0, out, offset, length);
+  }
+
+  @Override
+  public int readTail(byte[] out, int offset, int length) throws IOException {
+    Preconditions.checkPositionIndexes(offset, offset + length, out.length);
+    String range = String.format(Locale.ROOT, "bytes=-%s", length);
+    byte[] data = fetchRange(range);
+    int toCopy = Math.min(data.length, length);
+    System.arraycopy(data, 0, out, offset, toCopy);
+    return toCopy;
+  }
+
+  @Override
+  public void close() throws IOException {
+    super.close();
+    closed = true;
+    buffer = null;
+  }
+
+  private boolean inBuffer(long filePos) {
+    return filePos >= bufferFileStart && filePos < bufferFileStart + 
bufferLimit;
+  }
+
+  /**
+   * Ensures the buffer covers {@code next}. Issues a new range GET if {@code 
next} is outside the
+   * current buffer window.
+   */
+  private void ensureBuffered() throws IOException {
+    if (buffer != null && inBuffer(next)) {
+      return;
+    }
+
+    // Fetch a new chunk starting at the current position.
+    String range = String.format(Locale.ROOT, "bytes=%s-%s", next, next + 
CHUNK_SIZE - 1);
+    byte[] data = fetchRange(range);
+    if (data == null || data.length == 0) {
+      buffer = null;
+      return;
+    }
+
+    buffer = data;
+    bufferFileStart = next;
+    bufferLimit = data.length;
+  }
+
+  /** Fetches a byte range from the URL, with retries on transient network and 
server errors. */
+  private byte[] fetchRange(String range) throws IOException {
+    IOException lastException = null;
+    for (int attempt = 0; attempt <= MAX_RETRIES; attempt++) {
+      try {
+        return doFetchRange(range, url);
+      } catch (TransientHttpException | SocketException | 
SocketTimeoutException | SSLException e) {
+        lastException = e;
+        LOG.warn(
+            "Retrying range fetch for {} range={} (attempt {})", location, 
range, attempt + 1, e);
+      }
+    }
+
+    throw lastException;
+  }
+
+  private byte[] doFetchRange(String range, String requestUrl) throws 
IOException {
+    HttpGet request = new HttpGet(requestUrl);
+    request.setHeader(HttpHeaders.RANGE, range);
+
+    return client.execute(

Review Comment:
   > I'd propose factoring out all handling of s3 error codes into one place
   
   make sense to me 



##########
core/src/main/java/org/apache/iceberg/io/http/HTTPInputFile.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.http;
+
+import java.io.IOException;
+import java.util.Locale;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.exceptions.RuntimeIOException;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.SeekableInputStream;
+import org.apache.iceberg.metrics.MetricsContext;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+
+/**
+ * An {@link InputFile} backed by an HTTP URL, typically a pre-signed 
object-store URL that encodes
+ * auth in its query parameters.
+ *
+ * <p>A known content length is returned directly; otherwise it is fetched 
lazily via a {@code GET
+ * Range: bytes=0-0} request, which (unlike HEAD) works with pre-signed GET 
URLs.
+ */
+class HTTPInputFile implements InputFile {
+  private static final long UNKNOWN_LENGTH = -1L;
+
+  private final CloseableHttpClient client;
+  private final String location;
+  private final String url;
+  private final MetricsContext metrics;
+
+  private long length;
+
+  HTTPInputFile(CloseableHttpClient client, String location, String url, 
MetricsContext metrics) {
+    this(client, location, url, UNKNOWN_LENGTH, metrics);
+  }
+
+  HTTPInputFile(
+      CloseableHttpClient client,
+      String location,
+      String url,
+      long length,
+      MetricsContext metrics) {
+    Preconditions.checkNotNull(client, "Invalid HTTP client: null");
+    Preconditions.checkNotNull(location, "Invalid location: null");
+    Preconditions.checkNotNull(url, "Invalid url: null");
+    Preconditions.checkNotNull(metrics, "Invalid metrics context: null");
+    this.client = client;
+    this.location = location;
+    this.url = url;
+    this.length = length;
+    this.metrics = metrics;
+  }
+
+  @Override
+  public long getLength() {
+    if (length == UNKNOWN_LENGTH) {
+      this.length = fetchContentLength();
+    }
+
+    return length;
+  }
+
+  @Override
+  public SeekableInputStream newStream() {
+    return new HTTPInputStream(client, location, url, metrics);
+  }
+
+  @Override
+  public String location() {
+    return location;
+  }
+
+  @Override
+  public boolean exists() {
+    try {
+      HttpGet request = new HttpGet(url);
+      request.setHeader(HttpHeaders.RANGE, "bytes=0-0");
+      int statusCode = client.execute(request, ClassicHttpResponse::getCode);
+      return statusCode == HttpStatus.SC_PARTIAL_CONTENT || statusCode == 
HttpStatus.SC_OK;
+    } catch (IOException e) {
+      throw new RuntimeIOException(e, "Failed to check existence of %s", 
location);
+    }
+  }
+
+  /**
+   * Fetches the content length via {@code GET Range: bytes=0-0}, reading the 
total from the {@code
+   * Content-Range} header. Works with pre-signed GET URLs, unlike a {@code 
HEAD} request.
+   */
+  private long fetchContentLength() {
+    try {
+      HttpGet request = new HttpGet(url);
+      request.setHeader(HttpHeaders.RANGE, "bytes=0-0");
+
+      return client.execute(
+          request,
+          response -> {
+            int statusCode = response.getCode();
+
+            if (statusCode == HttpStatus.SC_NOT_FOUND) {
+              throw new NotFoundException("Location does not exist: %s", 
location);
+            }
+
+            // 206 Partial Content: parse total from "Content-Range: bytes 
0-0/TOTAL"
+            if (statusCode == HttpStatus.SC_PARTIAL_CONTENT) {
+              Header contentRange = response.getFirstHeader("Content-Range");
+              if (contentRange != null) {
+                long total = 
parseTotalFromContentRange(contentRange.getValue());
+                if (total >= 0) {
+                  return total;
+                }
+              }
+
+              return UNKNOWN_LENGTH;
+            }
+
+            // 200 OK: server returned full content, use Content-Length
+            if (statusCode == HttpStatus.SC_OK) {
+              return parseLengthFrom200(response);
+            }
+
+            throw new IOException(
+                String.format(Locale.ROOT, "Unexpected HTTP %d for %s", 
statusCode, url));
+          });
+    } catch (IOException e) {
+      throw new RuntimeIOException(e, "Failed to fetch content length for %s", 
location);
+    }
+  }
+
+  /** Extracts content length from a 200 response via entity or {@code 
Content-Length} header. */
+  private static long parseLengthFrom200(ClassicHttpResponse response) {
+    long contentLength =
+        response.getEntity() != null ? response.getEntity().getContentLength() 
: UNKNOWN_LENGTH;
+    if (contentLength >= 0) {
+      return contentLength;
+    }
+
+    Header header = response.getFirstHeader("Content-Length");
+    if (header != null) {
+      try {
+        return Long.parseLong(header.getValue());
+      } catch (NumberFormatException e) {
+        // fall through to UNKNOWN_LENGTH
+      }
+    }
+
+    return UNKNOWN_LENGTH;
+  }
+
+  /**
+   * Parses the total object size from a {@code Content-Range} header value 
such as {@code bytes
+   * 0-0/12345}.
+   */
+  private static long parseTotalFromContentRange(String contentRange) {
+    int slash = contentRange.lastIndexOf('/');
+    if (slash < 0) {
+      return UNKNOWN_LENGTH;
+    }
+
+    String totalStr = contentRange.substring(slash + 1).trim();
+    if ("*".equals(totalStr)) {
+      return UNKNOWN_LENGTH;
+    }
+
+    try {
+      return Long.parseLong(totalStr);
+    } catch (NumberFormatException e) {
+      return UNKNOWN_LENGTH;
+    }
+  }

Review Comment:
   should we move this to utils ? it would be easier to unit test this



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