geruh commented on code in PR #14824:
URL: https://github.com/apache/iceberg/pull/14824#discussion_r2616636325


##########
core/src/test/java/org/apache/iceberg/rest/TestScanTaskIterable.java:
##########
@@ -0,0 +1,523 @@
+/*
+ * 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.rest;
+
+import static java.util.stream.Collectors.toList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.IntStream;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.MockFileScanTask;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.rest.requests.FetchScanTasksRequest;
+import org.apache.iceberg.rest.responses.FetchScanTasksResponse;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestScanTaskIterable {
+
+  private static final TableIdentifier TABLE_IDENTIFIER =
+      TableIdentifier.of(Namespace.of("ns"), "table");
+  private static final String FETCH_TASKS_PATH = 
"v1/namespaces/ns/tables/table/tasks";
+  private static final Map<String, String> HEADERS =
+      ImmutableMap.of("Authorization", "Bearer token");
+
+  private RESTClient mockClient;
+  private ResourcePaths resourcePaths;
+  private ExecutorService executorService;
+  private ParserContext parserContext;
+
+  @BeforeEach
+  public void before() {
+    mockClient = mock(RESTClient.class);
+    resourcePaths = ResourcePaths.forCatalogProperties(ImmutableMap.of());
+    executorService = Executors.newFixedThreadPool(4);
+    parserContext = ParserContext.builder().build();
+  }
+
+  @AfterEach
+  public void after() {
+    if (executorService != null) {
+      executorService.shutdownNow();
+    }
+  }
+
+  private void assertIteratorThrows(CloseableIterator<FileScanTask> iterator, 
String errorPattern) {
+    assertThatThrownBy(iterator::hasNext)
+        .isInstanceOf(RuntimeException.class)
+        .hasMessageContaining(errorPattern);
+  }
+
+  private List<String> planTasks(int count) {
+    return IntStream.range(0, count).mapToObj(i -> "planTask" + 
i).collect(toList());
+  }
+
+  private List<FileScanTask> fileTasks(int count) {
+    return IntStream.range(1, count + 1).mapToObj(i -> new 
MockFileScanTask(i)).collect(toList());
+  }
+
+  private List<FileScanTask> collectAll(CloseableIterator<FileScanTask> 
iterator)
+      throws IOException {
+    try (iterator) {
+      return Lists.newArrayList(iterator);
+    }
+  }
+
+  private ScanTaskIterable createIterable(List<String> planTasks, 
List<FileScanTask> initialTasks) {
+    return new ScanTaskIterable(
+        planTasks,
+        initialTasks,
+        mockClient,
+        resourcePaths,
+        TABLE_IDENTIFIER,
+        HEADERS,
+        executorService,
+        parserContext);
+  }
+
+  private void mockClientPost(FetchScanTasksResponse... responses) {
+    if (responses.length == 1) {
+      when(mockClient.post(
+              eq(FETCH_TASKS_PATH),
+              any(FetchScanTasksRequest.class),
+              eq(FetchScanTasksResponse.class),
+              eq(HEADERS),
+              any(),
+              any(),
+              eq(parserContext)))
+          .thenReturn(responses[0]);
+    } else {
+      when(mockClient.post(
+              eq(FETCH_TASKS_PATH),
+              any(FetchScanTasksRequest.class),
+              eq(FetchScanTasksResponse.class),
+              eq(HEADERS),
+              any(),
+              any(),
+              eq(parserContext)))
+          .thenReturn(responses[0], java.util.Arrays.copyOfRange(responses, 1, 
responses.length));
+    }
+  }
+
+  // ==================== Nested/Paginated Plan Tasks Tests 
====================
+
+  @Test
+  public void iterableWithNestedPlanTasks() throws IOException {
+    // First plan task returns more plan tasks
+    FetchScanTasksResponse response1 =
+        FetchScanTasksResponse.builder()
+            .withPlanTasks(ImmutableList.of("nestedPlanTask1", 
"nestedPlanTask2"))
+            .withFileScanTasks(ImmutableList.of(new MockFileScanTask(100)))
+            .build();
+
+    FetchScanTasksResponse response2 =
+        FetchScanTasksResponse.builder()
+            .withFileScanTasks(ImmutableList.of(new MockFileScanTask(200)))
+            .build();
+    FetchScanTasksResponse response3 =
+        FetchScanTasksResponse.builder()
+            .withFileScanTasks(ImmutableList.of(new MockFileScanTask(300)))
+            .build();
+
+    mockClientPost(response1, response2, response3);
+
+    ScanTaskIterable iterable =
+        createIterable(ImmutableList.of("planTask1"), Collections.emptyList());
+
+    List<FileScanTask> result = collectAll(iterable.iterator());
+    assertThat(result).hasSize(3);
+    
assertThat(result).extracting(FileScanTask::length).containsExactlyInAnyOrder(100L,
 200L, 300L);
+
+    verify(mockClient, times(3))
+        .post(
+            eq(FETCH_TASKS_PATH),
+            any(FetchScanTasksRequest.class),
+            eq(FetchScanTasksResponse.class),
+            eq(HEADERS),
+            any(),
+            any(),
+            eq(parserContext));
+  }
+
+  @Test
+  public void iterableWithDeeplyNestedPlanTasks() throws IOException {
+    FetchScanTasksResponse response1 =
+        
FetchScanTasksResponse.builder().withPlanTasks(ImmutableList.of("level2")).build();
+    FetchScanTasksResponse response2 =
+        
FetchScanTasksResponse.builder().withPlanTasks(ImmutableList.of("level3")).build();
+    FetchScanTasksResponse response3 =
+        FetchScanTasksResponse.builder()
+            .withFileScanTasks(ImmutableList.of(new MockFileScanTask(100)))
+            .build();
+
+    mockClientPost(response1, response2, response3);
+
+    ScanTaskIterable iterable = createIterable(ImmutableList.of("level1"), 
Collections.emptyList());
+
+    List<FileScanTask> result = collectAll(iterable.iterator());
+    assertThat(result).hasSize(1);
+    assertThat(result.get(0).length()).isEqualTo(100L);
+  }
+
+  // ==================== Iterator Behavior Tests ====================
+
+  @Test
+  public void iteratorNextWithoutHasNext() throws IOException {
+    ScanTaskIterable iterable = createIterable(null, ImmutableList.of(new 
MockFileScanTask(100)));
+
+    try (CloseableIterator<FileScanTask> iterator = iterable.iterator()) {
+      FileScanTask task = iterator.next();
+      assertThat(task.length()).isEqualTo(100L);
+      assertThatThrownBy(iterator::next)
+          .isInstanceOf(NoSuchElementException.class)
+          .hasMessage("No more scan tasks available");
+    }
+  }
+
+  @Test
+  public void iteratorMultipleHasNextCallsIdempotent() throws IOException {
+    ScanTaskIterable iterable = createIterable(null, ImmutableList.of(new 
MockFileScanTask(100)));
+
+    try (CloseableIterator<FileScanTask> iterator = iterable.iterator()) {
+      // Multiple hasNext() calls should be idempotent
+      assertThat(iterator.hasNext()).isTrue();
+      assertThat(iterator.hasNext()).isTrue();
+      assertThat(iterator.hasNext()).isTrue();
+
+      FileScanTask task = iterator.next();
+      assertThat(task.length()).isEqualTo(100L);
+
+      assertThat(iterator.hasNext()).isFalse();
+      assertThat(iterator.hasNext()).isFalse();
+    }
+  }
+
+  // ==================== Error Handling Tests ====================
+
+  @Test
+  public void workerFailurePropagatesException() throws IOException {
+    when(mockClient.post(
+            eq(FETCH_TASKS_PATH),
+            any(FetchScanTasksRequest.class),
+            eq(FetchScanTasksResponse.class),
+            eq(HEADERS),
+            any(),
+            any(),
+            eq(parserContext)))
+        .thenThrow(new RuntimeException("Network error"));
+
+    ScanTaskIterable iterable =
+        createIterable(ImmutableList.of("planTask1"), Collections.emptyList());
+
+    try (CloseableIterator<FileScanTask> iterator = iterable.iterator()) {
+      assertIteratorThrows(iterator, "Worker failed");
+    }
+  }
+
+  // ==================== Chained Plan Tasks Test ====================
+
+  @Test
+  public void chainedPlanTasks() throws IOException {
+    AtomicInteger callCount = new AtomicInteger(0);
+
+    when(mockClient.post(
+            eq(FETCH_TASKS_PATH),
+            any(FetchScanTasksRequest.class),
+            eq(FetchScanTasksResponse.class),
+            eq(HEADERS),
+            any(),
+            any(),
+            eq(parserContext)))
+        .thenAnswer(
+            invocation -> {
+              int count = callCount.incrementAndGet();
+              if (count <= 3) {
+                return FetchScanTasksResponse.builder()
+                    .withPlanTasks(ImmutableList.of("chainedTask" + count))
+                    .withFileScanTasks(ImmutableList.of(new 
MockFileScanTask(count * 100L)))
+                    .build();
+              } else {
+                return FetchScanTasksResponse.builder()
+                    .withFileScanTasks(ImmutableList.of(new 
MockFileScanTask(count * 100L)))
+                    .build();
+              }
+            });
+
+    ScanTaskIterable iterable =
+        createIterable(ImmutableList.of("initialTask"), 
Collections.emptyList());
+
+    List<FileScanTask> result = collectAll(iterable.iterator());
+    assertThat(result).hasSize(4);
+  }
+
+  // ==================== Concurrency Tests ====================
+
+  @Test
+  public void concurrentWorkersProcessingTasks() throws IOException {
+    AtomicInteger callCount = new AtomicInteger(0);
+
+    when(mockClient.post(
+            eq(FETCH_TASKS_PATH),
+            any(FetchScanTasksRequest.class),
+            eq(FetchScanTasksResponse.class),
+            eq(HEADERS),
+            any(),
+            any(),
+            eq(parserContext)))
+        .thenAnswer(
+            invocation -> {
+              int count = callCount.incrementAndGet();
+              // Simulate some network latency
+              Thread.sleep(10);
+              return FetchScanTasksResponse.builder()
+                  .withFileScanTasks(ImmutableList.of(new 
MockFileScanTask(count * 100)))
+                  .build();
+            });
+
+    // Create many plan tasks to trigger multiple workers
+    ScanTaskIterable iterable = createIterable(planTasks(50), 
Collections.emptyList());
+
+    List<FileScanTask> result = collectAll(iterable.iterator());
+    assertThat(result).hasSize(50);
+
+    // All plan tasks should have been processed exactly once
+    assertThat(callCount.get()).isEqualTo(50);
+  }
+
+  @Test
+  public void slowProducerFastConsumer() throws IOException {
+    AtomicInteger callCount = new AtomicInteger(0);
+
+    when(mockClient.post(
+            eq(FETCH_TASKS_PATH),
+            any(FetchScanTasksRequest.class),
+            eq(FetchScanTasksResponse.class),
+            eq(HEADERS),
+            any(),
+            any(),
+            eq(parserContext)))
+        .thenAnswer(
+            invocation -> {
+              // Slow producer - simulate network delay
+              Thread.sleep(50);
+              int count = callCount.incrementAndGet();
+              return FetchScanTasksResponse.builder()
+                  .withFileScanTasks(ImmutableList.of(new 
MockFileScanTask(count * 100)))
+                  .build();
+            });
+
+    ScanTaskIterable iterable =
+        createIterable(
+            ImmutableList.of("planTask1", "planTask2", "planTask3"), 
Collections.emptyList());

Review Comment:
   nit: you can use your planTask helper here



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