|
| 1 | +/* |
| 2 | + * Copyright 2013-2025, Seqera Labs |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + */ |
| 17 | + |
| 18 | +package io.seqera.client |
| 19 | + |
| 20 | +import java.net.http.HttpClient |
| 21 | +import java.net.http.HttpRequest |
| 22 | +import java.net.http.HttpResponse |
| 23 | +import java.time.Duration |
| 24 | +import java.time.temporal.ChronoUnit |
| 25 | +import java.util.concurrent.Executors |
| 26 | +import java.util.function.Predicate |
| 27 | + |
| 28 | +import dev.failsafe.Failsafe |
| 29 | +import dev.failsafe.RetryPolicy |
| 30 | +import dev.failsafe.event.EventListener |
| 31 | +import dev.failsafe.event.ExecutionAttemptedEvent |
| 32 | +import dev.failsafe.function.CheckedSupplier |
| 33 | +import groovy.json.JsonOutput |
| 34 | +import groovy.transform.CompileStatic |
| 35 | +import groovy.util.logging.Slf4j |
| 36 | +import io.seqera.config.SeqeraConfig |
| 37 | +import io.seqera.exception.BadResponseException |
| 38 | +import io.seqera.sched.api.v1a1.CancelJobResponse |
| 39 | +import io.seqera.sched.api.v1a1.CreateJobRequest |
| 40 | +import io.seqera.sched.api.v1a1.CreateJobResponse |
| 41 | +import io.seqera.sched.api.v1a1.DescribeJobResponse |
| 42 | +import io.seqera.sched.api.v1a1.GetJobLogsResponse |
| 43 | +import io.seqera.serde.Serde |
| 44 | +import io.seqera.util.trace.TraceUtils |
| 45 | +import nextflow.Session |
| 46 | +import nextflow.util.Threads |
| 47 | +/** |
| 48 | + * |
| 49 | + * @author Paolo Di Tommaso <paolo.ditommaso@gmail.com> |
| 50 | + */ |
| 51 | +@Slf4j |
| 52 | +@CompileStatic |
| 53 | +class SeqeraClient { |
| 54 | + |
| 55 | + private HttpClient httpClient |
| 56 | + |
| 57 | + private CookieManager cookieManager |
| 58 | + |
| 59 | + private SeqeraConfig config |
| 60 | + |
| 61 | + SeqeraClient(Session session) { |
| 62 | + this.config = new SeqeraConfig(session.config.seqera as Map ?: Collections.emptyMap()) |
| 63 | + // the cookie manager |
| 64 | + cookieManager = new CookieManager() |
| 65 | + // create http client |
| 66 | + this.httpClient = newHttpClient() |
| 67 | + } |
| 68 | + |
| 69 | + protected HttpClient newHttpClient() { |
| 70 | + final builder = HttpClient.newBuilder() |
| 71 | + .version(HttpClient.Version.HTTP_1_1) |
| 72 | + .followRedirects(HttpClient.Redirect.NORMAL) |
| 73 | + .connectTimeout(Duration.ofSeconds(10)) |
| 74 | + .cookieHandler(cookieManager) |
| 75 | + // use virtual threads executor if enabled |
| 76 | + if( Threads.useVirtual() ) |
| 77 | + builder.executor(Executors.newVirtualThreadPerTaskExecutor()) |
| 78 | + // build and return the new client |
| 79 | + return builder.build() |
| 80 | + } |
| 81 | + |
| 82 | + protected <R> R get0(String uri, Class<R> responseType) { |
| 83 | + final trace = TraceUtils.rndTrace() |
| 84 | + final req = HttpRequest.newBuilder() |
| 85 | + .uri(URI.create(uri)) |
| 86 | + .headers('Content-Type','application/json', 'Traceparent', trace) |
| 87 | + .GET() |
| 88 | + .build() |
| 89 | + send0(req, responseType) |
| 90 | + } |
| 91 | + |
| 92 | + protected <R> R delete0(String uri, Class<R> response) { |
| 93 | + final trace = TraceUtils.rndTrace() |
| 94 | + final req = HttpRequest.newBuilder() |
| 95 | + .uri(URI.create(uri)) |
| 96 | + .headers('Content-Type','application/json', 'Traceparent', trace) |
| 97 | + .DELETE() |
| 98 | + .build() |
| 99 | + return send0(req, response) |
| 100 | + } |
| 101 | + |
| 102 | + protected <T,R> R post0(String uri, T request, Class<R> response) { |
| 103 | + final trace = TraceUtils.rndTrace() |
| 104 | + final body = JsonOutput.toJson(request) |
| 105 | + final req = HttpRequest.newBuilder() |
| 106 | + .uri(URI.create(uri)) |
| 107 | + .headers('Content-Type','application/json', 'Traceparent', trace) |
| 108 | + .POST(HttpRequest.BodyPublishers.ofString(body)) |
| 109 | + .build() |
| 110 | + return send0(req, response) |
| 111 | + } |
| 112 | + |
| 113 | + protected <T> T send0(HttpRequest req, Class<T> type) { |
| 114 | + final HttpResponse<String> resp = httpSend(req); |
| 115 | + log.debug("Seqera status response: statusCode={}; body={}", resp.statusCode(), resp.body()) |
| 116 | + if( resp.statusCode()==200 ) { |
| 117 | + return Serde.fromJson(resp.body(), type) |
| 118 | + } |
| 119 | + else { |
| 120 | + final msg = "Seqera invalid response: ${req.method()} ${req.uri()} [${resp.statusCode()}] ${resp.body()}" |
| 121 | + throw new BadResponseException(msg) |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + CreateJobResponse createJob(CreateJobRequest request) { |
| 126 | + final uri = "${config.endpoint}/v1a1/jobs" |
| 127 | + return post0(uri, request, CreateJobResponse) |
| 128 | + } |
| 129 | + |
| 130 | + DescribeJobResponse describeJob(String jobId) { |
| 131 | + final uri = "${config.endpoint}/v1a1/jobs/${jobId}" |
| 132 | + return get0(uri, DescribeJobResponse) |
| 133 | + } |
| 134 | + |
| 135 | + CancelJobResponse cancelJob(String jobId) { |
| 136 | + final uri = "${config.endpoint}/v1a1/jobs/${jobId}" |
| 137 | + return delete0(uri, CancelJobResponse) |
| 138 | + } |
| 139 | + |
| 140 | + GetJobLogsResponse getJobLogs(String jobId) { |
| 141 | + final uri = "${config.endpoint}/v1a1/jobs/${jobId}/logs" |
| 142 | + return get0(uri, GetJobLogsResponse) |
| 143 | + } |
| 144 | + |
| 145 | + protected <T> RetryPolicy<T> retryPolicy(Predicate<? extends Throwable> cond, Predicate<T> handle) { |
| 146 | + final cfg = config.retryOpts() |
| 147 | + final listener = new EventListener<ExecutionAttemptedEvent<T>>() { |
| 148 | + @Override |
| 149 | + void accept(ExecutionAttemptedEvent event) throws Throwable { |
| 150 | + def msg = "Seqera connection failure - attempt: ${event.attemptCount}" |
| 151 | + if( event.lastResult!=null ) |
| 152 | + msg += "; response: ${event.lastResult}" |
| 153 | + if( event.lastFailure != null ) |
| 154 | + msg += "; exception: [${event.lastFailure.class.name}] ${event.lastFailure.message}" |
| 155 | + log.debug(msg) |
| 156 | + } |
| 157 | + } |
| 158 | + return RetryPolicy.<T>builder() |
| 159 | + .handleIf(cond) |
| 160 | + .handleResultIf(handle) |
| 161 | + .withBackoff(cfg.delay.toMillis(), cfg.maxDelay.toMillis(), ChronoUnit.MILLIS) |
| 162 | + .withMaxAttempts(cfg.maxAttempts) |
| 163 | + .withJitter(cfg.jitter) |
| 164 | + .onRetry(listener) |
| 165 | + .build() |
| 166 | + } |
| 167 | + |
| 168 | + protected <T> HttpResponse<T> safeApply(CheckedSupplier action) { |
| 169 | + final retryOnException = (e -> e instanceof IOException) as Predicate<? extends Throwable> |
| 170 | + final retryOnStatusCode = ((HttpResponse<T> resp) -> resp.statusCode() in SERVER_ERRORS) as Predicate<HttpResponse<T>> |
| 171 | + final policy = retryPolicy(retryOnException, retryOnStatusCode) |
| 172 | + return Failsafe.with(policy).get(action) |
| 173 | + } |
| 174 | + |
| 175 | + static private final List<Integer> SERVER_ERRORS = [429,500,502,503,504] |
| 176 | + |
| 177 | + protected HttpResponse<String> httpSend(HttpRequest req) { |
| 178 | + return safeApply(() -> httpClient.send(req, HttpResponse.BodyHandlers.ofString())) |
| 179 | + } |
| 180 | +} |
0 commit comments