refactor(codeartifact): split the Verdaccio sidecar into a manager and a client (#5234)

VerdaccioSidecarManager now owns only the container lifecycle: starting,
readiness, release, and teardown. The HTTP protocol moves to
VerdaccioSidecarClient, which implements RepositorySidecarManager and is what
the registry and the npm data plane use, matching the Reposilite pair.

Wire-contract tests move to VerdaccioSidecarClientTest against a JDK
HttpServer fake. No behavior changes.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-07 07:43:26 -05:00
1 parent 4495ade6bb
commit a927c5aac6
8 files changed
+536 -491

No files matched your search

@@ -67,7 +67,7 @@ public class CodeArtifactNpmDataPlane {
"te", "trailers", "transfer-encoding", "upgrade", "authorization", "host");
private final CodeArtifactService service;
private final VerdaccioSidecarManager verdaccioManager;
private final VerdaccioSidecarClient verdaccioClient;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
private final HttpClient proxyClient;
@@ -76,10 +76,10 @@ public class CodeArtifactNpmDataPlane {
private final PreflightGate preflights = new PreflightGate(MAX_CONCURRENT_PREFLIGHTS, MAX_QUEUED_PREFLIGHTS);
@Inject
public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager,
public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient,
ServiceConfigAccess serviceConfigAccess, Vertx vertx, ObjectMapper mapper) {
this.service = service;
this.verdaccioManager = verdaccioManager;
this.verdaccioClient = verdaccioClient;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
this.proxyClient = vertx.createHttpClient(new HttpClientOptions()
@@ -341,8 +341,8 @@ public class CodeArtifactNpmDataPlane {
}
private String ensureBackendReady(String npmRepositoryId, NpmRequest npmRequest) {
return verdaccioManager.ensureReady(npmRepositoryId,
verdaccioManager.publicUrl(npmRequest.domain(), npmRequest.repository()));
return verdaccioClient.ensureReady(npmRepositoryId,
verdaccioClient.publicUrl(npmRequest.domain(), npmRequest.repository()));
}
/**
@@ -364,7 +364,7 @@ public class CodeArtifactNpmDataPlane {
}
Optional<JsonNode> storedDocument;
try {
storedDocument = verdaccioManager.fetchPackageDocument(backendBaseUrl, identity.namespace(),
storedDocument = verdaccioClient.fetchPackageDocument(backendBaseUrl, identity.namespace(),
identity.packageName());
} catch (IllegalStateException e) {
LOG.warnv(e, "Could not check {0}/{1} for an existing match before publishing: {2}",
@@ -376,7 +376,7 @@ public class CodeArtifactNpmDataPlane {
}
for (NpmPublishEnvelopeScanner.Version version : envelope.versions().values()) {
try {
Optional<String> stored = verdaccioManager.storedTarballIntegrity(backendBaseUrl,
Optional<String> stored = verdaccioClient.storedTarballIntegrity(backendBaseUrl,
identity.namespace(), identity.packageName(), tarballFilename(version.tarball()));
if (stored.isEmpty() || !stored.get().equals(version.integrity())) {
return false;
@@ -676,7 +676,7 @@ public class CodeArtifactService implements Resettable {
String owner = effectiveOwner(domainOwner);
// Maven, npm, and pypi are metadata-free passthroughs straight to their own sidecar
// (ReposiliteSidecarClient/VerdaccioSidecarManager/PypiserverSidecarManager): publish for
// (ReposiliteSidecarClient/VerdaccioSidecarClient/PypiserverSidecarManager): publish for
// these formats never goes through publishPackageVersion (it only ever accepts "generic"),
// so packageVersions can never hold a record for them. Bridge straight to the sidecar
// that actually has the asset instead of always 404ing here.
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;
/**
* The HTTP wire protocol for a Verdaccio sidecar: package metadata, tarball fetches, and stored
* integrity checks. Container lifecycle (start, readiness, stop) is {@link VerdaccioSidecarManager}'s
* job; this class asks it for a ready base URL and speaks Verdaccio's own protocol against it.
*
* <p>{@code namespace} is the npm scope without its leading {@code @}, or {@code null} for an
* unscoped package. Every path segment is percent-encoded on its own via
* {@link SidecarUriUtils#encodeSegment(String)} before the real {@code /} separators are added here,
* so a caller-supplied value cannot splice in extra path segments.
*/
@ApplicationScoped
public class VerdaccioSidecarClient implements RepositorySidecarManager {
private final VerdaccioSidecarManager manager;
private final EmulatorConfig config;
private final ObjectMapper mapper;
private final HttpClient httpClient;
@Inject
public VerdaccioSidecarClient(VerdaccioSidecarManager manager, EmulatorConfig config, ObjectMapper mapper) {
this(manager, config, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
VerdaccioSidecarClient(VerdaccioSidecarManager manager, EmulatorConfig config, ObjectMapper mapper,
HttpClient httpClient) {
this.manager = manager;
this.config = config;
this.mapper = mapper;
this.httpClient = httpClient;
}
@Override
public String format() {
return "npm";
}
@Override
public String ensureReady(String repositoryContainerId, String publicUrl) {
return manager.ensureReady(repositoryContainerId, publicUrl);
}
@Override
public void release(String repositoryContainerId) {
manager.release(repositoryContainerId);
}
/** The public URL a Verdaccio sidecar is told to advertise for one npm repository. */
public String publicUrl(String domain, String repository) {
return config.effectiveBaseUrl() + "/codeartifact/npm/" + domain + "/" + repository + "/";
}
/**
* Confirms {@code version} maps to {@code assetName} in the package's own metadata before fetching
* the tarball, rather than serving whatever file that name resolves to under a version the caller
* never published.
*/
@Override
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version, String assetName) {
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
if (!versionHasAsset(baseUrl, packagePath(namespace, packageName), version, assetName)) {
return Optional.empty();
}
return fetchTarball(baseUrl, namespace, packageName, assetName);
}
/**
* The package's metadata document as Verdaccio serves it, or empty when the package isn't there.
* {@code baseUrl} is a backend already made ready by {@link #ensureReady}.
*/
public Optional<JsonNode> fetchPackageDocument(String baseUrl, String namespace, String packageName) {
return packageDocument(baseUrl, packagePath(namespace, packageName));
}
/** One tarball by its filename, from a backend already made ready by {@link #ensureReady}. */
public Optional<byte[]> fetchTarball(String baseUrl, String namespace, String packageName, String assetName) {
HttpRequest request = tarballRequest(baseUrl, namespace, packageName, assetName);
HttpResponse<byte[]> response;
try {
response = httpClient.send(request, BodyHandlers.ofByteArray());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to fetch " + assetName, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
return Optional.of(response.body());
}
/**
* The SHA-512 integrity of a stored tarball, computed by streaming its bytes so the file never
* sits in memory. Empty when the tarball is not there.
*/
public Optional<String> storedTarballIntegrity(String baseUrl, String namespace, String packageName,
String assetName) {
HttpResponse<InputStream> response;
try {
response = httpClient.send(tarballRequest(baseUrl, namespace, packageName, assetName),
BodyHandlers.ofInputStream());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to hash " + assetName, e);
}
try (InputStream body = response.body()) {
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
MessageDigest digest = sha512();
byte[] chunk = new byte[64 * 1024];
for (int read = body.read(chunk); read != -1; read = body.read(chunk)) {
digest.update(chunk, 0, read);
}
return Optional.of("sha512-" + Base64.getEncoder().encodeToString(digest.digest()));
} catch (IOException e) {
throw new IllegalStateException("Could not read " + assetName + " from the Verdaccio sidecar", e);
}
}
private static String packagePath(String namespace, String packageName) {
return namespace == null
? SidecarUriUtils.encodeSegment(packageName)
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName);
}
private HttpRequest tarballRequest(String baseUrl, String namespace, String packageName, String assetName) {
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath(namespace, packageName) + "/-/"
+ SidecarUriUtils.encodeSegment(assetName));
return HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
}
private Optional<JsonNode> packageDocument(String baseUrl, String packagePath) {
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> response;
try {
response = httpClient.send(request, BodyHandlers.ofString());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to look up " + packagePath, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not look up " + packagePath + " on the Verdaccio sidecar: "
+ "upstream returned " + response.statusCode());
}
try {
return Optional.of(mapper.readTree(response.body()));
} catch (Exception e) {
throw new IllegalStateException("Could not parse Verdaccio's package metadata for " + packagePath, e);
}
}
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
Optional<JsonNode> document = packageDocument(baseUrl, packagePath);
if (document.isEmpty()) {
return false;
}
JsonNode versionNode = document.get().path("versions").path(version);
if (versionNode.isMissingNode()) {
return false;
}
String tarballUrl = versionNode.path("dist").path("tarball").asText("");
String tarballFilename = tarballUrl.substring(tarballUrl.lastIndexOf('/') + 1);
return assetName.equals(tarballFilename);
}
private static MessageDigest sha512() {
try {
return MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-512 is required by every Java runtime", e);
}
}
}
@@ -1,7 +1,5 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -20,45 +18,17 @@ import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;
/**
* Lazily starts and manages one Verdaccio container per CodeArtifact repository backing the
* {@code npm} format. Unlike Reposilite (Maven), Verdaccio has no native concept of multiple
* named repositories inside one instance, so npm repositories each get their own container
* instead of sharing one the way {@link ReposiliteSidecarManager} does. The actual per-key
* container lifecycle (map of running containers, per-key start lock, health poll,
* restart-on-unhealthy, stop-all on shutdown) is generic and lives in
* {@link PerKeyContainerPool}; this class only knows how to build and configure a Verdaccio
* container specifically.
*
* <p>Each container is configured with open access (no auth, no upstream proxying) since the
* real CodeArtifact authorization check happens once at Floci's proxy layer
* ({@code CodeArtifactNpmDataPlane}), before a request ever reaches the container; the container
* itself is never reachable directly by a client.
*
* <p>Implements {@link ContainerTeardown} rather than observing {@code ShutdownEvent} directly:
* {@code ContainerTeardowns.stopAll} already runs every implementation both at process shutdown
* and on {@code /state/reset}/{@code /state/nuke}, so this is what actually stops every
* repository's container on reset, driven by what {@link #pool} is really tracking rather than by
* which repository records still exist in storage.
* Starts and stops one Verdaccio container per CodeArtifact npm repository, unlike Reposilite's one
* shared instance. The HTTP protocol lives in {@link VerdaccioSidecarClient}. Implements
* {@link ContainerTeardown} so reset, nuke, and shutdown stop every container this manager started.
*/
@ApplicationScoped
public class VerdaccioSidecarManager implements RepositorySidecarManager, ContainerTeardown {
public class VerdaccioSidecarManager implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(VerdaccioSidecarManager.class);
private static final String FORMAT = "npm";
private static final int VERDACCIO_PORT = 4873;
private static final String HEALTH_PATH = "/-/ping";
private static final String CONFIG_REMOTE_DIR = "/verdaccio/conf";
@@ -92,199 +62,30 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
private final PerKeyContainerPool pool;
private final HttpClient httpClient;
private final ObjectMapper mapper;
@Inject
public VerdaccioSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
EmulatorConfig config, ObjectMapper mapper) {
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.config = config;
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
this.mapper = mapper;
}
@Override
public String format() {
return FORMAT;
}
/**
* Base URL of a ready Verdaccio instance for this npm repository, starting its container if
* this is the first use. Each repository's container is independent, so concurrent first-use
* of two different repositories never blocks on each other (unlike Reposilite's one shared
* instance, which does need a single lock around every provisioning call).
*
* @param publicUrl the externally reachable proxy URL for this specific repository (e.g.
* {@code http://localhost:4566/codeartifact/npm/<domain>/<repository>/}),
* passed to the container as {@code VERDACCIO_PUBLIC_URL} so package metadata
* it returns (notably {@code dist.tarball}) points back through Floci's proxy
* instead of the container's own internal, unreachable-by-the-client address.
* Base URL of a ready Verdaccio for this repository, starting its container on first use.
* {@code publicUrl} becomes {@code VERDACCIO_PUBLIC_URL}, so the {@code dist.tarball} links it
* returns point back through Floci's proxy.
*/
@Override
public String ensureReady(String npmRepositoryId, String publicUrl) {
return pool.ensureReady(npmRepositoryId, () -> startContainer(npmRepositoryId, publicUrl));
}
/** Stops and removes the container for one npm repository, if one was ever started. */
@Override
public void release(String npmRepositoryId) {
pool.stopContainer(npmRepositoryId);
}
/**
* {@code namespace} is the npm scope without its leading {@code @}, or {@code null} for an
* unscoped package; real npm (and Verdaccio, confirmed against a live container) serves every
* version's tarball at {@code <scoped-or-plain-name>/-/<filename>}, with the scope, if any,
* still carrying its {@code @} in that path even though the filename itself never includes it.
*
* <p>The tarball path alone is keyed by filename, not version: a package's own metadata is
* checked first (its {@code versions.<version>.dist.tarball} entry) to confirm {@code version}
* genuinely maps to {@code assetName} before fetching it, rather than serving whatever file
* that name happens to resolve to under a version the caller never actually published.
*
* <p>{@code namespace}, {@code packageName}, and {@code assetName} are each their own
* independently caller-supplied value, only meant to be one path segment; {@code
* packagePath} and the final {@code /-/<assetName>} suffix supply the real {@code /}
* separators themselves, around each value already percent-encoded on its own via
* {@link SidecarUriUtils#encodeSegment(String)}. Without that, a {@code /} inside, say,
* {@code assetName} would be indistinguishable from one of those real separators and could
* splice in extra path segments.
*/
@Override
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
String namespace, String packageName, String version, String assetName) {
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
if (!versionHasAsset(baseUrl, packagePath(namespace, packageName), version, assetName)) {
return Optional.empty();
}
return fetchTarball(baseUrl, namespace, packageName, assetName);
}
/** The public URL a Verdaccio sidecar is told to advertise for one npm repository. */
public String publicUrl(String domain, String repository) {
return config.effectiveBaseUrl() + "/codeartifact/npm/" + domain + "/" + repository + "/";
}
private static String packagePath(String namespace, String packageName) {
return namespace == null
? SidecarUriUtils.encodeSegment(packageName)
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName);
}
/**
* The package's metadata document as Verdaccio serves it, or empty when the package isn't
* there. {@code baseUrl} is a backend already made ready by {@link #ensureReady}, so repeated
* calls for one publish don't each pay another readiness probe.
*/
public Optional<JsonNode> fetchPackageDocument(String baseUrl, String namespace, String packageName) {
return packageDocument(baseUrl, packagePath(namespace, packageName));
}
/** One tarball by its filename, from a backend already made ready by {@link #ensureReady}. */
public Optional<byte[]> fetchTarball(String baseUrl, String namespace, String packageName, String assetName) {
HttpRequest request = tarballRequest(baseUrl, namespace, packageName, assetName);
HttpResponse<byte[]> response;
try {
response = httpClient.send(request, BodyHandlers.ofByteArray());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to fetch " + assetName, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
return Optional.of(response.body());
}
/**
* The SHA-512 integrity of a stored tarball, computed by streaming its bytes so the file never
* sits in memory. Empty when the tarball is not there.
*/
public Optional<String> storedTarballIntegrity(String baseUrl, String namespace, String packageName,
String assetName) {
HttpResponse<InputStream> response;
try {
response = httpClient.send(tarballRequest(baseUrl, namespace, packageName, assetName),
BodyHandlers.ofInputStream());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to hash " + assetName, e);
}
try (InputStream body = response.body()) {
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not fetch " + assetName
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
}
MessageDigest digest = sha512();
byte[] chunk = new byte[64 * 1024];
for (int read = body.read(chunk); read != -1; read = body.read(chunk)) {
digest.update(chunk, 0, read);
}
return Optional.of("sha512-" + Base64.getEncoder().encodeToString(digest.digest()));
} catch (IOException e) {
throw new IllegalStateException("Could not read " + assetName + " from the Verdaccio sidecar", e);
}
}
private HttpRequest tarballRequest(String baseUrl, String namespace, String packageName, String assetName) {
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath(namespace, packageName) + "/-/"
+ SidecarUriUtils.encodeSegment(assetName));
return HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
}
private static MessageDigest sha512() {
try {
return MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-512 is required by every Java runtime", e);
}
}
private Optional<JsonNode> packageDocument(String baseUrl, String packagePath) {
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> response;
try {
response = httpClient.send(request, BodyHandlers.ofString());
} catch (Exception e) {
throw new IllegalStateException("Could not reach the Verdaccio sidecar to look up " + packagePath, e);
}
if (response.statusCode() == 404) {
return Optional.empty();
}
if (response.statusCode() != 200) {
throw new IllegalStateException("Could not look up " + packagePath + " on the Verdaccio sidecar: "
+ "upstream returned " + response.statusCode());
}
try {
return Optional.of(mapper.readTree(response.body()));
} catch (Exception e) {
throw new IllegalStateException("Could not parse Verdaccio's package metadata for " + packagePath, e);
}
}
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
Optional<JsonNode> document = packageDocument(baseUrl, packagePath);
if (document.isEmpty()) {
return false;
}
JsonNode versionNode = document.get().path("versions").path(version);
if (versionNode.isMissingNode()) {
return false;
}
String tarballUrl = versionNode.path("dist").path("tarball").asText("");
String tarballFilename = tarballUrl.substring(tarballUrl.lastIndexOf('/') + 1);
return assetName.equals(tarballFilename);
}
private PerKeyContainerPool.StartedContainer startContainer(String npmRepositoryId, String publicUrl) {
String image = config.services().codeartifact().npmImage();
String containerName = ContainerStorageHelper.dockerName(config, "floci-verdaccio-" + npmRepositoryId);