mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codeartifact): retain npm packages from a public external connection (#7198)
npm's native registry route can now retain a missing package from a repository's own public:npmjs external connection and serve it, instead of always 404ing, mirroring the AWS-documented external-connection behavior already shipped for Maven (#6889) and NuGet (#7104). Unlike Maven's GAV layout and NuGet's {id}/{version}/{filename} content route, npm's own real wire protocol has no request shape that names one version: npm install <pkg>@<version> always fetches the bare package's full packument first (confirmed against pacote's own source, RegistryFetcher#packumentUrl, always the bare package path) and only picks the version out of its own versions map afterward. So this does two things together, not just one: - A bare packument read (the one every real npm install actually sends) merges the real registry's own versions and dist-tags into whatever Verdaccio already knows locally, computed fresh per request and never written to Verdaccio itself (its own publish protocol has no way to record a version's metadata without that version's real tarball bytes in the very same call, confirmed against a live container). Every newly-merged version's dist.tarball is rewritten to this repository's own proxy URL under a deterministic <bareName>-<version>.tgz shape; dist.shasum/dist.integrity are kept exactly as the real registry declared them, since there is no real content yet to hash locally. - A tarball download for a version not yet genuinely retained triggers the real fetch, the same claim/fence/origin-tracking machinery Maven and NuGet already use (closing the same race against a concurrent DeletePackageVersions/direct push), reusing CodeArtifactService's already-generalized claimRetainedVersionOrigin/retainAssetUnderVersionFence methods directly. New: NpmExternalConnectionClient (the outbound client for public:npmjs) and CodeArtifactNpmExternalConnectionImporter (the merge and retention logic), wired into CodeArtifactNpmDataPlane's existing raw proxy. Deliberately scoped the same way Maven/NuGet's own base PRs were: no caching/TTL on the merge fetch (a live check against the real registry on every packument read for a connected repository, matching the same no-caching fidelity level Maven's own maven-metadata.xml merge already ships with), and the documented but rarely-used single-version registry endpoint (GET /<pkg>/<version>) is not specially handled, since real npm install never sends it either. Update: fixed three issues Greptile's review caught, all specific to npm's own two-step retention (a plain cache-miss asset fetch, as NuGet/Maven's retention already was, is not enough here): - retainAssetUnderVersionFence's own write was always the fixed RepositorySidecarManager# storePackageVersionAsset call, which builds a minimal version document with no dependencies/ engines/scripts. Generalized it to take the actual write as a plain Runnable instead, so npm's own call can reuse the real registry's full-form version document verbatim (the same reuse-the-source-document treatment VerdaccioSidecarClient#copyPackageVersionAsset already gives a version copied from another repository), fetched once, only when a version is actually retained, via a new NpmExternalConnectionClient#fetchFullPackument. NuGet's own call site wraps the exact same plain storePackageVersionAsset call it always made. - Verdaccio always points a fresh package's dist-tags.latest at whichever version was retained most recently (confirmed live, nothing a retention write sends can suppress it), so a plain retention could silently move what an unpinned npm install or ListPackageVersions' defaultDisplayVersion resolves to. Fixed on both sides of that same bug: the merge now only lets an external dist-tag replace a local one that itself points at an externally-retained version, and CodeArtifactService#listPackageVersions ignores preferredDisplayVersion the same way when it names one. - A retained version's readme was never captured, so GetPackageVersionReadme 404ed on it even though the tarball existed; the full packument fetch above also captures the package's own readme (confirmed live: it only ever lives at the top of the full packument, never per version) the same way a native publish's own readme capture already works. Verified two ways beyond the automated suite: - A Docker-gated integration test retains a real package (is-even 1.0.0) from the real, live npmjs.com, through a real Verdaccio sidecar: a bare packument read merges the real version in without yet counting any bytes, a subsequent tarball fetch retains it and counts its bytes, a refetch does not double-count, mixed-case-irrelevant upstream-block enforcement blocks both the merge and the retention, a genuinely-missing package stays 404, the retained version's EXTERNAL origin reporting is confirmed against the real sidecar, and its real dependencies/ engines and readme are confirmed readable back from the real sidecar afterward. - Direct curl checks against the real registry.npmjs.org confirmed the exact packument/tarball URL shapes this client builds, including the %2F-escaped scope separator the packument endpoint specifically needs (unlike the tarball path, which uses a literal slash), and that the abbreviated packument form carries dependencies/engines but not scripts or any readme. Update: fixed a fourth issue from the same re-review, found once the three fixes above landed: mergedPackument always fetched the real registry's abbreviated form, even when the real npm client's own Accept header asked for the full one (the shape npm view <pkg> readme-style commands use), so a package the merge had not yet retained anything for showed no readme at all. The merge now honors that header, fetching the real full packument only when the request actually asked for it, and copies its package-level descriptive fields (readme among them) in the same never-override-local way everything else here already merges, with no change to the hot npm install path's own abbreviated fetch. Update 3: fixed a fifth issue from the same re-review: mergedPackument's own real registry fetch is a genuine network round trip, and nothing held any lock across it, so a DeleteRepository finishing its own cleanup while that fetch was still in flight let the later ensureReady call start a fresh container under an id the delete had already released, one nothing would ever release again. Added a re-check that the repository still exists right after that fetch, before this method ever touches the sidecar. This narrows the window back down to an ordinary check-then-act gap rather than one stretched out by a real network round trip, not a full fix: VerdaccioSidecarManager's own beginUse/endUse are no-ops today (unlike PypiserverSidecarManager's), so nothing here can fully close this yet. Filed #7204 to track giving it real in-flight-use tracking as its own, cross-cutting fix. Update 4: fixed a sixth issue from the same re-review: DisposePackageVersions deletes a version's real Verdaccio content outright, so versions.has(version) alone could not tell a disposed version apart from one never retained at all, and the merge could add a disposed version straight back in from the real registry's own still-unaware listing, even pointing dist-tags.latest at it. An unpinned npm install could then select it, only to have the download correctly, but confusingly, fail. The merge now excludes any externally-named version this repository has marked Archived or Disposed, reusing the same requireContainerBackedVersionDownloadable check the native download route itself already enforces.
This commit is contained in:
1 parent
dfaab8ba4c
commit
b3bee2d407
13 files changed
+2121
-35
No files matched your search
+126
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.codeartifact;
|
||||
import com.fasterxml.jackson.core.exc.StreamConstraintsException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
@@ -71,6 +72,7 @@ public class CodeArtifactNpmDataPlane {
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final VerdaccioSidecarClient verdaccioClient;
|
||||
private final CodeArtifactNpmExternalConnectionImporter externalConnectionImporter;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
private final Vertx vertx;
|
||||
private final HttpClient proxyClient;
|
||||
@@ -80,9 +82,11 @@ public class CodeArtifactNpmDataPlane {
|
||||
|
||||
@Inject
|
||||
public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarClient verdaccioClient,
|
||||
CodeArtifactNpmExternalConnectionImporter externalConnectionImporter,
|
||||
ServiceConfigAccess serviceConfigAccess, Vertx vertx, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.verdaccioClient = verdaccioClient;
|
||||
this.externalConnectionImporter = externalConnectionImporter;
|
||||
this.serviceConfigAccess = serviceConfigAccess;
|
||||
this.vertx = vertx;
|
||||
this.proxyClient = vertx.createHttpClient(new HttpClientOptions()
|
||||
@@ -149,12 +153,45 @@ public class CodeArtifactNpmDataPlane {
|
||||
context.request().pause();
|
||||
String repoId = npmRepositoryId;
|
||||
AuthorizationTokenScope tokenScope = scope.get();
|
||||
|
||||
Optional<PackageIdentity> packumentTarget = nativePackumentRequestTarget(context.request().method(),
|
||||
npmRequest.rest());
|
||||
if (packumentTarget.isPresent()) {
|
||||
PackageIdentity identity = packumentTarget.get();
|
||||
boolean fullMetadata = !acceptsCorgi(context.request().getHeader("Accept"));
|
||||
vertx.<ObjectNode>executeBlocking(promise -> promise.complete(externalConnectionImporter.mergedPackument(
|
||||
tokenScope.region(), npmRequest.domain(), tokenScope.owner(), npmRequest.repository(), repoId,
|
||||
identity.namespace(), identity.packageName(), fullMetadata).orElse(null)), false).onComplete(
|
||||
mergeResult -> {
|
||||
if (mergeResult.succeeded() && mergeResult.result() != null) {
|
||||
context.request().resume();
|
||||
respondWithMergedPackument(context, mergeResult.result());
|
||||
return;
|
||||
}
|
||||
proceedToProxy(context, npmRequest, repoId, tokenScope);
|
||||
});
|
||||
return;
|
||||
}
|
||||
proceedToProxy(context, npmRequest, repoId, tokenScope);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code packumentTarget}'s own fallback, and the only path for every request that isn't a
|
||||
* bare packument GET to begin with: proxies straight to Verdaccio, importing a missing
|
||||
* tarball from this repository's own npm external connection first (see {@link
|
||||
* #tryImportMissingTarball}) when the requested download is one.
|
||||
*/
|
||||
private void proceedToProxy(RoutingContext context, NpmRequest npmRequest, String repoId,
|
||||
AuthorizationTokenScope tokenScope) {
|
||||
Optional<TarballDownloadRequest> tarballTarget = nativeTarballDownloadTarget(context.request().method(),
|
||||
npmRequest.rest());
|
||||
Optional<PackageIdentity> unpublishTarget = nativeUnpublishTarget(context.request().method(),
|
||||
npmRequest.rest());
|
||||
vertx.<String>executeBlocking(promise -> {
|
||||
tarballTarget.ifPresent(target -> blockIfArchived(tokenScope, npmRequest, repoId, target));
|
||||
tarballTarget.ifPresent(target -> {
|
||||
tryImportMissingTarball(tokenScope, npmRequest, repoId, target);
|
||||
blockIfArchived(tokenScope, npmRequest, repoId, target);
|
||||
});
|
||||
promise.complete(ensureBackendReady(repoId, npmRequest));
|
||||
}).onComplete(result -> {
|
||||
if (result.failed()) {
|
||||
@@ -173,6 +210,94 @@ public class CodeArtifactNpmDataPlane {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves {@code merged} directly as this request's own response: the content {@link
|
||||
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} computed is never written to
|
||||
* Verdaccio (it only promises versions whose real tarball has not been fetched yet, which
|
||||
* Verdaccio's own publish protocol has no way to record without that tarball's real bytes in
|
||||
* the same call), so it has to be answered from here rather than by proxying to the sidecar
|
||||
* the way every other request already is.
|
||||
*/
|
||||
private void respondWithMergedPackument(RoutingContext context, ObjectNode merged) {
|
||||
if (context.response().ended() || context.response().closed()) {
|
||||
return;
|
||||
}
|
||||
byte[] body;
|
||||
try {
|
||||
body = mapper.writeValueAsBytes(merged);
|
||||
} catch (Exception e) {
|
||||
context.response().setStatusCode(500).end();
|
||||
return;
|
||||
}
|
||||
context.response().putHeader("Content-Type", "application/json").setStatusCode(200).end(Buffer.buffer(body));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code target}'s own filename is checked against the {@code <bareName>-<version>.tgz} shape
|
||||
* {@link CodeArtifactNpmExternalConnectionImporter#mergedPackument} always synthesizes for a
|
||||
* version it has not yet fetched the real asset for: unlike {@link #blockIfArchived}'s own
|
||||
* {@link VerdaccioSidecarClient#versionForTarballFilename}, which resolves a filename against
|
||||
* whatever Verdaccio's own packument already has (and must never assume this shape for a real
|
||||
* client's own arbitrarily-named publish), there is nothing stored locally to resolve against
|
||||
* yet on a genuine miss, so the version has to be read back out of the one filename shape this
|
||||
* importer itself ever hands out. A filename that doesn't fit (a real local publish's own,
|
||||
* differently-named tarball that happens to 404 for an unrelated reason) is left alone: {@link
|
||||
* VerdaccioSidecarClient#packageVersionExists} already found nothing to import, and {@link
|
||||
* #proxy} below still answers with whatever Verdaccio itself says.
|
||||
*/
|
||||
private void tryImportMissingTarball(AuthorizationTokenScope tokenScope, NpmRequest npmRequest, String repoId,
|
||||
TarballDownloadRequest target) {
|
||||
String bareName = target.identity().packageName();
|
||||
String filename = target.filename();
|
||||
String prefix = bareName + "-";
|
||||
String suffix = ".tgz";
|
||||
if (!filename.startsWith(prefix) || !filename.endsWith(suffix)
|
||||
|| filename.length() <= prefix.length() + suffix.length()) {
|
||||
return;
|
||||
}
|
||||
String version = filename.substring(prefix.length(), filename.length() - suffix.length());
|
||||
if (verdaccioClient.packageVersionExists(repoId, npmRequest.domain(), npmRequest.repository(),
|
||||
target.identity().namespace(), bareName, version)) {
|
||||
return;
|
||||
}
|
||||
externalConnectionImporter.tryImportAsset(tokenScope.region(), npmRequest.domain(), tokenScope.owner(),
|
||||
npmRequest.repository(), repoId, target.identity().namespace(), bareName, version, filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* A real npm packument read, bare ({@code GET /<name>}) only: unlike {@link #isPublish}'s own
|
||||
* one-segment PUT shape, this excludes the registry's reserved {@code -}-prefixed meta routes
|
||||
* ({@code /-/all}, {@code /-/package/...}), which npm package names can never collide with
|
||||
* (the registry reserves that prefix outright). The documented single-version read ({@code
|
||||
* GET /<name>/<version>}) is deliberately not matched here: real {@code npm install}, even
|
||||
* for one pinned version, never sends it (confirmed against {@code pacote}'s own source,
|
||||
* {@code RegistryFetcher#packumentUrl}, always the bare package path), so nothing exercises it
|
||||
* on this emulator's own critical path either.
|
||||
*/
|
||||
private static Optional<PackageIdentity> nativePackumentRequestTarget(HttpMethod method, String rest) {
|
||||
if (method != HttpMethod.GET || rest.length() <= 1 || rest.startsWith("/-") || rest.indexOf('/', 1) >= 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(packageIdentityFromPath(rest));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code accept} is {@code pacote}'s own corgi-preferring value ({@code
|
||||
* application/vnd.npm.install-v1+json}, confirmed against its own source as what a real
|
||||
* {@code npm install} sends) rather than a plain {@code application/json} ({@code npm view
|
||||
* <pkg> <field>}-style commands, confirmed the same way): decides whether {@link
|
||||
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} fetches the real registry's
|
||||
* cheaper abbreviated form or its full one (found by Greptile's review: the abbreviated form
|
||||
* never carries a package's {@code readme}, so always using it regardless of what was asked
|
||||
* silently dropped that field even for a request that explicitly wanted it). {@code null} (no
|
||||
* header at all) is treated as wanting the full form, confirmed live against the real
|
||||
* registry: with no {@code Accept} header at all (what a bare {@code curl} sends), it answers
|
||||
* with the full document, corgi being a deliberately-requested trim, never the default.
|
||||
*/
|
||||
private static boolean acceptsCorgi(String accept) {
|
||||
return accept != null && accept.contains("vnd.npm.install-v1+json");
|
||||
}
|
||||
|
||||
/**
|
||||
* A real {@code npm publish} is a {@code PUT} to the bare package path (no further path
|
||||
* segments): {@code /<name>} unscoped, or {@code /@scope%2Fname} scoped, still one segment
|
||||
|
||||
+395
@@ -0,0 +1,395 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.codeartifact.model.ExternalConnection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Retains npm packages and package versions from the real public registry a repository's {@code
|
||||
* public:npmjs} external connection names, the way real CodeArtifact does when an {@code npm}
|
||||
* client requests a package that is not present locally yet. Confirmed against the User Guide's
|
||||
* own "Connect a CodeArtifact repository to a public repository" and "Requesting packages from
|
||||
* external connections" sections, not inferred:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>One public connection, one asset per version.</b> AWS names {@code public:npmjs} as
|
||||
* npm's only public connection, and states npm packages "only have one asset per package
|
||||
* version", the same as NuGet: the real tarball itself is the only thing {@link
|
||||
* #tryImportAsset} ever imports.</li>
|
||||
* <li><b>No deterministic single-version request.</b> Unlike Maven's GAV layout and NuGet's
|
||||
* {@code {id}/{version}/{filename}} content route, npm's own real protocol has no request
|
||||
* shape naming one version: {@code npm install <pkg>@<version>} always fetches the bare
|
||||
* package's full packument first and only picks the version out of its own {@code versions}
|
||||
* map afterward (confirmed against {@code pacote}'s own source). {@link #mergedPackument} is
|
||||
* this format's counterpart to {@code CodeArtifactMavenExternalConnectionImporter}'s own {@code
|
||||
* maven-metadata.xml} merge: without it, a plain {@code npm install} could never even learn
|
||||
* that an unretained version exists, let alone request its real asset.</li>
|
||||
* <li><b>Checking asset origins.</b> A package version's retention origin, once confirmed,
|
||||
* never changes (see {@link CodeArtifactService#claimRetainedVersionOrigin}'s own javadoc); an
|
||||
* import attempt under a different connection than what is already claimed for that exact
|
||||
* version is refused outright, and the claim stays reserved for as long as any concurrent
|
||||
* attempt under the original connection is still in flight.</li>
|
||||
* <li><b>Coordinated with this emulator's own deletion and disposal.</b> The real write, via
|
||||
* {@link CodeArtifactService#retainAssetUnderVersionFence}, happens inside the exact same lock
|
||||
* {@code DeletePackageVersions}/{@code DeletePackage}/{@code DeleteRepository}/{@code
|
||||
* DisposePackageVersions} already hold for their entire duration, so the two can never
|
||||
* interleave.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactNpmExternalConnectionImporter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactNpmExternalConnectionImporter.class);
|
||||
|
||||
/**
|
||||
* Package-level fields the real registry's full packument carries that {@code npm view
|
||||
* <pkg> <field>}-style commands read directly off the package, not off any one version
|
||||
* (found by Greptile's review: {@code readme} specifically, confirmed live to never appear
|
||||
* anywhere on the abbreviated form, or on any version's own entry even in the full form).
|
||||
* Never includes {@code versions}/{@code dist-tags}/{@code name}/{@code _id}: those are
|
||||
* merged by their own dedicated logic right below this list's own use, not by this
|
||||
* blanket copy.
|
||||
*/
|
||||
private static final List<String> PACKAGE_LEVEL_DESCRIPTIVE_FIELDS = List.of("description", "readme",
|
||||
"readmeFilename", "homepage", "license", "keywords", "author", "repository", "bugs", "maintainers");
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final VerdaccioSidecarClient verdaccio;
|
||||
private final NpmExternalConnectionClient externalConnectionClient;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactNpmExternalConnectionImporter(CodeArtifactService service, VerdaccioSidecarClient verdaccio,
|
||||
NpmExternalConnectionClient externalConnectionClient, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.verdaccio = verdaccio;
|
||||
this.externalConnectionClient = externalConnectionClient;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves {@code namespace}/{@code packageName}'s own packument through {@code repository}'s
|
||||
* npm external connection, merging in whichever versions and dist-tags the real public
|
||||
* registry names that are not already known locally. Returns {@code Optional#empty()} when
|
||||
* there is no connection, retention is blocked, the real registry doesn't have this package at
|
||||
* all, or the merge adds nothing beyond what is already known locally: a caller that gets
|
||||
* {@code empty()} back should fall through to its own existing behavior exactly as if this
|
||||
* method had never been called, since that already correctly serves (or 404s) whatever is
|
||||
* known locally.
|
||||
*
|
||||
* <p>Every newly-merged version's {@code dist.tarball} is rewritten to this repository's own
|
||||
* tarball URL, under the exact {@code <bareName>-<version>.tgz} shape {@link #tryImportAsset}
|
||||
* itself expects back: the real asset is never fetched here, only promised, the same way
|
||||
* {@code CodeArtifactMavenExternalConnectionImporter}'s own {@code maven-metadata.xml} merge
|
||||
* only ever advertises release versions without fetching every jar up front. {@code
|
||||
* dist.shasum}/{@code dist.integrity} are kept exactly as the real registry declared them,
|
||||
* not recomputed here (there is no real content yet to hash): a client that later downloads
|
||||
* this version verifies its bytes against these same values, and once {@link
|
||||
* #tryImportAsset} actually fetches and stores the real tarball, the stored content is
|
||||
* byte-for-byte the real registry's own, so the hashes it independently computes from that
|
||||
* content agree with what was already promised here.
|
||||
*
|
||||
* <p>A dist-tag from the real registry is only ever written when it names a version this
|
||||
* merge actually knows about, and only replaces whatever the sidecar already has locally for
|
||||
* that same tag when the version that local tag currently names was itself only ever retained
|
||||
* through an external connection, never a tag a genuine local publish set: Verdaccio's own
|
||||
* first-ever publish to a package always points {@code dist-tags.latest} at that one version
|
||||
* (confirmed live; nothing in the retention write below can suppress it), so without this
|
||||
* check, retaining an old pinned version would leave {@code latest} stuck on it forever even
|
||||
* once a newer version exists on the real registry (found by Greptile's review). Mirrors
|
||||
* {@code CodeArtifactService#listPackageVersions}'s own identical check on {@code
|
||||
* preferredDisplayVersion} for exactly the same reason, on the AWS-facing side of this same
|
||||
* bug.
|
||||
*
|
||||
* <p>{@code fullMetadata} is the caller's own read of whether the real npm client actually
|
||||
* asked for the full document (an {@code Accept} with no {@code vnd.npm.install-v1+json},
|
||||
* the shape {@code npm view <pkg> readme}-style commands use) rather than the abbreviated
|
||||
* form {@code npm install} itself sends: only then is the real registry's full packument
|
||||
* fetched, and only then are its package-level, descriptive fields ({@code readme} among
|
||||
* them, found by Greptile's review: the abbreviated form never carries it at all) copied in,
|
||||
* never overriding a field already set locally. Honoring the caller's own request shape here,
|
||||
* rather than always fetching the (cheaper) abbreviated form regardless of what was asked,
|
||||
* keeps {@code npm install}'s own hot path exactly as cheap as before.
|
||||
*/
|
||||
public Optional<ObjectNode> mergedPackument(String region, String domain, String owner, String repository,
|
||||
String repoId, String namespace, String packageName, boolean fullMetadata) {
|
||||
String externalConnectionName = npmExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<NpmExternalConnectionClient.FetchedAsset> fetched;
|
||||
try {
|
||||
fetched = fullMetadata
|
||||
? externalConnectionClient.fetchFullPackument(externalConnectionName, namespace, packageName)
|
||||
: externalConnectionClient.fetchPackument(externalConnectionName, namespace, packageName);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not fetch {0}/{1}''s packument from {2} while resolving its versions through an "
|
||||
+ "external connection; leaving it unresolved.", namespace, packageName, externalConnectionName);
|
||||
return Optional.empty();
|
||||
}
|
||||
if (fetched.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JsonNode external;
|
||||
try {
|
||||
external = mapper.readTree(fetched.get().content());
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not parse {0}/{1}''s packument fetched from {2}; leaving it unresolved.", namespace,
|
||||
packageName, externalConnectionName);
|
||||
return Optional.empty();
|
||||
}
|
||||
// Re-checked here, right after the slow external fetch above and before this method ever
|
||||
// touches the sidecar, not just once at this method's own start (found by Greptile's
|
||||
// review): a DeleteRepository can finish its own cleanup while that fetch was still in
|
||||
// flight, and calling ensureReady below against an id that cleanup already released would
|
||||
// start a fresh container under a repository that no longer exists, one nothing can ever
|
||||
// release again. Narrows the window back down to an ordinary, already-accepted
|
||||
// check-then-act gap (the same one every other sidecar call here already has) rather than
|
||||
// one stretched out by a real network round trip; closing it completely needs the sidecar
|
||||
// itself to track in-flight use the way PypiserverSidecarManager's own container pool
|
||||
// does, tracked separately as a follow-up since Verdaccio's manager does not.
|
||||
try {
|
||||
service.describeRepository(region, domain, owner, repository);
|
||||
} catch (AwsException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// Two different base URLs, deliberately: containerBaseUrl is the sidecar's own reachable
|
||||
// address, needed to actually read its stored packument, while publicBaseUrl (already
|
||||
// ending in "/", see publicUrl's own javadoc) is what a real client reaches this
|
||||
// repository's tarball route through and so the only one safe to embed in dist.tarball
|
||||
// below; a client sent containerBaseUrl instead could never actually reach it.
|
||||
String publicBaseUrl = verdaccio.publicUrl(domain, repository);
|
||||
String containerBaseUrl = verdaccio.ensureReady(repoId, publicBaseUrl);
|
||||
JsonNode local = verdaccio.fetchPackageDocument(containerBaseUrl, namespace, packageName).orElse(null);
|
||||
ObjectNode merged = local != null ? ((ObjectNode) local).deepCopy() : mapper.createObjectNode();
|
||||
String npmName = namespace == null ? packageName : "@" + namespace + "/" + packageName;
|
||||
merged.put("name", npmName);
|
||||
if (!merged.has("_id")) {
|
||||
merged.put("_id", npmName);
|
||||
}
|
||||
boolean addedAnything = false;
|
||||
if (fullMetadata) {
|
||||
for (String field : PACKAGE_LEVEL_DESCRIPTIVE_FIELDS) {
|
||||
if (!merged.has(field) && external.has(field)) {
|
||||
merged.set(field, external.get(field));
|
||||
addedAnything = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Defaulted after the real external description had its own chance above: an empty
|
||||
// string here is a last resort, never preferred over the real registry's own value.
|
||||
if (!merged.has("description")) {
|
||||
merged.put("description", "");
|
||||
}
|
||||
ObjectNode versions = merged.has("versions") && merged.get("versions").isObject()
|
||||
? (ObjectNode) merged.get("versions") : merged.putObject("versions");
|
||||
ObjectNode distTags = merged.has("dist-tags") && merged.get("dist-tags").isObject()
|
||||
? (ObjectNode) merged.get("dist-tags") : merged.putObject("dist-tags");
|
||||
|
||||
for (Map.Entry<String, JsonNode> entry : external.path("versions").properties()) {
|
||||
String version = entry.getKey();
|
||||
if (versions.has(version)) {
|
||||
continue;
|
||||
}
|
||||
// Raised by Greptile's review: DisposePackageVersions deletes a version's real
|
||||
// Verdaccio content outright (see VerdaccioSidecarClient#deletePackageVersionAsset),
|
||||
// so versions.has(version) alone cannot tell a genuinely new external version apart
|
||||
// from one this repository already disposed of; the real registry's own listing has
|
||||
// no idea either happened. Without this, a disposed version could be merged straight
|
||||
// back in (and even land on dist-tags.latest below), only to have its own tarball
|
||||
// download correctly, but confusingly, refused later by retentionWriteStillAllowed's
|
||||
// own status check. Archived is excluded the same way: an archived version is still
|
||||
// genuinely present locally, which versions.has already caught, so this only ever
|
||||
// actually filters a disposed one in practice.
|
||||
try {
|
||||
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "npm",
|
||||
namespace, packageName, version, repoId);
|
||||
} catch (AwsException e) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode versionDoc = ((ObjectNode) entry.getValue()).deepCopy();
|
||||
versionDoc.put("name", npmName);
|
||||
versionDoc.put("version", version);
|
||||
ObjectNode dist = versionDoc.has("dist") && versionDoc.get("dist").isObject()
|
||||
? (ObjectNode) versionDoc.get("dist") : versionDoc.putObject("dist");
|
||||
dist.put("tarball", publicBaseUrl + packagePath(namespace, packageName) + "/-/"
|
||||
+ tarballFilename(packageName, version));
|
||||
versions.set(version, versionDoc);
|
||||
addedAnything = true;
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> tag : external.path("dist-tags").properties()) {
|
||||
String tagVersion = tag.getValue().asText(null);
|
||||
if (tagVersion == null || !versions.has(tagVersion)) {
|
||||
continue;
|
||||
}
|
||||
String currentLocalVersion = distTags.path(tag.getKey()).asText(null);
|
||||
boolean currentlyUnset = currentLocalVersion == null;
|
||||
boolean currentlyPointsAtARetainedVersion = currentLocalVersion != null
|
||||
&& service.retainedVersionOriginConnection(region, domain, owner, repository, "npm", namespace,
|
||||
packageName, currentLocalVersion).isPresent();
|
||||
if (currentlyUnset || currentlyPointsAtARetainedVersion) {
|
||||
distTags.set(tag.getKey(), tag.getValue());
|
||||
addedAnything = true;
|
||||
}
|
||||
}
|
||||
return addedAnything ? Optional.of(merged) : Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to retain {@code namespace}/{@code packageName}/{@code version}'s one real asset
|
||||
* into {@code repoId} from {@code repository}'s own npm external connection. Returns {@code
|
||||
* true} only when the asset is genuinely present under this connection's claim by the time
|
||||
* this returns, whether because this attempt imported it or a concurrent one already had: a
|
||||
* caller that gets {@code false} back should fall through to its own existing not-found
|
||||
* response exactly as if this method had never been called.
|
||||
*/
|
||||
public boolean tryImportAsset(String region, String domain, String owner, String repository, String repoId,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
String externalConnectionName = npmExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "npm", namespace, packageName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
|
||||
"npm", namespace, packageName);
|
||||
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
|
||||
"npm", namespace, packageName, version);
|
||||
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
|
||||
domain, owner, repository, "npm", namespace, packageName, version, externalConnectionName,
|
||||
packageFenceSnapshot);
|
||||
if (!claim.claimed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean imported = false;
|
||||
try {
|
||||
if (verdaccio.packageVersionExists(repoId, domain, repository, namespace, packageName, version)) {
|
||||
imported = service.retainedVersionOriginConnection(region, domain, owner, repository, "npm",
|
||||
namespace, packageName, version).filter(externalConnectionName::equals).isPresent();
|
||||
return imported;
|
||||
}
|
||||
Optional<NpmExternalConnectionClient.FetchedAsset> fetched;
|
||||
try {
|
||||
fetched = externalConnectionClient.fetchTarball(externalConnectionName, namespace, packageName,
|
||||
version);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not fetch {0} {1} {2} from {3} while retaining an npm package through an "
|
||||
+ "external connection.", namespace, packageName, version, externalConnectionName);
|
||||
return false;
|
||||
}
|
||||
if (fetched.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
byte[] content = fetched.get().content();
|
||||
// Fetched again here, full rather than abbreviated, rather than reusing whatever
|
||||
// mergedPackument already saw: that call is per-request and never keeps anything
|
||||
// around between one request and the next, and this is the one real network call
|
||||
// this whole import attempt pays for retrieving a version's dependencies/engines/
|
||||
// scripts and the package's own readme (see ExternalPackumentDetails' own javadoc),
|
||||
// paid at most once per version ever actually retained.
|
||||
ExternalPackumentDetails details = fetchExternalPackumentDetails(externalConnectionName, namespace,
|
||||
packageName, version);
|
||||
if (details.versionDoc() == null) {
|
||||
// Raised by hectorvent's review: storing now with no full-form document would
|
||||
// retain this version with the minimal one storeRetainedVersionAsset falls back
|
||||
// to (no dependencies/engines/scripts), and permanently so, since the merge above
|
||||
// skips any version once versions.has(version) is true. Returning false instead
|
||||
// abandons this attempt without writing anything, so a later download retries the
|
||||
// full fetch rather than settling for a degraded document forever.
|
||||
LOG.warnv("Not retaining {0}/{1}@{2} from {3} without its full-form version "
|
||||
+ "document; a later download will retry.", namespace, packageName, version,
|
||||
externalConnectionName);
|
||||
return false;
|
||||
}
|
||||
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
|
||||
domain, owner, repository, "npm", namespace, packageName, version, versionFenceSnapshot,
|
||||
packageFenceSnapshot, claim.episodeId(), repoId, assetName, content,
|
||||
() -> verdaccio.storeRetainedVersionAsset(repoId, domain, repository, namespace, packageName,
|
||||
version, assetName, content, details.versionDoc()));
|
||||
imported = result.fenceMatched() && result.wroteNewContent();
|
||||
if (imported) {
|
||||
// Raised by Greptile's review: without this, GetPackageVersionReadme 404s on an
|
||||
// otherwise fully retained version, since npm (unlike nuget's BaGetter) answers
|
||||
// that call from a capture taken at write time, never live from the sidecar; see
|
||||
// CodeArtifactService#recordPublishedPackageVersionReadme's own javadoc for why
|
||||
// versionFenceSnapshot, taken before this same write, is what it checks against.
|
||||
service.recordPublishedPackageVersionReadme(region, domain, owner, repository, "npm", namespace,
|
||||
packageName, version, details.readme(), versionFenceSnapshot);
|
||||
}
|
||||
return imported;
|
||||
} finally {
|
||||
if (imported) {
|
||||
service.ensureRetainedPackageOriginDefault(region, domain, owner, repository, "npm", namespace,
|
||||
packageName, packageFenceSnapshot);
|
||||
}
|
||||
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "npm", namespace,
|
||||
packageName, version, claim.episodeId(), imported);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code versionDoc} is the real registry's own full-form entry for exactly this version
|
||||
* (never missing/null, the shape {@link VerdaccioSidecarClient#storeRetainedVersionAsset}
|
||||
* itself already falls back safely without), or {@code null} when the full packument fetch
|
||||
* itself failed or no longer names this version; {@code readme} is the package-level readme
|
||||
* the full form carries (confirmed live: never present on any one version, only once at the
|
||||
* top of the whole document), or {@code ""} in either of those same failure cases, the same
|
||||
* empty-string convention pypi's own upload path already uses for a package with no readme at
|
||||
* all.
|
||||
*/
|
||||
private record ExternalPackumentDetails(JsonNode versionDoc, String readme) {}
|
||||
|
||||
private ExternalPackumentDetails fetchExternalPackumentDetails(String externalConnectionName, String namespace,
|
||||
String packageName, String version) {
|
||||
JsonNode full;
|
||||
try {
|
||||
Optional<NpmExternalConnectionClient.FetchedAsset> fetched = externalConnectionClient.fetchFullPackument(
|
||||
externalConnectionName, namespace, packageName);
|
||||
if (fetched.isEmpty()) {
|
||||
return new ExternalPackumentDetails(null, "");
|
||||
}
|
||||
full = mapper.readTree(fetched.get().content());
|
||||
} catch (RuntimeException | IOException e) {
|
||||
LOG.warnv(e, "Could not fetch {0}/{1}''s full packument from {2} while retaining {3}; its dependencies "
|
||||
+ "and readme will be unavailable.", namespace, packageName, externalConnectionName, version);
|
||||
return new ExternalPackumentDetails(null, "");
|
||||
}
|
||||
JsonNode versionDoc = full.path("versions").path(version);
|
||||
return new ExternalPackumentDetails(versionDoc.isMissingNode() || versionDoc.isNull() ? null : versionDoc,
|
||||
full.path("readme").asText(""));
|
||||
}
|
||||
|
||||
private static String packagePath(String namespace, String packageName) {
|
||||
return namespace == null
|
||||
? SidecarUriUtils.encodeSegment(packageName)
|
||||
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName);
|
||||
}
|
||||
|
||||
private static String tarballFilename(String packageName, String version) {
|
||||
return packageName + "-" + version + ".tgz";
|
||||
}
|
||||
|
||||
private String npmExternalConnectionName(String region, String domain, String owner, String repository) {
|
||||
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
|
||||
.filter(ec -> "npm".equals(ec.getPackageFormat()))
|
||||
.map(ExternalConnection::getExternalConnectionName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -139,7 +139,9 @@ public class CodeArtifactNuGetExternalConnectionImporter {
|
||||
// methods already hold.
|
||||
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(region,
|
||||
domain, owner, repository, "nuget", null, packageId, version, versionFenceSnapshot,
|
||||
packageFenceSnapshot, claim.episodeId(), bagetter, repoId, assetName, content);
|
||||
packageFenceSnapshot, claim.episodeId(), repoId, assetName, content,
|
||||
() -> bagetter.storePackageVersionAsset(repoId, domain, repository, null, packageId, version,
|
||||
assetName, content));
|
||||
imported = result.fenceMatched() && result.wroteNewContent();
|
||||
return imported;
|
||||
} finally {
|
||||
|
||||
+28
-13
@@ -1257,7 +1257,18 @@ public class CodeArtifactService implements Resettable {
|
||||
}
|
||||
|
||||
String preferredVersion = preferredDisplayVersion;
|
||||
String defaultDisplayVersion = preferredVersion != null
|
||||
// Raised by Greptile's review: npm's own Verdaccio sidecar always points its own
|
||||
// dist-tags.latest at whichever version a package's very first-ever stored version
|
||||
// happens to be, confirmed live, with no way for a caller's write to suppress that
|
||||
// default. A version retained through an external connection (never a deliberate local
|
||||
// publish) is excluded from being read as this preference for exactly that reason:
|
||||
// downloading an old, specifically-pinned version must never change what an unpinned
|
||||
// npm install resolves to, the same most-recently-published fallback this already uses
|
||||
// when preferredDisplayVersion itself is unset.
|
||||
boolean preferredVersionIsExternallyRetained = preferredVersion != null
|
||||
&& entries.stream().anyMatch(e -> e.version().equals(preferredVersion)
|
||||
&& "EXTERNAL".equals(e.originType()));
|
||||
String defaultDisplayVersion = preferredVersion != null && !preferredVersionIsExternallyRetained
|
||||
&& entries.stream().anyMatch(e -> e.version().equals(preferredVersion)
|
||||
&& "Published".equals(e.status()))
|
||||
? preferredVersion
|
||||
@@ -3236,16 +3247,21 @@ public class CodeArtifactService implements Resettable {
|
||||
|
||||
/**
|
||||
* Generic sibling of {@link #deployMavenAssetUnderVersionFence}, for npm/pypi/nuget's own
|
||||
* external-connection importers to write a retained asset into their own sidecar
|
||||
* ({@code sidecar.storePackageVersionAsset}) under the same fence/status/claim-episode
|
||||
* protection Maven's own method already provides, inside the exact same lock {@code
|
||||
* deletePackageVersions}/{@code deletePackage}/{@code deleteRepository}/{@code
|
||||
* disposePackageVersions} hold for their own entire operation.
|
||||
* external-connection importers to write a retained asset into their own sidecar under the
|
||||
* same fence/status/claim-episode protection Maven's own method already provides, inside the
|
||||
* exact same lock {@code deletePackageVersions}/{@code deletePackage}/{@code
|
||||
* deleteRepository}/{@code disposePackageVersions} hold for their own entire operation.
|
||||
*
|
||||
* <p>Unlike {@link ReposiliteSidecarClient#deployArtifact}, {@link
|
||||
* RepositorySidecarManager#storePackageVersionAsset} reports no status code or idempotent-match
|
||||
* distinction of its own: it either succeeds (void) or throws. A caller that wants to avoid
|
||||
* double-counting bytes on a retry should check {@link
|
||||
* <p>{@code write} is the caller's own sidecar call, run only once the fence actually still
|
||||
* allows it, inside this same {@code synchronized} method: a plain {@link Runnable} rather
|
||||
* than a fixed {@code RepositorySidecarManager}/{@code storePackageVersionAsset} shape (found
|
||||
* by Greptile's review of npm's own external-connection work) since npm's own write needs to
|
||||
* reuse the real registry's own version document to avoid dropping {@code dependencies}/
|
||||
* {@code engines}/{@code scripts}, something {@link RepositorySidecarManager#storePackageVersionAsset}'s
|
||||
* fixed signature has no way to carry through; nuget's own call wraps the exact same plain
|
||||
* {@code storePackageVersionAsset} call this method used to make itself. Reports no status
|
||||
* code or idempotent-match distinction of its own: it either succeeds or throws. A caller
|
||||
* that wants to avoid double-counting bytes on a retry should check {@link
|
||||
* RepositorySidecarManager#fetchPackageVersionAsset} first and skip this call entirely when
|
||||
* the asset is already there with matching content, the same way a direct upload's own
|
||||
* idempotency check already does for this format's controller.
|
||||
@@ -3253,14 +3269,13 @@ public class CodeArtifactService implements Resettable {
|
||||
public synchronized AssetRetentionAttemptResult retainAssetUnderVersionFence(String region, String domain,
|
||||
String domainOwner, String repository, String format, String namespace, String packageName,
|
||||
String version, long versionFenceSnapshot, long packageFenceSnapshot, long episodeId,
|
||||
RepositorySidecarManager sidecar, String repositoryContainerId, String assetName, byte[] content) {
|
||||
String repositoryContainerId, String assetName, byte[] content, Runnable write) {
|
||||
if (!retentionWriteStillAllowed(region, domain, domainOwner, repository, format, namespace, packageName,
|
||||
version, repositoryContainerId, versionFenceSnapshot, episodeId)) {
|
||||
return new AssetRetentionAttemptResult(false, false);
|
||||
}
|
||||
try {
|
||||
sidecar.storePackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName,
|
||||
version, assetName, content);
|
||||
write.run();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not write {0} {1} {2}''s asset {3} while retaining it through an external "
|
||||
+ "connection.", format, packageName, version, assetName);
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
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.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A real outbound client for the one public npm repository CodeArtifact's {@code public:npmjs}
|
||||
* external connection names: {@code https://registry.npmjs.org}, confirmed live, not inferred.
|
||||
*
|
||||
* <p>Unlike Maven's GAV layout and NuGet's {@code {id}/{version}/{filename}} content route,
|
||||
* npm's own real wire protocol has no request shape that names a single package version: {@code
|
||||
* npm install <pkg>@<version>} always fetches the bare package's full packument first (confirmed
|
||||
* against npm's own {@code pacote} client source, {@code RegistryFetcher#packumentUrl}, which is
|
||||
* always {@code <registry>/<escapedName>}, never a version-specific path) and only picks the
|
||||
* requested version out of its {@code versions} map afterward. {@link
|
||||
* CodeArtifactNpmExternalConnectionImporter#mergedPackument} is what actually needs a version's
|
||||
* metadata before any asset is ever fetched; {@link #fetchPackument} serves that, using the same
|
||||
* {@code corgi} abbreviated format {@code pacote} itself requests by default, since every field
|
||||
* this emulator's own merge needs ({@code versions[v].dist}, {@code dist-tags}) survives that
|
||||
* trimming and a full packument can run to several megabytes for a popular package.
|
||||
*
|
||||
* <p>The real tarball path ({@link #fetchTarball}) is fetched by exact coordinate, not guessed:
|
||||
* confirmed live that the real registry serves it at a deterministic {@code
|
||||
* <packagePath>/-/<bareName>-<version>.tgz}, scope included in {@code packagePath} with a literal
|
||||
* {@code /} (unlike the packument path below, which needs the scope separator percent-encoded as
|
||||
* {@code %2F} to reach the single-package resource rather than a sub-path of it, also confirmed
|
||||
* live). {@link CodeArtifactNpmExternalConnectionImporter} always synthesizes its own rewritten
|
||||
* {@code dist.tarball} using this exact {@code <bareName>-<version>.tgz} shape, so this never
|
||||
* needs to trust whatever filename the real packument itself declared.
|
||||
*
|
||||
* <p>Every failure mode (an unknown connection name, a real non-200 response, a network error)
|
||||
* resolves to {@link Optional#empty()} rather than throwing: a caller here is always deciding
|
||||
* whether to retain a package or a package version from an external source, and AWS's own
|
||||
* documented behavior for an unreachable external repository is to behave exactly as if the
|
||||
* asset were not found, with no special error surfaced to the client.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class NpmExternalConnectionClient {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(NpmExternalConnectionClient.class);
|
||||
|
||||
private static final String CORGI_ACCEPT = "application/vnd.npm.install-v1+json; q=1.0, "
|
||||
+ "application/json; q=0.8, */*";
|
||||
private static final String FULL_ACCEPT = "application/json";
|
||||
|
||||
private static final Map<String, String> BASE_URLS = Map.of(
|
||||
"public:npmjs", "https://registry.npmjs.org");
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final Map<String, String> baseUrls;
|
||||
|
||||
@Inject
|
||||
public NpmExternalConnectionClient() {
|
||||
this(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL).build(), BASE_URLS);
|
||||
}
|
||||
|
||||
/** For tests: a fake base-URL map, so the wire contract can be exercised against a local
|
||||
* {@code HttpServer} fake instead of the real public registry. */
|
||||
NpmExternalConnectionClient(HttpClient httpClient, Map<String, String> baseUrls) {
|
||||
this.httpClient = httpClient;
|
||||
this.baseUrls = baseUrls;
|
||||
}
|
||||
|
||||
/** One package's real packument, or one real tarball's bytes, fetched from the real registry. */
|
||||
public record FetchedAsset(byte[] content) {}
|
||||
|
||||
/**
|
||||
* Fetches {@code namespace}/{@code packageName}'s own real, abbreviated packument from the
|
||||
* real public registry {@code externalConnectionName} names.
|
||||
*/
|
||||
public Optional<FetchedAsset> fetchPackument(String externalConnectionName, String namespace,
|
||||
String packageName) {
|
||||
return fetchPackument(externalConnectionName, namespace, packageName, CORGI_ACCEPT);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real registry's full, uncompressed packument for {@code namespace}/{@code packageName}.
|
||||
* Confirmed live against the same package and version: the abbreviated form {@link
|
||||
* #fetchPackument} uses already carries a version's {@code dependencies}/{@code engines}, but
|
||||
* drops its {@code scripts}, and carries no {@code readme} anywhere at all (not per version,
|
||||
* and not even on the full form's own per-version entry: the real registry only ever keeps
|
||||
* one {@code readme}, at the top of the full document). Used by {@link
|
||||
* CodeArtifactNpmExternalConnectionImporter#tryImportAsset} once, per version ever actually
|
||||
* retained, not on every packument read the way {@link #fetchPackument} is: the extra cost of
|
||||
* the full form over the abbreviated one is paid at most once per version.
|
||||
*/
|
||||
public Optional<FetchedAsset> fetchFullPackument(String externalConnectionName, String namespace,
|
||||
String packageName) {
|
||||
return fetchPackument(externalConnectionName, namespace, packageName, FULL_ACCEPT);
|
||||
}
|
||||
|
||||
private Optional<FetchedAsset> fetchPackument(String externalConnectionName, String namespace,
|
||||
String packageName, String accept) {
|
||||
String baseUrl = baseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packumentPathSegment(namespace, packageName));
|
||||
return send(uri, accept, namespace, packageName);
|
||||
}
|
||||
|
||||
/** Fetches {@code namespace}/{@code packageName}/{@code version}'s one real tarball. */
|
||||
public Optional<FetchedAsset> fetchTarball(String externalConnectionName, String namespace, String packageName,
|
||||
String version) {
|
||||
String baseUrl = baseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), tarballPath(namespace, packageName, version));
|
||||
return send(uri, "*/*", namespace, packageName);
|
||||
}
|
||||
|
||||
private Optional<FetchedAsset> send(URI uri, String accept, String namespace, String packageName) {
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(uri)
|
||||
.timeout(Duration.ofSeconds(20))
|
||||
.header("Accept", accept)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<byte[]> response = httpClient.send(request, BodyHandlers.ofByteArray());
|
||||
return response.statusCode() == 200 ? Optional.of(new FetchedAsset(response.body())) : Optional.empty();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return Optional.empty();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not fetch {0} {1} from the public npm registry: {2}", namespace, packageName,
|
||||
e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The real registry's single-package resource path: a bare, percent-encoded package name, or
|
||||
* for a scoped package, {@code @<namespace>%2F<packageName>} as one opaque segment with the
|
||||
* scope separator escaped (confirmed live: an unescaped {@code /} there 404s the single-
|
||||
* package endpoint instead of reaching it).
|
||||
*/
|
||||
private static String packumentPathSegment(String namespace, String packageName) {
|
||||
String encodedName = SidecarUriUtils.encodeSegment(packageName);
|
||||
return namespace == null ? encodedName : "@" + SidecarUriUtils.encodeSegment(namespace) + "%2F" + encodedName;
|
||||
}
|
||||
|
||||
private static String tarballPath(String namespace, String packageName, String version) {
|
||||
String encodedName = SidecarUriUtils.encodeSegment(packageName);
|
||||
String packagePath = namespace == null ? encodedName
|
||||
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + encodedName;
|
||||
String tarballFilename = SidecarUriUtils.encodeSegment(packageName + "-" + version + ".tgz");
|
||||
return "/" + packagePath + "/-/" + tarballFilename;
|
||||
}
|
||||
}
|
||||
+22
@@ -451,6 +451,28 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
|
||||
sourceVersionDoc);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code CodeArtifactNpmExternalConnectionImporter}'s own destination write for a version
|
||||
* retained through a {@code public:npmjs} external connection, the same reuse-the-source-
|
||||
* document treatment {@link #copyPackageVersionAsset} already gives a version copied from
|
||||
* another repository here, just sourced from the real public registry's own fetched packument
|
||||
* instead of another Verdaccio-backed repository (found by Greptile's review of npm's own
|
||||
* external-connection work: a plain {@link #storePackageVersionAsset} call builds a minimal
|
||||
* document with no {@code dependencies}/{@code engines}/{@code scripts}, which a real {@code
|
||||
* npm install} of this exact version needs). {@code externalVersionDoc} is {@code null} when
|
||||
* the caller could not resolve the real registry's own version entry (should not normally
|
||||
* happen once {@link CodeArtifactNpmExternalConnectionImporter#mergedPackument} has already
|
||||
* merged this exact version in, but defended the same way {@link #copyPackageVersionAsset}
|
||||
* already is): falls back to the same minimal document {@link #storePackageVersionAsset}
|
||||
* would have built.
|
||||
*/
|
||||
public void storeRetainedVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content,
|
||||
JsonNode externalVersionDoc) {
|
||||
storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content,
|
||||
externalVersionDoc);
|
||||
}
|
||||
|
||||
private void storeVersion(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName, String version, String assetName, byte[] content, JsonNode sourceVersionDoc) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
|
||||
|
||||
Reference in new issue
Block a user