mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
perf(codeartifact): parallelize per-version metadata fetches in ListPackageVersions (#6262)
Qodo follow-up from #6204: PypiserverSidecarClient and ReposiliteSidecarClient each made one sequential HTTP request per version (a HEAD per pypi release, a details GET per Maven version) before CodeArtifactService paginated, so even a one-result page waited on every version's own round trip. Both now run their per-version requests through a new shared SidecarConcurrency.mapBounded, capped at 8 concurrent requests per sidecar container. The cap is enforced by a shared, per-container permit (keyed by pypiserver's repositoryContainerId, or a single constant for Reposilite's one shared container) rather than a per-call-only limit, so two simultaneous listPackageVersions calls against the same container still can't exceed 8 requests between them. Tasks run on a virtual-thread-per-task executor, not a platform-thread pool: mapBounded submits every item up front and lets the semaphore do the real gating, so a package with thousands of versions doesn't start that many platform threads per call, each just parked in Semaphore.acquire(). A failure (or the caller being interrupted) also cancels the rest of the call's work, instead of leaving it running against the sidecar after the call has already failed. Results stay in input order and a failing item still fails the whole call, matching the original sequential behavior exactly. Verified with unit tests for the helper (ordering, the per-container concurrency cap, the cap holding across two simultaneous calls sharing a container, exception propagation, cancellation of the rest of the work after an early failure) and a 12-version Docker-gated test per format against the real pypiserver and Reposilite sidecars, on top of the existing single-version coverage.
This commit is contained in:
1 parent
6bc598fbfd
commit
581cd62790
6 files changed
+422
-11
No files matched your search
+42
@@ -20,7 +20,10 @@ import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -590,6 +593,45 @@ class CodeArtifactMavenDockerIntegrationTest {
|
||||
.body("versions[0].origin.originType", equalTo("INTERNAL"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The real-world gap this guards against: {@code ReposiliteSidecarClient#listPackageVersions}
|
||||
* used to fetch every version's publish-time details page one at a time, so a package with
|
||||
* many versions still answered no faster than its slowest version's own round trip, times the
|
||||
* version count. This deploys enough versions that a broken fan-out (dropped, duplicated, or
|
||||
* silently empty results from the bounded executor) would show up as something other than
|
||||
* exactly this set of versions, against the real Reposilite sidecar, not a mock.
|
||||
*/
|
||||
@Test
|
||||
@Order(22)
|
||||
void listPackageVersionsFetchesManyVersionsPublishTimesCorrectly() {
|
||||
String packageName = "manyversions";
|
||||
int versionCount = 12;
|
||||
Set<String> expectedVersions = new HashSet<>();
|
||||
for (int i = 1; i <= versionCount; i++) {
|
||||
String version = "1.0." + i;
|
||||
expectedVersions.add(version);
|
||||
byte[] content = ("many-versions-bytes-" + i).getBytes(StandardCharsets.UTF_8);
|
||||
given().header("Authorization", "Bearer " + bearerToken).body(content)
|
||||
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/" + packageName + "/" + version
|
||||
+ "/" + packageName + "-" + version + ".jar")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
JsonPath body = given().header("Authorization", AUTH)
|
||||
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=maven"
|
||||
+ "&namespace=com.example&package=" + packageName)
|
||||
.then().statusCode(200)
|
||||
.body("package", equalTo(packageName))
|
||||
.body("versions.size()", equalTo(versionCount))
|
||||
.extract().jsonPath();
|
||||
List<String> actualVersions = body.getList("versions.version", String.class);
|
||||
assertEquals(expectedVersions, new HashSet<>(actualVersions));
|
||||
String defaultDisplayVersion = body.getString("defaultDisplayVersion");
|
||||
assertTrue(expectedVersions.contains(defaultDisplayVersion),
|
||||
"expected defaultDisplayVersion to be one of the deployed versions, got "
|
||||
+ defaultDisplayVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* A throwaway groupId/artifactId, not {@link #GAV}: deleting it exercises Reposilite's real
|
||||
* directory delete (confirmed live before this was built: a single {@code DELETE} on the
|
||||
|
||||
+43
@@ -18,8 +18,10 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -728,6 +730,47 @@ class CodeArtifactPypiDockerIntegrationTest {
|
||||
throw new AssertionError("expected an asset named " + name + " among " + assets);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real-world gap this guards against: {@code PypiserverSidecarClient#listPackageVersions}
|
||||
* used to send one {@code HEAD} per version, one at a time, so a package with many versions
|
||||
* answered no faster than its slowest version's own round trip, times the version count. This
|
||||
* uploads enough versions that a broken fan-out (dropped, duplicated, or silently empty results
|
||||
* from the bounded executor) would show up as something other than exactly this set of
|
||||
* versions, against the real pypiserver sidecar, not a mock.
|
||||
*/
|
||||
@Test
|
||||
@Order(21)
|
||||
void listPackageVersionsFetchesManyVersionsPublishTimesCorrectly() {
|
||||
String packageName = "many-versions-pypi-pkg";
|
||||
int versionCount = 12;
|
||||
Set<String> expectedVersions = new HashSet<>();
|
||||
for (int i = 1; i <= versionCount; i++) {
|
||||
String version = "1.0." + i;
|
||||
expectedVersions.add(version);
|
||||
String filename = "many_versions_pypi_pkg-" + version + ".tar.gz";
|
||||
byte[] content = ("many-versions-sdist-bytes-" + i).getBytes(StandardCharsets.UTF_8);
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(twineUploadBody("boundary123", packageName, filename, content))
|
||||
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
JsonPath body = given().header("Authorization", AUTH)
|
||||
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=pypi"
|
||||
+ "&package=" + packageName)
|
||||
.then().statusCode(200)
|
||||
.body("package", equalTo(packageName))
|
||||
.body("versions.size()", equalTo(versionCount))
|
||||
.extract().jsonPath();
|
||||
List<String> actualVersions = body.getList("versions.version", String.class);
|
||||
assertEquals(expectedVersions, new HashSet<>(actualVersions));
|
||||
String defaultDisplayVersion = body.getString("defaultDisplayVersion");
|
||||
assertTrue(expectedVersions.contains(defaultDisplayVersion),
|
||||
"expected defaultDisplayVersion to be one of the uploaded versions, got "
|
||||
+ defaultDisplayVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves the actual mechanism, not just that {@code PypiserverSidecarManager} has a method
|
||||
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Focused unit coverage for the bounded-fan-out helper {@code PypiserverSidecarClient} and {@code
|
||||
* ReposiliteSidecarClient} both use to parallelize their per-version {@code listPackageVersions}
|
||||
* requests. These tests use plain in-process work, not real HTTP, to pin down the properties that
|
||||
* matter: results come back in input order regardless of completion order, more than {@code
|
||||
* MAX_CONCURRENT_REQUESTS} items never run at once against one sidecar key (even across two
|
||||
* simultaneous calls sharing that key), a failing item fails the whole call with its own real
|
||||
* exception rather than a wrapped or swallowed one, and the rest of the work is cancelled rather
|
||||
* than left running after a failure.
|
||||
*/
|
||||
class SidecarConcurrencyTest {
|
||||
|
||||
@Test
|
||||
void mapBoundedPreservesInputOrderRegardlessOfCompletionOrder() {
|
||||
List<Integer> items = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
List<String> result = SidecarConcurrency.mapBounded(new Object(), items, i -> {
|
||||
// Later items sleep less, so they would finish first if order depended on completion.
|
||||
try {
|
||||
Thread.sleep((11 - i) % 4);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
fail("interrupted");
|
||||
}
|
||||
return "v" + i;
|
||||
});
|
||||
assertThat(result, equalTo(List.of("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapBoundedNeverRunsMoreThanTheConcurrencyCapAtOnce() throws InterruptedException {
|
||||
int itemCount = 32;
|
||||
List<Integer> items = new ArrayList<>(itemCount);
|
||||
for (int i = 0; i < itemCount; i++) {
|
||||
items.add(i);
|
||||
}
|
||||
AtomicInteger concurrent = new AtomicInteger();
|
||||
AtomicInteger maxObserved = new AtomicInteger();
|
||||
CountDownLatch allDone = new CountDownLatch(1);
|
||||
Thread worker = new Thread(() -> {
|
||||
SidecarConcurrency.mapBounded(new Object(), items, i -> {
|
||||
int current = concurrent.incrementAndGet();
|
||||
maxObserved.getAndUpdate(previous -> Math.max(previous, current));
|
||||
try {
|
||||
Thread.sleep(20);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
concurrent.decrementAndGet();
|
||||
return i;
|
||||
});
|
||||
allDone.countDown();
|
||||
});
|
||||
worker.start();
|
||||
assertTrue(allDone.await(10, TimeUnit.SECONDS), "mapBounded did not finish in time");
|
||||
assertTrue(maxObserved.get() <= 8, "expected at most 8 concurrent items, saw " + maxObserved.get());
|
||||
assertTrue(maxObserved.get() > 1, "expected real parallelism, saw " + maxObserved.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapBoundedCapsConcurrencyAcrossSimultaneousCallsSharingTheSameSidecarKey() throws InterruptedException {
|
||||
Object sharedKey = new Object();
|
||||
int itemsPerCall = 6;
|
||||
List<Integer> items = new ArrayList<>(itemsPerCall);
|
||||
for (int i = 0; i < itemsPerCall; i++) {
|
||||
items.add(i);
|
||||
}
|
||||
AtomicInteger concurrent = new AtomicInteger();
|
||||
AtomicInteger maxObserved = new AtomicInteger();
|
||||
Runnable call = () -> SidecarConcurrency.mapBounded(sharedKey, items, i -> {
|
||||
int current = concurrent.incrementAndGet();
|
||||
maxObserved.getAndUpdate(previous -> Math.max(previous, current));
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
concurrent.decrementAndGet();
|
||||
return i;
|
||||
});
|
||||
Thread callA = new Thread(call);
|
||||
Thread callB = new Thread(call);
|
||||
callA.start();
|
||||
callB.start();
|
||||
callA.join(10_000);
|
||||
callB.join(10_000);
|
||||
assertThat("two simultaneous calls sharing one sidecar key must not exceed the shared cap in aggregate",
|
||||
maxObserved.get(), lessThanOrEqualTo(8));
|
||||
assertThat("expected the two calls' work to actually overlap under the shared cap", maxObserved.get(),
|
||||
greaterThan(itemsPerCall));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapBoundedPropagatesARuntimeExceptionFromAFailingItemUnwrapped() {
|
||||
List<Integer> items = List.of(1, 2, 3);
|
||||
IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> SidecarConcurrency.mapBounded(
|
||||
new Object(), items, i -> {
|
||||
if (i == 2) {
|
||||
throw new IllegalStateException("boom on " + i);
|
||||
}
|
||||
return i;
|
||||
}));
|
||||
assertThat(thrown.getMessage(), equalTo("boom on 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapBoundedCancelsTheOtherItemAfterAnEarlyFailure() throws InterruptedException {
|
||||
CountDownLatch otherItemStarted = new CountDownLatch(1);
|
||||
CountDownLatch otherItemFinished = new CountDownLatch(1);
|
||||
CountDownLatch neverOpens = new CountDownLatch(1);
|
||||
AtomicBoolean otherItemInterrupted = new AtomicBoolean(false);
|
||||
assertThrows(IllegalStateException.class, () -> SidecarConcurrency.mapBounded(new Object(), List.of(1, 2),
|
||||
i -> {
|
||||
if (i == 1) {
|
||||
// Only fail once item 2 is actually running and blocked, so this exercises real
|
||||
// cancellation of in-flight work instead of racing against whether item 2's task
|
||||
// had even been scheduled yet.
|
||||
boolean started;
|
||||
try {
|
||||
started = otherItemStarted.await(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
started = false;
|
||||
}
|
||||
if (!started) {
|
||||
throw new IllegalStateException("item 2 never started");
|
||||
}
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
otherItemStarted.countDown();
|
||||
try {
|
||||
neverOpens.await();
|
||||
} catch (InterruptedException e) {
|
||||
otherItemInterrupted.set(true);
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
otherItemFinished.countDown();
|
||||
}
|
||||
return i;
|
||||
}));
|
||||
assertTrue(otherItemFinished.await(5, TimeUnit.SECONDS), "expected mapBounded to cancel item 2 once item "
|
||||
+ "1 had already failed, instead of leaving it blocked indefinitely");
|
||||
assertTrue(otherItemInterrupted.get(), "expected item 2 to be interrupted rather than complete normally "
|
||||
+ "after item 1 had already failed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapBoundedCallsPerItemDirectlyWhenThereIsAtMostOneItem() {
|
||||
Set<String> threadNames = ConcurrentHashMap.newKeySet();
|
||||
List<Integer> result = SidecarConcurrency.mapBounded(new Object(), List.of(42), i -> {
|
||||
threadNames.add(Thread.currentThread().getName());
|
||||
return i;
|
||||
});
|
||||
assertThat(result, equalTo(List.of(42)));
|
||||
assertThat(threadNames, equalTo(Set.of(Thread.currentThread().getName())));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user