|
| 1 | +/* |
| 2 | + * Copyright OpenSearch Contributors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package org.opensearch.sql.opensearch.storage.scan; |
| 7 | + |
| 8 | +import static org.opensearch.sql.opensearch.executor.OpenSearchQueryManager.SQL_BACKGROUND_THREAD_POOL_NAME; |
| 9 | + |
| 10 | +import java.util.Collections; |
| 11 | +import java.util.Iterator; |
| 12 | +import java.util.concurrent.CompletableFuture; |
| 13 | +import java.util.concurrent.ExecutionException; |
| 14 | +import java.util.concurrent.Executor; |
| 15 | +import javax.annotation.Nullable; |
| 16 | +import org.opensearch.sql.data.model.ExprValue; |
| 17 | +import org.opensearch.sql.exception.NonFallbackCalciteException; |
| 18 | +import org.opensearch.sql.opensearch.client.OpenSearchClient; |
| 19 | +import org.opensearch.sql.opensearch.request.OpenSearchRequest; |
| 20 | +import org.opensearch.sql.opensearch.response.OpenSearchResponse; |
| 21 | + |
| 22 | +/** |
| 23 | + * Utility class for asynchronously scanning an index. This lets us send background requests to the |
| 24 | + * index while we work on processing the previous batch. |
| 25 | + * |
| 26 | + * <h2>Lifecycle</h2> |
| 27 | + * |
| 28 | + * The typical usage pattern is: |
| 29 | + * |
| 30 | + * <pre> |
| 31 | + * 1. Create scanner: new BackgroundSearchScanner(client) |
| 32 | + * 2. Start initial scan: startScanning(request) |
| 33 | + * 3. Fetch batches in a loop: fetchNextBatch(request, maxWindow) |
| 34 | + * 4. Close scanner when done: close() |
| 35 | + * </pre> |
| 36 | + * |
| 37 | + * <h2>Async vs Sync Behavior</h2> |
| 38 | + * |
| 39 | + * The scanner attempts to operate asynchronously when possible to improve performance: |
| 40 | + * |
| 41 | + * <ul> |
| 42 | + * <li>When async is available (client has thread pool access): - Next batch is pre-fetched while |
| 43 | + * current batch is being processed - Reduces latency between batches |
| 44 | + * <li>When async is not available (client lacks thread pool access): - Falls back to synchronous |
| 45 | + * fetching - Each batch is fetched only when needed |
| 46 | + * </ul> |
| 47 | + * |
| 48 | + * <h2>Termination Conditions</h2> |
| 49 | + * |
| 50 | + * Scanning will stop when any of these conditions are met: |
| 51 | + * |
| 52 | + * <ul> |
| 53 | + * <li>An empty response is received (lastBatch = true) |
| 54 | + * <li>Response is an aggregation or count response (fetchOnce = true) |
| 55 | + * <li>Response size is less than maxResultWindow (fetchOnce = true) |
| 56 | + * </ul> |
| 57 | + * |
| 58 | + * Note: This class should be explicitly closed when no longer needed to ensure proper resource |
| 59 | + * cleanup. |
| 60 | + */ |
| 61 | +public class BackgroundSearchScanner { |
| 62 | + private final OpenSearchClient client; |
| 63 | + @Nullable private final Executor backgroundExecutor; |
| 64 | + private CompletableFuture<OpenSearchResponse> nextBatchFuture = null; |
| 65 | + private boolean stopIteration = false; |
| 66 | + |
| 67 | + public BackgroundSearchScanner(OpenSearchClient client) { |
| 68 | + this.client = client; |
| 69 | + // We can only actually do the background operation if we have the ability to access the thread |
| 70 | + // pool. Otherwise, fallback to synchronous fetch. |
| 71 | + if (client.getNodeClient().isPresent()) { |
| 72 | + this.backgroundExecutor = |
| 73 | + client.getNodeClient().get().threadPool().executor(SQL_BACKGROUND_THREAD_POOL_NAME); |
| 74 | + } else { |
| 75 | + this.backgroundExecutor = null; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + private boolean isAsync() { |
| 80 | + return backgroundExecutor != null; |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * @return Whether the search scanner has fetched all batches |
| 85 | + */ |
| 86 | + public boolean isScanDone() { |
| 87 | + return stopIteration; |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Initiates the scanning process. If async operations are available, this will trigger the first |
| 92 | + * background fetch. |
| 93 | + * |
| 94 | + * @param request The OpenSearch request to execute |
| 95 | + */ |
| 96 | + public void startScanning(OpenSearchRequest request) { |
| 97 | + if (isAsync()) { |
| 98 | + nextBatchFuture = |
| 99 | + CompletableFuture.supplyAsync(() -> client.search(request), backgroundExecutor); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + private OpenSearchResponse getCurrentResponse(OpenSearchRequest request) { |
| 104 | + if (isAsync()) { |
| 105 | + try { |
| 106 | + return nextBatchFuture.get(); |
| 107 | + } catch (InterruptedException | ExecutionException e) { |
| 108 | + throw new NonFallbackCalciteException( |
| 109 | + "Failed to fetch data from the index: the background task failed or interrupted.\n" |
| 110 | + + " Inner error: " |
| 111 | + + e.getMessage()); |
| 112 | + } |
| 113 | + } else { |
| 114 | + return client.search(request); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Fetches the next batch of results. If async is enabled and more batches are expected, this will |
| 120 | + * also trigger the next background fetch. |
| 121 | + * |
| 122 | + * @param request The OpenSearch request to execute |
| 123 | + * @param maxResultWindow Maximum number of results to fetch per batch |
| 124 | + * @return SearchBatchResult containing the current batch's iterator and completion status |
| 125 | + * @throws NonFallbackCalciteException if the background fetch fails or is interrupted |
| 126 | + */ |
| 127 | + public SearchBatchResult fetchNextBatch(OpenSearchRequest request, int maxResultWindow) { |
| 128 | + OpenSearchResponse response = getCurrentResponse(request); |
| 129 | + |
| 130 | + // Determine if we need future batches |
| 131 | + if (response.isAggregationResponse() |
| 132 | + || response.isCountResponse() |
| 133 | + || response.getHitsSize() < maxResultWindow) { |
| 134 | + stopIteration = true; |
| 135 | + } |
| 136 | + |
| 137 | + Iterator<ExprValue> iterator; |
| 138 | + if (!response.isEmpty()) { |
| 139 | + iterator = response.iterator(); |
| 140 | + |
| 141 | + // Pre-fetch next batch if needed |
| 142 | + if (!stopIteration && isAsync()) { |
| 143 | + nextBatchFuture = |
| 144 | + CompletableFuture.supplyAsync(() -> client.search(request), backgroundExecutor); |
| 145 | + } |
| 146 | + } else { |
| 147 | + iterator = Collections.emptyIterator(); |
| 148 | + stopIteration = true; |
| 149 | + } |
| 150 | + |
| 151 | + return new SearchBatchResult(iterator, stopIteration); |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Resets the scanner to its initial state, allowing a new scan to begin. This clears all |
| 156 | + * completion flags and initiates a new background fetch if async is enabled. |
| 157 | + * |
| 158 | + * @param request The OpenSearch request to execute |
| 159 | + */ |
| 160 | + public void reset(OpenSearchRequest request) { |
| 161 | + stopIteration = false; |
| 162 | + startScanning(request); |
| 163 | + } |
| 164 | + |
| 165 | + /** |
| 166 | + * Releases resources associated with this scanner. Cancels any pending background fetches and |
| 167 | + * marks the scan as complete. The scanner cannot be reused after closing without calling reset(). |
| 168 | + */ |
| 169 | + public void close() { |
| 170 | + stopIteration = true; |
| 171 | + if (nextBatchFuture != null) { |
| 172 | + nextBatchFuture.cancel(true); |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + public record SearchBatchResult(Iterator<ExprValue> iterator, boolean stopIteration) {} |
| 177 | +} |
0 commit comments