|
| 1 | +package ai.docling.serve.client.operations; |
| 2 | + |
| 3 | +import java.time.Duration; |
| 4 | +import java.util.Optional; |
| 5 | +import java.util.concurrent.CompletableFuture; |
| 6 | +import java.util.concurrent.CompletionStage; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | + |
| 9 | +import org.slf4j.Logger; |
| 10 | +import org.slf4j.LoggerFactory; |
| 11 | + |
| 12 | +import ai.docling.serve.api.DoclingServeTaskApi; |
| 13 | +import ai.docling.serve.api.task.request.TaskResultRequest; |
| 14 | +import ai.docling.serve.api.task.request.TaskStatusPollRequest; |
| 15 | +import ai.docling.serve.api.task.response.TaskStatusPollResponse; |
| 16 | +import ai.docling.serve.api.util.ValidationUtils; |
| 17 | + |
| 18 | +/** |
| 19 | + * Abstract base class for managing asynchronous operations, providing methods to execute |
| 20 | + * tasks asynchronously and poll for their status until completion. Subclasses must implement |
| 21 | + * specific logic for retrieving task results. |
| 22 | + */ |
| 23 | +public abstract class AsyncOperations { |
| 24 | + private static final Logger LOG = LoggerFactory.getLogger(AsyncOperations.class); |
| 25 | + |
| 26 | + private final HttpOperations httpOperations; |
| 27 | + private final DoclingServeTaskApi taskApi; |
| 28 | + private final Duration asyncPollInterval; |
| 29 | + private final Duration asyncTimeout; |
| 30 | + |
| 31 | + protected AsyncOperations(HttpOperations httpOperations, DoclingServeTaskApi taskApi, Duration asyncPollInterval, Duration asyncTimeout) { |
| 32 | + this.httpOperations = httpOperations; |
| 33 | + this.taskApi = taskApi; |
| 34 | + this.asyncPollInterval = asyncPollInterval; |
| 35 | + this.asyncTimeout = asyncTimeout; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Retrieves the result of a task based on the provided task result request. |
| 40 | + * |
| 41 | + * This method is abstract and meant to be implemented by subclasses. |
| 42 | + * It uses the information provided in the {@code TaskResultRequest} |
| 43 | + * to obtain the result of the task execution. |
| 44 | + * |
| 45 | + * @param <O> the type of the result object returned |
| 46 | + * @param taskResultRequest the request containing the details, including the task ID, |
| 47 | + * required to retrieve the task result |
| 48 | + * @return the result of the task execution, of the type {@code O} |
| 49 | + */ |
| 50 | + protected abstract <O> O getTaskResult(TaskResultRequest taskResultRequest); |
| 51 | + |
| 52 | + /** |
| 53 | + * Executes an asynchronous operation by sending a request to the specified URI |
| 54 | + * and polling for the task completion. This method uses an HTTP POST operation |
| 55 | + * to start the task and then repeatedly polls the task status to determine |
| 56 | + * when the operation is complete. |
| 57 | + * |
| 58 | + * @param <I> the type of the request object being sent |
| 59 | + * @param <O> the type of the response object returned upon completion |
| 60 | + * @param request the request object containing the data necessary to initialize the task |
| 61 | + * @param uri the endpoint URI to which the request will be sent |
| 62 | + * @return a {@link CompletableFuture} that will be completed with the result of the asynchronous operation |
| 63 | + */ |
| 64 | + protected <I, O> CompletableFuture<O> executeAsync(I request, String uri) { |
| 65 | + ValidationUtils.ensureNotNull(request, "request"); |
| 66 | + |
| 67 | + // Start the async conversion and chain the polling logic |
| 68 | + return CompletableFuture.supplyAsync(() -> |
| 69 | + this.httpOperations.executePost(createAsyncRequestContext(uri, request)) |
| 70 | + ).thenCompose(taskResponse -> { |
| 71 | + LOG.info("Started async conversion with task ID: {}", taskResponse.getTaskId()); |
| 72 | + |
| 73 | + long startTime = System.currentTimeMillis(); |
| 74 | + return pollTaskUntilComplete(taskResponse, startTime); |
| 75 | + }); |
| 76 | + } |
| 77 | + |
| 78 | + private <I> RequestContext<I, TaskStatusPollResponse> createAsyncRequestContext(String uri, I request) { |
| 79 | + return RequestContext.<I, TaskStatusPollResponse>builder() |
| 80 | + .request(request) |
| 81 | + .responseType(TaskStatusPollResponse.class) |
| 82 | + .uri(uri) |
| 83 | + .build(); |
| 84 | + } |
| 85 | + |
| 86 | + private <O> CompletionStage<O> pollTaskUntilComplete(TaskStatusPollResponse statusPollResponse, long startTime) { |
| 87 | + var taskId = statusPollResponse.getTaskId(); |
| 88 | + |
| 89 | + // Check if we've timed out |
| 90 | + if (System.currentTimeMillis() - startTime > this.asyncTimeout.toMillis()) { |
| 91 | + return CompletableFuture.failedFuture( |
| 92 | + new RuntimeException("Async conversion timed out after %s for task: %s".formatted(this.asyncTimeout, taskId)) |
| 93 | + ); |
| 94 | + } |
| 95 | + |
| 96 | + // Poll the task status |
| 97 | + var pollRequest = TaskStatusPollRequest.builder() |
| 98 | + .taskId(taskId) |
| 99 | + .build(); |
| 100 | + |
| 101 | + return CompletableFuture.supplyAsync(() -> this.taskApi.pollTaskStatus(pollRequest)) |
| 102 | + .thenCompose(statusResponse -> pollTaskStatus(statusResponse, startTime)); |
| 103 | + } |
| 104 | + |
| 105 | + private <O> CompletionStage<O> pollTaskStatus(TaskStatusPollResponse statusResponse, long startTime) { |
| 106 | + var status = statusResponse.getTaskStatus(); |
| 107 | + var taskId = statusResponse.getTaskId(); |
| 108 | + LOG.debug("Task {} status: {}", taskId, status); |
| 109 | + |
| 110 | + return switch (status) { |
| 111 | + case SUCCESS -> { |
| 112 | + LOG.info("Task {} completed successfully", taskId); |
| 113 | + |
| 114 | + // Retrieve the result |
| 115 | + var taskResult = TaskResultRequest.builder() |
| 116 | + .taskId(statusResponse.getTaskId()) |
| 117 | + .build(); |
| 118 | + |
| 119 | + yield CompletableFuture.supplyAsync(() -> getTaskResult(taskResult)); |
| 120 | + } |
| 121 | + |
| 122 | + case FAILURE -> { |
| 123 | + var errorMessage = Optional.ofNullable(statusResponse.getTaskStatusMetadata()) |
| 124 | + .map(metadata -> "Task failed: %s".formatted(metadata)) |
| 125 | + .orElse("Task failed"); |
| 126 | + |
| 127 | + yield CompletableFuture.failedStage( |
| 128 | + new RuntimeException("Async conversion failed for task %s: %s".formatted(taskId, errorMessage))); |
| 129 | + } |
| 130 | + |
| 131 | + default -> |
| 132 | + // Still in progress (PENDING or STARTED), schedule next poll after delay |
| 133 | + CompletableFuture.supplyAsync( |
| 134 | + () -> null, |
| 135 | + CompletableFuture.delayedExecutor(this.asyncPollInterval.toMillis(), TimeUnit.MILLISECONDS) |
| 136 | + ).thenCompose(v -> pollTaskUntilComplete(statusResponse, startTime)); |
| 137 | + }; |
| 138 | + } |
| 139 | +} |
0 commit comments