|
| 1 | +package nextflow.plugin |
| 2 | + |
| 3 | +import com.google.gson.Gson |
| 4 | +import dev.failsafe.Failsafe |
| 5 | +import dev.failsafe.FailsafeExecutor |
| 6 | +import dev.failsafe.Fallback |
| 7 | +import dev.failsafe.RetryPolicy |
| 8 | +import dev.failsafe.event.EventListener |
| 9 | +import dev.failsafe.event.ExecutionAttemptedEvent |
| 10 | +import dev.failsafe.function.CheckedSupplier |
| 11 | +import groovy.transform.CompileStatic |
| 12 | +import groovy.util.logging.Slf4j |
| 13 | +import nextflow.BuildInfo |
| 14 | +import org.pf4j.PluginRuntimeException |
| 15 | +import org.pf4j.update.FileDownloader |
| 16 | +import org.pf4j.update.FileVerifier |
| 17 | +import org.pf4j.update.PluginInfo |
| 18 | +import org.pf4j.update.SimpleFileDownloader |
| 19 | +import org.pf4j.update.verifier.CompoundVerifier |
| 20 | + |
| 21 | +import java.net.http.HttpClient |
| 22 | +import java.net.http.HttpRequest |
| 23 | +import java.net.http.HttpResponse |
| 24 | + |
| 25 | +/** |
| 26 | + * Represents an update repository served via an HTTP api. |
| 27 | + * |
| 28 | + * It implements PrefetchUpdateRepository so that all relevant |
| 29 | + * plugin metadata can be loaded with a single HTTP request, rather |
| 30 | + * than a request-per-plugin. |
| 31 | + * |
| 32 | + * Metadata is prefetched into memory when Nextflow starts and expires |
| 33 | + * upon termination (or when 'refresh()' is called). |
| 34 | + */ |
| 35 | +@Slf4j |
| 36 | +@CompileStatic |
| 37 | +class HttpPluginRepository implements PrefetchUpdateRepository { |
| 38 | + private final HttpClient client = HttpClient.newHttpClient() |
| 39 | + private final String id |
| 40 | + private final URI url |
| 41 | + |
| 42 | + private Map<String, PluginInfo> plugins = new HashMap<>() |
| 43 | + |
| 44 | + HttpPluginRepository(String id, URI url) { |
| 45 | + this.id = id |
| 46 | + this.url = url |
| 47 | + } |
| 48 | + |
| 49 | + // NOTE ON PREFETCHING |
| 50 | + // |
| 51 | + // The prefetch mechanism is used to work around a limitation in the |
| 52 | + // UpdateRepository interface from pf4j. |
| 53 | + // |
| 54 | + // Specifically, p4fj expects that getPlugins() returns a Map<> of all |
| 55 | + // metadata about all plugins. To implement this for an HTTP repository |
| 56 | + // would require either downloading the entire contents of the remote |
| 57 | + // repository or implementing a lazy map and making an HTTP request for |
| 58 | + // each required plugin. |
| 59 | + // |
| 60 | + // Instead we can use the list of configured plugins to load all relevant |
| 61 | + // metadata in a single HTTP request at startup, and use this to populate |
| 62 | + // the map. Once the prefetch is complete, this repository will behave |
| 63 | + // like any other implementation of UpdateRepository. |
| 64 | + @Override |
| 65 | + void prefetch(List<PluginSpec> plugins) { |
| 66 | + if (plugins && !plugins.isEmpty()) { |
| 67 | + this.plugins = fetchMetadata(plugins) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + String getId() { |
| 73 | + return id |
| 74 | + } |
| 75 | + |
| 76 | + @Override |
| 77 | + URL getUrl() { |
| 78 | + return url.toURL() |
| 79 | + } |
| 80 | + |
| 81 | + @Override |
| 82 | + Map<String, PluginInfo> getPlugins() { |
| 83 | + if (plugins.isEmpty()) { |
| 84 | + log.warn "getPlugins() called before prefetch() - plugins map will be empty" |
| 85 | + return Map.of() |
| 86 | + } |
| 87 | + return Collections.unmodifiableMap(plugins) |
| 88 | + } |
| 89 | + |
| 90 | + @Override |
| 91 | + PluginInfo getPlugin(String id) { |
| 92 | + return plugins.computeIfAbsent(id) { key -> fetchMetadataByIds([key]).get(key) } |
| 93 | + } |
| 94 | + |
| 95 | + @Override |
| 96 | + void refresh() { |
| 97 | + plugins = fetchMetadataByIds(plugins.keySet()) |
| 98 | + } |
| 99 | + |
| 100 | + @Override |
| 101 | + FileDownloader getFileDownloader() { |
| 102 | + return new SimpleFileDownloader() |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + FileVerifier getFileVerifier() { |
| 107 | + return new CompoundVerifier() |
| 108 | + } |
| 109 | + |
| 110 | + // ---------------------------------------------------------------------------- |
| 111 | + // http handling |
| 112 | + |
| 113 | + private Map<String, PluginInfo> fetchMetadataByIds(Collection<String> ids) { |
| 114 | + def specs = ids.collect(id -> new PluginSpec(id, null)) |
| 115 | + return fetchMetadata(specs) |
| 116 | + } |
| 117 | + |
| 118 | + private Map<String, PluginInfo> fetchMetadata(Collection<PluginSpec> specs) { |
| 119 | + final ordered = specs.sort(false) |
| 120 | + final CheckedSupplier<Map<String, PluginInfo>> supplier = () -> fetchMetadata0(ordered) |
| 121 | + return retry().get(supplier) |
| 122 | + } |
| 123 | + |
| 124 | + private Map<String, PluginInfo> fetchMetadata0(List<PluginSpec> specs) { |
| 125 | + final gson = new Gson() |
| 126 | + |
| 127 | + def reqBody = gson.toJson([ |
| 128 | + 'nextflowVersion': BuildInfo.version, |
| 129 | + 'plugins' : specs |
| 130 | + ]) |
| 131 | + |
| 132 | + def req = HttpRequest.newBuilder() |
| 133 | + .uri(url.resolve("plugins/collect")) |
| 134 | + .POST(HttpRequest.BodyPublishers.ofString(reqBody)) |
| 135 | + .build() |
| 136 | + |
| 137 | + def rep = client.send(req, HttpResponse.BodyHandlers.ofString()) |
| 138 | + if (rep.statusCode() != 200) throw new PluginRuntimeException(errorMessage(rep, gson)) |
| 139 | + |
| 140 | + try { |
| 141 | + def repBody = gson.fromJson(rep.body(), FetchResponse) |
| 142 | + return repBody.plugins.collectEntries { p -> Map.entry(p.id, p) } |
| 143 | + } catch (Exception e) { |
| 144 | + log.info("Plugin metadata response body: '${rep.body()}'") |
| 145 | + throw new PluginRuntimeException("Failed to parse response body", e) |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + // create a retry executor using failsafe |
| 150 | + private static FailsafeExecutor retry() { |
| 151 | + EventListener<ExecutionAttemptedEvent> logAttempt = (ExecutionAttemptedEvent attempt) -> { |
| 152 | + log.debug("Retrying download of plugins metadata - attempt ${attempt.attemptCount}, ${attempt.lastFailure.message}", attempt.lastFailure) |
| 153 | + } |
| 154 | + Fallback fallback = Fallback.ofException { e -> |
| 155 | + e.lastFailure instanceof ConnectException |
| 156 | + ? new ConnectException("Failed to download plugins metadata") |
| 157 | + : new PluginRuntimeException("Failed to download plugin metadata: ${e.lastFailure.message}") |
| 158 | + } |
| 159 | + final policy = RetryPolicy.builder() |
| 160 | + .withMaxAttempts(3) |
| 161 | + .handle(ConnectException) |
| 162 | + .onRetry(logAttempt) |
| 163 | + .build() |
| 164 | + return Failsafe.with(fallback, policy) |
| 165 | + } |
| 166 | + |
| 167 | + private static String errorMessage(HttpResponse<String> rep, Gson gson) { |
| 168 | + try { |
| 169 | + def err = gson.fromJson(rep.body(), ErrorResponse) |
| 170 | + return "${err.type} - ${err.message}" |
| 171 | + } catch (Exception e) { |
| 172 | + return rep.body() |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + // --------------------- |
| 177 | + |
| 178 | + /** |
| 179 | + * Response format object expected from repository |
| 180 | + */ |
| 181 | + private static class FetchResponse { |
| 182 | + List<PluginInfo> plugins |
| 183 | + } |
| 184 | + |
| 185 | + private static class ErrorResponse { |
| 186 | + String type |
| 187 | + String message |
| 188 | + } |
| 189 | +} |
0 commit comments