|
| 1 | +/* |
| 2 | + * Copyright © 2018-2026 Commonwealth Scientific and Industrial Research |
| 3 | + * Organisation (CSIRO) ABN 41 687 119 230. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package au.csiro.pathling.async; |
| 19 | + |
| 20 | +import static au.csiro.pathling.security.SecurityAspect.checkHasAuthority; |
| 21 | +import static au.csiro.pathling.security.SecurityAspect.getCurrentUserId; |
| 22 | + |
| 23 | +import au.csiro.pathling.config.ServerConfiguration; |
| 24 | +import au.csiro.pathling.errors.AccessDeniedError; |
| 25 | +import au.csiro.pathling.errors.ErrorHandlingInterceptor; |
| 26 | +import au.csiro.pathling.errors.ResourceNotFoundError; |
| 27 | +import au.csiro.pathling.security.PathlingAuthority; |
| 28 | +import ca.uhn.fhir.rest.annotation.Operation; |
| 29 | +import ca.uhn.fhir.rest.annotation.OperationParam; |
| 30 | +import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; |
| 31 | +import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; |
| 32 | +import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; |
| 33 | +import jakarta.annotation.Nonnull; |
| 34 | +import jakarta.annotation.Nullable; |
| 35 | +import jakarta.servlet.http.HttpServletRequest; |
| 36 | +import jakarta.servlet.http.HttpServletResponse; |
| 37 | +import java.util.Optional; |
| 38 | +import java.util.concurrent.ExecutionException; |
| 39 | +import java.util.regex.Pattern; |
| 40 | +import lombok.extern.slf4j.Slf4j; |
| 41 | +import org.hl7.fhir.instance.model.api.IBaseResource; |
| 42 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
| 43 | +import org.springframework.security.core.Authentication; |
| 44 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 45 | +import org.springframework.stereotype.Component; |
| 46 | + |
| 47 | +/** |
| 48 | + * Provides the $job-result operation for retrieving the result of a completed async job. This |
| 49 | + * endpoint is used when operations are configured with {@code redirectOnComplete=true}, following |
| 50 | + * the SQL on FHIR unify-async specification. |
| 51 | + * |
| 52 | + * <p>The flow is: 1. Client polls $job endpoint until job completes 2. $job returns 303 See Other |
| 53 | + * with Location header pointing to $job-result 3. Client fetches result from $job-result endpoint |
| 54 | + * |
| 55 | + * @author John Grimes |
| 56 | + */ |
| 57 | +@Component |
| 58 | +@ConditionalOnProperty(prefix = "pathling", name = "async.enabled", havingValue = "true") |
| 59 | +@Slf4j |
| 60 | +public class JobResultProvider { |
| 61 | + |
| 62 | + private static final Pattern ID_PATTERN = |
| 63 | + Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"); |
| 64 | + |
| 65 | + @Nonnull private final ServerConfiguration configuration; |
| 66 | + |
| 67 | + @Nonnull private final JobRegistry jobRegistry; |
| 68 | + |
| 69 | + /** |
| 70 | + * Creates a new JobResultProvider. |
| 71 | + * |
| 72 | + * @param configuration the server configuration |
| 73 | + * @param jobRegistry the job registry |
| 74 | + */ |
| 75 | + public JobResultProvider( |
| 76 | + @Nonnull final ServerConfiguration configuration, @Nonnull final JobRegistry jobRegistry) { |
| 77 | + this.configuration = configuration; |
| 78 | + this.jobRegistry = jobRegistry; |
| 79 | + } |
| 80 | + |
| 81 | + /** |
| 82 | + * Retrieves the result of a completed async job. |
| 83 | + * |
| 84 | + * @param id the job ID |
| 85 | + * @param request the HTTP request |
| 86 | + * @param response the HTTP response |
| 87 | + * @return the job result as a Parameters resource |
| 88 | + */ |
| 89 | + @SuppressWarnings("unused") |
| 90 | + @Operation(name = "$job-result", idempotent = true) |
| 91 | + public IBaseResource jobResult( |
| 92 | + @Nullable @OperationParam(name = "id") final String id, |
| 93 | + @Nonnull final HttpServletRequest request, |
| 94 | + @Nullable final HttpServletResponse response) { |
| 95 | + log.debug("Received $job-result request with id: {}", id); |
| 96 | + |
| 97 | + final Job<?> job = getJob(id); |
| 98 | + |
| 99 | + if (configuration.getAuth().isEnabled()) { |
| 100 | + // Check for the required authority associated with the operation that initiated the job. |
| 101 | + checkHasAuthority(PathlingAuthority.operationAccess(job.getOperation())); |
| 102 | + // Check that the user requesting the job result is the same user that started the job. |
| 103 | + final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| 104 | + final Optional<String> currentUserId = getCurrentUserId(authentication); |
| 105 | + if (!job.getOwnerId().equals(currentUserId)) { |
| 106 | + throw new AccessDeniedError("The requested job is not owned by the current user"); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return handleJobResultRequest(job, response); |
| 111 | + } |
| 112 | + |
| 113 | + @Nonnull |
| 114 | + private Job<?> getJob(@Nullable final String id) { |
| 115 | + // Validate that the ID looks reasonable. |
| 116 | + if (id == null || !ID_PATTERN.matcher(id).matches()) { |
| 117 | + throw new ResourceNotFoundError("Job ID not found"); |
| 118 | + } |
| 119 | + |
| 120 | + log.debug("Received request for job result: {}", id); |
| 121 | + @Nullable final Job<?> job = jobRegistry.get(id); |
| 122 | + // Check that the job exists. |
| 123 | + if (job == null) { |
| 124 | + throw new ResourceNotFoundError("Job ID not found"); |
| 125 | + } |
| 126 | + return job; |
| 127 | + } |
| 128 | + |
| 129 | + @Nonnull |
| 130 | + private IBaseResource handleJobResultRequest( |
| 131 | + @Nonnull final Job<?> job, @Nullable final HttpServletResponse response) { |
| 132 | + // Handle cancelled jobs. |
| 133 | + if (job.getResult().isCancelled()) { |
| 134 | + throw new ResourceNotFoundException( |
| 135 | + "A DELETE request cancelled this job or deleted all files associated with this job."); |
| 136 | + } |
| 137 | + |
| 138 | + // Verify the job is complete. |
| 139 | + if (!job.getResult().isDone()) { |
| 140 | + throw new InvalidRequestException( |
| 141 | + "Job is not yet complete. Poll the $job endpoint to check status."); |
| 142 | + } |
| 143 | + |
| 144 | + // Set cache headers. |
| 145 | + if (response != null) { |
| 146 | + final int maxAge = configuration.getAsync().getCacheMaxAge(); |
| 147 | + response.setHeader("Cache-Control", "max-age=" + maxAge); |
| 148 | + } |
| 149 | + |
| 150 | + // Apply any response modifications set by the operation (e.g., Expires header). |
| 151 | + job.getResponseModification().accept(response); |
| 152 | + |
| 153 | + // Return the result. |
| 154 | + try { |
| 155 | + return job.getResult().get(); |
| 156 | + } catch (final InterruptedException e) { |
| 157 | + Thread.currentThread().interrupt(); |
| 158 | + throw new InternalErrorException("Job was interrupted", e); |
| 159 | + } catch (final ExecutionException e) { |
| 160 | + throw ErrorHandlingInterceptor.convertError(unwrapExecutionException(e)); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + /** |
| 165 | + * Unwraps the cause chain from an ExecutionException. The Future wraps exceptions in |
| 166 | + * ExecutionException, and AsyncAspect may wrap them in IllegalStateException. |
| 167 | + * |
| 168 | + * @param e The ExecutionException to unwrap. |
| 169 | + * @return The root cause or the original exception. |
| 170 | + */ |
| 171 | + @Nonnull |
| 172 | + private static Throwable unwrapExecutionException(@Nonnull final ExecutionException e) { |
| 173 | + Throwable cause = e.getCause(); |
| 174 | + if (cause != null && cause.getCause() != null) { |
| 175 | + cause = cause.getCause(); |
| 176 | + } |
| 177 | + return cause != null ? cause : e; |
| 178 | + } |
| 179 | +} |
0 commit comments