diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java index dc6b2ae8ff..dbfabf5231 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/PypiserverSidecarClient.java @@ -64,6 +64,7 @@ public class PypiserverSidecarClient implements RepositorySidecarManager { @Override public void release(String repositoryContainerId) { manager.release(repositoryContainerId); + SidecarConcurrency.release(repositoryContainerId); } /** @@ -155,42 +156,54 @@ public class PypiserverSidecarClient implements RepositorySidecarManager { * requests one at a time before returning even a single-result page. Keyed by {@code * repositoryContainerId} so the concurrency cap holds across simultaneous calls against the * same pypiserver container, not just within one of them. + * + *

The whole method runs between {@link SidecarConcurrency#beginUse} and {@link + * SidecarConcurrency#endUse}, not only the {@code mapBounded} call: a repository delete racing + * this call's own HTTP fetch of the version listing, before {@code mapBounded} is even reached, + * must not be able to run {@link SidecarConcurrency#release} to completion in between, or {@code + * mapBounded} would cache a fresh permit for a container that is already gone. */ @Override public List listPackageVersions(String repositoryContainerId, String domain, String repository, String namespace, String packageName) { - String baseUrl = ensureReady(repositoryContainerId, null); - String normalized = normalizePackageName(packageName); - URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.encodeSegment(normalized) - + "/json"); - HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build(); - HttpResponse response; + SidecarConcurrency.beginUse(repositoryContainerId); try { - response = httpClient.send(request, BodyHandlers.ofString()); - } catch (Exception e) { - throw new IllegalStateException("Could not reach the pypiserver sidecar to list versions of " - + packageName, e); + String baseUrl = ensureReady(repositoryContainerId, null); + String normalized = normalizePackageName(packageName); + URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.encodeSegment(normalized) + + "/json"); + HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build(); + HttpResponse response; + try { + response = httpClient.send(request, BodyHandlers.ofString()); + } catch (Exception e) { + throw new IllegalStateException("Could not reach the pypiserver sidecar to list versions of " + + packageName, e); + } + if (response.statusCode() == 404) { + return List.of(); + } + if (response.statusCode() != 200) { + throw new IllegalStateException("Could not list versions of " + packageName + " on the pypiserver " + + "sidecar: upstream returned " + response.statusCode()); + } + JsonNode releases; + try { + releases = mapper.readTree(response.body()).path("releases"); + } catch (Exception e) { + throw new IllegalStateException("Could not parse pypiserver's version listing for " + packageName, + e); + } + List versions = new ArrayList<>(); + releases.fieldNames().forEachRemaining(versions::add); + return SidecarConcurrency.mapBounded(repositoryContainerId, versions, version -> { + JsonNode files = releases.path(version); + String fileUrl = files.isEmpty() ? "" : files.get(0).path("url").asText(""); + return new PackageVersionTimestamp(version, fileUrl.isEmpty() ? null : lastModified(fileUrl)); + }); + } finally { + SidecarConcurrency.endUse(repositoryContainerId); } - if (response.statusCode() == 404) { - return List.of(); - } - if (response.statusCode() != 200) { - throw new IllegalStateException("Could not list versions of " + packageName + " on the pypiserver " - + "sidecar: upstream returned " + response.statusCode()); - } - JsonNode releases; - try { - releases = mapper.readTree(response.body()).path("releases"); - } catch (Exception e) { - throw new IllegalStateException("Could not parse pypiserver's version listing for " + packageName, e); - } - List versions = new ArrayList<>(); - releases.fieldNames().forEachRemaining(versions::add); - return SidecarConcurrency.mapBounded(repositoryContainerId, versions, version -> { - JsonNode files = releases.path(version); - String fileUrl = files.isEmpty() ? "" : files.get(0).path("url").asText(""); - return new PackageVersionTimestamp(version, fileUrl.isEmpty() ? null : lastModified(fileUrl)); - }); } private Instant lastModified(String fileUrl) { diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrency.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrency.java index 70358fe482..8af1a5dcd8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrency.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrency.java @@ -34,15 +34,35 @@ final class SidecarConcurrency { private static final int MAX_CONCURRENT_REQUESTS = 8; /** - * One {@link Semaphore} per sidecar container, shared across every {@code mapBounded} call for - * that container so {@link #MAX_CONCURRENT_REQUESTS} holds in aggregate: a per-call-only limit + * One entry per sidecar container, shared across every {@code mapBounded} call for that + * container so {@link #MAX_CONCURRENT_REQUESTS} holds in aggregate: a per-call-only limit * would let two simultaneous {@code listPackageVersions} calls against the same container each * open that many connections, doubling the real cap. The key is whatever identity a caller * already has for "which container": pypiserver's own {@code repositoryContainerId} (one * container per CodeArtifact repository), or a single shared constant for Reposilite (one - * container for every Maven repository). + * container for every Maven repository). Callers whose key dies with the container (pypiserver's + * {@code repositoryContainerId}, not Reposilite's shared constant) must bracket every call with + * {@link #beginUse} and {@link #endUse}, and call {@link #release} once that container is torn + * down, or this map grows by one entry for every repository ever deleted, for as long as the + * process runs. */ - private static final Map SIDECAR_PERMITS = new ConcurrentHashMap<>(); + private static final Map SIDECAR_PERMITS = new ConcurrentHashMap<>(); + + /** + * One sidecar container's {@link Semaphore} plus the bookkeeping {@link #beginUse}/{@link + * #endUse}/{@link #release} need to agree on when it is actually safe to drop this entry: + * {@code activeCalls} is the number of calls currently between {@link #beginUse} and {@link + * #endUse} for this key, and {@code releasing} records that {@link #release} ran while at least + * one of them was still in flight. Every field is only ever touched from inside a {@link + * Map#compute}/{@link Map#computeIfAbsent}/{@link Map#computeIfPresent} remapping function for + * this exact key, which {@link ConcurrentHashMap} runs under a lock scoped to that key, so plain + * (non-atomic) fields are safe here. + */ + private static final class ContainerUse { + private final Semaphore semaphore = new Semaphore(MAX_CONCURRENT_REQUESTS); + private int activeCalls; + private boolean releasing; + } /** * Virtual threads, not a platform-thread pool: {@code mapBounded} submits every item up front and @@ -82,7 +102,7 @@ final class SidecarConcurrency { } return result; } - Semaphore permits = SIDECAR_PERMITS.computeIfAbsent(sidecarKey, key -> new Semaphore(MAX_CONCURRENT_REQUESTS)); + Semaphore permits = SIDECAR_PERMITS.computeIfAbsent(sidecarKey, key -> new ContainerUse()).semaphore; List> futures = new ArrayList<>(items.size()); for (T item : items) { futures.add(EXECUTOR.submit(() -> runWithPermit(permits, perItem, item))); @@ -104,6 +124,49 @@ final class SidecarConcurrency { } } + /** + * Marks the start of one call against {@code sidecarKey}'s container, before that call does + * anything else against it (a {@code listPackageVersions} HTTP fetch happens before the + * {@link #mapBounded} that actually consumes the permit). Pairs with {@link #endUse} in a + * {@code try}/{@code finally} around the whole call: without this, a {@link #release} racing a + * call that has only fetched its version listing so far, and has not reached {@link #mapBounded} + * yet, would remove the entry before that call ever registers using it, and {@link #mapBounded} + * would then cache a brand new one for a container that is already gone, orphaned forever since + * nothing will call {@link #release} for that key a second time. + */ + static void beginUse(Object sidecarKey) { + SIDECAR_PERMITS.compute(sidecarKey, (key, existing) -> { + ContainerUse use = existing != null ? existing : new ContainerUse(); + use.activeCalls++; + return use; + }); + } + + /** Marks the end of one call {@link #beginUse} started, dropping the entry if {@link #release} + * ran while this was the last call still using it. */ + static void endUse(Object sidecarKey) { + SIDECAR_PERMITS.computeIfPresent(sidecarKey, (key, use) -> { + use.activeCalls--; + return use.activeCalls == 0 && use.releasing ? null : use; + }); + } + + /** + * Drops the cached permit for {@code sidecarKey} once its container has actually been torn + * down, unless a call already between {@link #beginUse} and {@link #endUse} is still using it, + * in which case the last matching {@link #endUse} drops it instead. A no-op (leaves nothing + * behind) if the key was never used. Only meaningful for a key tied to one container's lifetime + * (pypiserver's {@code repositoryContainerId}); never call this for Reposilite's shared constant, + * since its one container keeps serving every other Maven repository. + */ + static void release(Object sidecarKey) { + SIDECAR_PERMITS.compute(sidecarKey, (key, existing) -> { + ContainerUse use = existing != null ? existing : new ContainerUse(); + use.releasing = true; + return use.activeCalls == 0 ? null : use; + }); + } + private static R runWithPermit(Semaphore permits, Function perItem, T item) throws InterruptedException { permits.acquire(); diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrencyTest.java index 7eb0fe1079..4c218e4cfa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/SidecarConcurrencyTest.java @@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.codeartifact; import org.junit.jupiter.api.Test; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; @@ -15,6 +17,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -164,6 +168,69 @@ class SidecarConcurrencyTest { + "after item 1 had already failed"); } + @Test + void releaseDropsTheCachedPermitForASidecarKey() throws Exception { + Object key = new Object(); + SidecarConcurrency.mapBounded(key, List.of(1, 2), i -> i); + assertTrue(sidecarPermitsContainsKey(key), "expected mapBounded to have cached a permit for this key"); + + SidecarConcurrency.release(key); + + assertFalse(sidecarPermitsContainsKey(key), "expected release to drop the cached permit for this key, " + + "otherwise it leaks one Semaphore per repository ever deleted for the life of the process"); + } + + @Test + void releaseIsANoOpForAKeyThatWasNeverUsed() { + assertDoesNotThrow(() -> SidecarConcurrency.release(new Object())); + } + + @Test + void releaseDuringAnActiveUseDefersRemovalUntilTheMatchingEndUse() throws Exception { + Object key = new Object(); + SidecarConcurrency.beginUse(key); + assertTrue(sidecarPermitsContainsKey(key), "expected beginUse to register this key"); + + SidecarConcurrency.release(key); + assertTrue(sidecarPermitsContainsKey(key), "expected release to defer removal while a call is still " + + "using this key; otherwise a listPackageVersions call that fetched its version listing before " + + "the repository was deleted, but had not yet reached mapBounded, would cache a fresh permit " + + "for a container that is already gone, orphaned forever since nothing calls release twice"); + + SidecarConcurrency.endUse(key); + assertFalse(sidecarPermitsContainsKey(key), "expected the matching endUse to drop the entry once " + + "release had already marked it for removal"); + } + + @Test + void releaseWithNoActiveUseRemovesImmediately() throws Exception { + Object key = new Object(); + SidecarConcurrency.release(key); + assertFalse(sidecarPermitsContainsKey(key), "release on a key nobody is using must not leave anything " + + "behind"); + } + + @Test + void mapBoundedReusesThePermitABeginUseAlreadyCreated() throws Exception { + Object key = new Object(); + SidecarConcurrency.beginUse(key); + try { + List result = SidecarConcurrency.mapBounded(key, List.of(1, 2, 3), i -> i); + assertThat(result, equalTo(List.of(1, 2, 3))); + } finally { + SidecarConcurrency.endUse(key); + } + assertTrue(sidecarPermitsContainsKey(key), "expected endUse, with no release pending, to leave the " + + "cache entry alone instead of removing it"); + } + + private static boolean sidecarPermitsContainsKey(Object key) throws Exception { + Field field = SidecarConcurrency.class.getDeclaredField("SIDECAR_PERMITS"); + field.setAccessible(true); + Map permits = (Map) field.get(null); + return permits.containsKey(key); + } + @Test void mapBoundedCallsPerItemDirectlyWhenThereIsAtMostOneItem() { Set threadNames = ConcurrentHashMap.newKeySet();