mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codeartifact): resolve Maven version ranges and dynamic versions through an external connection (#6961)
A bare group/artifact-level maven-metadata.xml request used to be rejected outright, so a Maven version range or a Gradle dynamic version could never resolve against a connected repository that had not already retained some other fixed version of the same package some other way. This merges the public repository's own maven-metadata.xml release-version list into the local copy instead: only release versions (never snapshots or versions this repository already knows are Archived/Disposed) are merged, a version already listed locally is never duplicated, and an already-existing local latest/release is never overridden by the external source, since there is no reliable way to compare Maven version strings for recency. The actual asset bytes for whichever version a resolver settles on are still only fetched lazily through the existing per-asset import path, unchanged. A bare metadata request always retries the merge, even once a local copy already exists, so a public release published after the first import is still discoverable later; a fixed version's own asset keeps the old miss-only gate, since it never changes once retained. The merge writes matching .sha1/.md5 checksums alongside the metadata, repairing them even on an otherwise-no-op retry, and reads any existing local copy through the confirmed-404 check rather than treating a transient read error as if no local metadata existed. The merge itself is fenced at package granularity the same way a per-version write already is, so a DeletePackage or DeleteRepository that finishes while the real, public-repository fetch is still in flight can never have its removal undone by a write that lands afterward: the package fence now also bumps on an origin-config-only delete, not just one that removed real content, and the merge separately re-checks that the repository itself still exists under the same lock, since neither case bumps any individual package's fence on its own. Also fixes a package-existence check that this surfaced: writing the merged metadata into the group/artifact directory made the sidecar's own packageExists treat a metadata-only package as already directly published, permanently blocking every later retention attempt for it since no claim could ever get recorded to prove otherwise. packageExists now requires an actual version subdirectory, not just any file, to consider the package present; a new hasAnyContentToDelete still catches the metadata-only case for DeletePackage, so a package left in that state is still cleared. Verified against the real, live public:maven-central connection with a genuine mvn dependency:resolve run against a version range, not just the mocked test suite.
This commit is contained in:
1 parent
e2d65a6378
commit
00ab75b395
10 files changed
+1068
-44
No files matched your search
+21
-4
@@ -178,8 +178,9 @@ public class CodeArtifactMavenController {
|
||||
return Response.status(Response.Status.NOT_FOUND).build();
|
||||
}
|
||||
Optional<FetchedArtifact> artifact = reposilite.fetchArtifact(scope.repoId(), gav);
|
||||
if (artifact.isEmpty() && externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(),
|
||||
repository, scope.repoId(), gav)) {
|
||||
if ((artifact.isEmpty() || isBareMavenMetadataFile(gav))
|
||||
&& externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository,
|
||||
scope.repoId(), gav)) {
|
||||
artifact = reposilite.fetchArtifact(scope.repoId(), gav);
|
||||
}
|
||||
return artifact.map(this::toResponse).orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build());
|
||||
@@ -197,13 +198,29 @@ public class CodeArtifactMavenController {
|
||||
// miss would, or a HEAD-first client would see a false "not found" before the real GET
|
||||
// ever gets the chance to retain it.
|
||||
boolean exists = reposilite.artifactExists(scope.repoId(), gav);
|
||||
if (!exists && externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository,
|
||||
scope.repoId(), gav)) {
|
||||
if ((!exists || isBareMavenMetadataFile(gav))
|
||||
&& externalConnectionImporter.tryImport(scope.region(), domain, scope.owner(), repository,
|
||||
scope.repoId(), gav)) {
|
||||
exists = reposilite.artifactExists(scope.repoId(), gav);
|
||||
}
|
||||
return exists ? Response.ok().build() : Response.status(Response.Status.NOT_FOUND).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code true} only for the exact, bare {@code maven-metadata.xml} path, never a checksum
|
||||
* sibling: unlike a fixed version's own assets, which never change once retained, a package's
|
||||
* available-version list can keep growing on the real public repository after this
|
||||
* repository's own first merge of it, so a request for this exact file always gets a fresh
|
||||
* import attempt even when a local copy already exists, not just on the first ever miss.
|
||||
* Raised by Greptile's review: without this, {@link #fetch}/{@link #head} only ever imported
|
||||
* metadata once, the first time this exact GAV was requested, and every later request for the
|
||||
* same package's version list silently kept serving that same first snapshot forever, no
|
||||
* matter how many releases the public repository published afterward.
|
||||
*/
|
||||
private static boolean isBareMavenMetadataFile(String gav) {
|
||||
return gav.endsWith("/maven-metadata.xml");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code true} unless {@code gav} names an exact version this service knows is {@code
|
||||
* Archived}: {@link #parseNamespaceAndPackageName}'s own version element is {@code null} for a
|
||||
|
||||
+86
-1
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
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;
|
||||
@@ -7,6 +8,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Retains a Maven package version from the real public repository a repository's {@code
|
||||
@@ -50,6 +52,12 @@ import java.util.Optional;
|
||||
* also checks the version's current status directly, not just its fence, so a request already
|
||||
* admitted before a disposal that finished before this attempt's own snapshot was even taken
|
||||
* can never write real bytes back for a version already marked unusable.</li>
|
||||
* <li><b>Resolving version ranges and dynamic versions.</b> A bare group/artifact-level
|
||||
* {@code maven-metadata.xml} request is resolved by merging in whichever release versions the
|
||||
* public repository's own metadata names, not by importing a single fixed version; see
|
||||
* {@link #tryImportMetadata}'s own javadoc. Without this, a Maven version range or a Gradle
|
||||
* dynamic version could never resolve against a connected repository that has not already
|
||||
* retained some other fixed version of this exact package some other way.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Deliberately not modeled here, because it cannot apply without an actual upstream
|
||||
@@ -84,16 +92,30 @@ public class CodeArtifactMavenExternalConnectionImporter {
|
||||
* try again later" applies when nothing here can help (no connection configured, the version
|
||||
* is a SNAPSHOT, retention is blocked, a mixed-origin conflict, or the real public repository
|
||||
* genuinely doesn't have it).
|
||||
*
|
||||
* <p>A bare group/artifact-level {@code maven-metadata.xml} (no version segment in {@code
|
||||
* gav}) is resolved differently: see {@link #tryImportMetadata}. This only ever merges in
|
||||
* which releases the public repository has; the real bytes of whichever version a resolver
|
||||
* settles on afterward still come through this same method's ordinary per-asset path, on
|
||||
* the request that follows, the same two-step resolution a real {@code mvn}/Gradle client
|
||||
* already does against a connected upstream.
|
||||
*/
|
||||
public boolean tryImport(String region, String domain, String owner, String repository, String repoId,
|
||||
String gav) {
|
||||
Optional<String[]> coordinate = CodeArtifactMavenController.parseNamespaceAndPackageName(gav);
|
||||
if (coordinate.isEmpty() || coordinate.get()[2] == null || coordinate.get()[2].endsWith("-SNAPSHOT")) {
|
||||
if (coordinate.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String namespace = coordinate.get()[0];
|
||||
String packageName = coordinate.get()[1];
|
||||
String version = coordinate.get()[2];
|
||||
if (version == null) {
|
||||
return gav.endsWith("/maven-metadata.xml") && tryImportMetadata(region, domain, owner, repository,
|
||||
repoId, namespace, packageName);
|
||||
}
|
||||
if (version.endsWith("-SNAPSHOT")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String externalConnectionName = mavenExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
@@ -251,6 +273,69 @@ public class CodeArtifactMavenExternalConnectionImporter {
|
||||
return externalConnectionClient.exists(externalConnectionName, pomGav);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves {@code namespace}/{@code packageName}'s own group/artifact-level {@code
|
||||
* maven-metadata.xml} through {@code repository}'s maven external connection: without this, a
|
||||
* Maven version range or a Gradle dynamic version could never resolve against a connected
|
||||
* repository that has not already retained a fixed version of this exact package some other
|
||||
* way, since nothing else here ever asks the real public repository what versions it
|
||||
* actually has. Every candidate version this repository already knows is {@code Archived}/
|
||||
* {@code Disposed} is kept out of the merge, the same existence check a per-version download
|
||||
* itself already enforces through {@link
|
||||
* CodeArtifactService#requireContainerBackedVersionDownloadable}, so a disposed version's
|
||||
* metadata entry can never come back from the public repository's own still-unaware listing.
|
||||
* Returns {@code true} only when the public repository's own metadata named at least one
|
||||
* allowed release version this repository did not already have listed; see {@link
|
||||
* ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s own javadoc for exactly
|
||||
* how a merge with any locally-published versions is handled.
|
||||
*
|
||||
* <p>Raised by Greptile's review: the real fetch from the public repository below can take
|
||||
* long enough for a concurrent {@code DeletePackage} to finish while it is still in flight.
|
||||
* Without a fence, the merge that follows would write {@code maven-metadata.xml} straight
|
||||
* back once that fetch completes, resurrecting the version list {@code DeletePackage} had
|
||||
* already told its caller was gone. {@code packageFenceSnapshot} is taken here, before that
|
||||
* fetch, for {@link CodeArtifactService#mergeMavenMetadataUnderPackageFence} to check right
|
||||
* before the write, inside the same lock {@code DeletePackage} itself holds for its own entire
|
||||
* operation; see that method's own javadoc for the full race this closes.
|
||||
*/
|
||||
private boolean tryImportMetadata(String region, String domain, String owner, String repository, String repoId,
|
||||
String namespace, String packageName) {
|
||||
String externalConnectionName = mavenExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "maven", namespace,
|
||||
packageName)) {
|
||||
return false;
|
||||
}
|
||||
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
|
||||
"maven", namespace, packageName);
|
||||
String metadataGav = namespace.replace('.', '/') + "/" + packageName + "/maven-metadata.xml";
|
||||
Optional<MavenExternalConnectionClient.FetchedAsset> fetched;
|
||||
try {
|
||||
fetched = externalConnectionClient.fetchAsset(externalConnectionName, metadataGav);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not fetch {0}/{1}''s maven-metadata.xml from {2} while resolving its versions "
|
||||
+ "through an external connection; leaving it unresolved.", namespace, packageName,
|
||||
externalConnectionName);
|
||||
return false;
|
||||
}
|
||||
if (fetched.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Predicate<String> versionAllowed = version -> {
|
||||
try {
|
||||
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "maven",
|
||||
namespace, packageName, version, repoId);
|
||||
return true;
|
||||
} catch (AwsException e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
return service.mergeMavenMetadataUnderPackageFence(region, domain, owner, repository, namespace,
|
||||
packageName, packageFenceSnapshot, reposilite, repoId, fetched.get().content(), versionAllowed);
|
||||
}
|
||||
|
||||
private String mavenExternalConnectionName(String region, String domain, String owner, String repository) {
|
||||
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
|
||||
.filter(ec -> "maven".equals(ec.getPackageFormat()))
|
||||
|
||||
+72
-8
@@ -53,6 +53,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
@@ -3126,6 +3127,54 @@ public class CodeArtifactService implements Resettable {
|
||||
return new MavenDeployAttemptResult(true, outcome);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s own counterpart to
|
||||
* {@link #deployMavenAssetUnderVersionFence}, at package granularity rather than one version's:
|
||||
* a metadata merge has no single version or claim episode of its own to check against, since
|
||||
* it only ever advertises versions, never retains real bytes for any of them. Checked and
|
||||
* acted on inside this very same {@code synchronized} call {@link #deletePackage} already
|
||||
* holds for its own entire operation (and bumps {@code containerBackedPackageDeletionFence}
|
||||
* behind), so the two can never interleave.
|
||||
*
|
||||
* <p>Raised by Greptile's review: {@code CodeArtifactMavenExternalConnectionImporter} used to
|
||||
* fetch the real public repository's metadata and write the merge straight back with no fence
|
||||
* check at all. A {@code DeletePackage} that finished while that real, slow fetch was still in
|
||||
* flight would have its removal silently undone the moment the fetch finally completed and
|
||||
* this write landed, resurrecting a {@code maven-metadata.xml} (and its checksums) for a
|
||||
* package {@code DeletePackage} had already told its caller was gone, even if the external
|
||||
* connection itself was also removed somewhere in that same gap.
|
||||
*
|
||||
* <p>{@code packageFenceSnapshot} is whatever {@link #currentContainerBackedPackageFence}
|
||||
* returned when the importer called it, right before issuing the real fetch that produced
|
||||
* {@code externalMetadataXml}; {@code reposilite}, {@code repoId}, and the rest of the merge's
|
||||
* own inputs come from the caller for the same reason {@link #deployMavenAssetUnderVersionFence}
|
||||
* takes them as parameters rather than fields: the slow part already happened before this lock
|
||||
* was ever taken.
|
||||
*
|
||||
* <p>Raised by Greptile's review: the package fence alone says nothing about {@link
|
||||
* #deleteRepository} (also {@code synchronized} on this same lock) having removed the whole
|
||||
* repository, not just this one package, while that same fetch was in flight. Without also
|
||||
* checking that here, {@link ReposiliteSidecarClient#mergeExternalConnectionReleaseVersions}'s
|
||||
* own {@code ensureRepository} call would transparently recreate the Reposilite repository
|
||||
* {@code deleteRepository} had just torn down, leaving real metadata and checksum files behind
|
||||
* with no CodeArtifact repository left through which anything could ever delete them again.
|
||||
*/
|
||||
public synchronized boolean mergeMavenMetadataUnderPackageFence(String region, String domain,
|
||||
String domainOwner, String repository, String namespace, String packageName, long packageFenceSnapshot,
|
||||
ReposiliteSidecarClient reposilite, String repoId, byte[] externalMetadataXml,
|
||||
Predicate<String> versionAllowed) {
|
||||
if (currentContainerBackedPackageFence(region, domain, domainOwner, repository, "maven", namespace,
|
||||
packageName) != packageFenceSnapshot) {
|
||||
return false;
|
||||
}
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
if (repositories.getForAccount(owner, repositoryKey(region, domain, repository)).isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return reposilite.mergeExternalConnectionReleaseVersions(repoId, namespace, packageName, externalMetadataXml,
|
||||
versionAllowed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a package has any real version behind it: a stored {@code packageVersions} record
|
||||
* for generic, or the repository's own sidecar for a container-backed format. Deliberately
|
||||
@@ -3194,11 +3243,16 @@ public class CodeArtifactService implements Resettable {
|
||||
if (CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
hadRealContent = deleteContainerBackedPackageIfPresent(region, domain, owner, repository, format,
|
||||
namespace, packageName);
|
||||
if (hadRealContent) {
|
||||
// Bumped only on an actual deletion, never a no-op (nothing there to begin with):
|
||||
// see currentContainerBackedPackageFence's own javadoc for what this protects
|
||||
// against, and why it can replace a sidecar round trip entirely rather than just
|
||||
// relocate one.
|
||||
if (hadRealContent || originConfig.isPresent()) {
|
||||
// Bumped on any deletion this call actually goes through with, not just one that
|
||||
// removed real content: see currentContainerBackedPackageFence's own javadoc for
|
||||
// what this protects against, and why it can replace a sidecar round trip entirely
|
||||
// rather than just relocate one. Raised by Greptile's review: an origin-config-only
|
||||
// package (no real content, just a stored PutPackageOriginConfiguration) used to
|
||||
// leave this fence untouched, so a Maven metadata merge already in flight for that
|
||||
// exact package, racing this exact delete, could still write maven-metadata.xml
|
||||
// back afterward with a snapshot that still matched, resurrecting a package this
|
||||
// call had already told its caller was gone.
|
||||
containerBackedPackageDeletionFence.put(ownerScopedKey(owner, accountingKey),
|
||||
containerBackedPackageDeletionCounter.incrementAndGet());
|
||||
}
|
||||
@@ -3306,13 +3360,21 @@ public class CodeArtifactService implements Resettable {
|
||||
* origin-config-only or not; that cost already existed for every real package before this
|
||||
* method's origin-config awareness, this just stops it from being skipped by accident instead
|
||||
* of by choice.
|
||||
*
|
||||
* <p>Checked through {@link RepositorySidecarManager#hasAnyContentToDelete}, not {@link
|
||||
* RepositorySidecarManager#packageExists}: a Maven package that only ever had its {@code
|
||||
* maven-metadata.xml} merged in from an external connection, with no version ever actually
|
||||
* retained, correctly answers {@code packageExists} {@code false} (see that method's own
|
||||
* javadoc), but still has that merged metadata file sitting on the sidecar for this call to
|
||||
* actually remove, rather than skipping the delete and reporting success while leaving it
|
||||
* fetchable.
|
||||
*/
|
||||
private boolean deleteContainerBackedPackageIfPresent(String region, String domain, String owner,
|
||||
String repository, String format, String namespace, String packageName) {
|
||||
String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
|
||||
RepositorySidecarManager manager = sidecarRegistry.forFormat(format)
|
||||
.orElseThrow(() -> notFound("Package '" + packageName + "' was not found.", packageName, "package"));
|
||||
if (!manager.packageExists(repoId, domain, repository, namespace, packageName)) {
|
||||
if (!manager.hasAnyContentToDelete(repoId, domain, repository, namespace, packageName)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
@@ -4530,8 +4592,10 @@ public class CodeArtifactService implements Resettable {
|
||||
* delayed callback (its own Vert.x response arriving well after this snapshot was taken, long
|
||||
* after Maven's or pypi's near-immediate inline accounting would have run) must not have the
|
||||
* first publish's bytes misattributed to the second. {@code deletePackage}'s container-backed
|
||||
* branch bumps the counter behind this snapshot on an actual deletion; so does
|
||||
* {@link #forgetContainerBackedPackage}, for the one other way a container-backed package's
|
||||
* branch bumps the counter behind this snapshot on any deletion it actually goes through with,
|
||||
* real content or an origin-config-only package alike, never a no-op where neither existed to
|
||||
* begin with (that case 404s outright instead); so does {@link #forgetContainerBackedPackage},
|
||||
* for the one other way a container-backed package's
|
||||
* real content can disappear: a real npm client's native {@code npm unpublish}, which the
|
||||
* pinned Verdaccio image (configured with {@code unpublish: $all}) honors on its own wire
|
||||
* protocol without ever calling {@code deletePackage} (confirmed: {@code
|
||||
|
||||
+177
-4
@@ -29,6 +29,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* HTTP client for the shared Reposilite sidecar. A CodeArtifact repository maps to a named
|
||||
@@ -149,15 +150,55 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a confirmed 404 means absent; confirmed live (a {@code GET} on a missing directory, or a
|
||||
* never-provisioned repository, both answer a clean 404). Anything else, an auth failure or a
|
||||
* server error, throws instead of collapsing to "not found": a Reposilite outage must not read
|
||||
* as every Maven package having been deleted.
|
||||
* {@code true} only when at least one real version subdirectory sits beneath the group/
|
||||
* artifact directory, not merely whenever that directory answers at all: {@link
|
||||
* #mergeExternalConnectionReleaseVersions} writes a {@code maven-metadata.xml} straight into
|
||||
* that same directory purely to advertise resolvable versions, with no version ever actually
|
||||
* retained there, so treating that file's presence alone as "exists" would make {@code
|
||||
* CodeArtifactService#isUpstreamRetentionBlocked} see a brand-new package as already
|
||||
* directly-published and permanently refuse every later retention attempt for it, since no
|
||||
* claim could ever get recorded to prove otherwise. A confirmed 404 means absent (a missing
|
||||
* directory, or a never-provisioned repository, both answer a clean 404). Anything else, an
|
||||
* auth failure or a server error, throws instead of collapsing to "not found": a Reposilite
|
||||
* outage must not read as every Maven package having been deleted.
|
||||
*/
|
||||
@Override
|
||||
public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
String path = "/api/maven/details" + packageDirectoryPath(repositoryContainerId, namespace, packageName);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader())
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = send(request, BodyHandlers.ofString());
|
||||
if (response.statusCode() == 404) {
|
||||
return false;
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not look up " + packageName + " on the Reposilite sidecar: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
for (JsonNode entry : readTree(response.body()).path("files")) {
|
||||
if ("DIRECTORY".equals(entry.path("type").asText())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlike {@link #packageExists}, a bare GET on the group/artifact directory, with no
|
||||
* requirement that anything beneath it be a real version: a metadata-only merge (just a
|
||||
* {@code maven-metadata.xml} file, no version subdirectory) still answers {@code 200} here,
|
||||
* so {@code DeletePackage} actually removes it instead of skipping the delete and reporting
|
||||
* success while leaving it fetchable.
|
||||
*/
|
||||
@Override
|
||||
public boolean hasAnyContentToDelete(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
packageDirectoryPath(repositoryContainerId, namespace, packageName)))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
@@ -624,6 +665,138 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
deployArtifact(repositoryContainerId, gav, metadata.build().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges {@code externalMetadataXml}, a real public Maven repository's own group/artifact-
|
||||
* level {@code maven-metadata.xml} fetched through an external connection, into {@code
|
||||
* repositoryContainerId}'s own copy, so a client resolving a Maven version range or a Gradle
|
||||
* dynamic version can discover a release this repository has never actually retained a byte
|
||||
* of yet. The real asset bytes for whichever version the resolver settles on are still
|
||||
* fetched on demand the normal way, through a separate, per-version import attempt; this
|
||||
* only ever advertises versions, the same separation a real {@code maven-metadata.xml}
|
||||
* request and the version-specific GAV requests that follow it already have.
|
||||
*
|
||||
* <p>Only {@code -SNAPSHOT}-free versions this repository's own {@code versionAllowed} does
|
||||
* not reject are merged in: the snapshot restriction matches an external connection's own
|
||||
* per-asset import ("AWS CodeArtifact only supports importing Maven release versions"), and
|
||||
* {@code versionAllowed} exists so a caller can also keep out any version this repository has
|
||||
* recorded as {@code Archived}/{@code Disposed}. Without that second check, disposing this
|
||||
* package's only locally-listed version deletes its metadata file outright (see {@link
|
||||
* #recordVersionDisposed}), and the next merge would otherwise re-import that exact disposed
|
||||
* version straight back from the public repository's own still-unaware listing: a resolver
|
||||
* could then pick a version whose real bytes this repository will never serve again. A
|
||||
* version already listed locally is never added twice. Returns {@code false} without writing
|
||||
* anything when the public repository's own metadata names no allowed release version this
|
||||
* repository doesn't already have listed.
|
||||
*
|
||||
* <p>Reads the existing local copy through {@link #fetchArtifactConfirmingMissing}, not
|
||||
* {@link #fetchArtifact}: that method's {@code empty()} also means "any non-200," 500/503
|
||||
* included, which this merge must never read as "no local metadata yet," since that would let
|
||||
* a transient sidecar read failure silently replace a real, locally-published package's
|
||||
* {@code latest}/{@code release} with the external source's own guess at them.
|
||||
*
|
||||
* <p>Never lets the external source override an already-existing local {@code latest}/
|
||||
* {@code release}: this bridge has no reliable way to tell whether a locally-published
|
||||
* version a direct {@code mvn deploy} already recorded is newer or older than whatever the
|
||||
* public repository last published, since Maven version strings do not sort by any universal
|
||||
* rule this emulator could apply safely. A package with no local metadata at all has nothing
|
||||
* to protect, so its merged {@code latest}/{@code release} are taken from the external
|
||||
* source's own declared values, falling back to the last release version in document order
|
||||
* when the source's own {@code <latest>}/{@code <release>} elements are themselves missing.
|
||||
*
|
||||
* <p>Writes the matching {@code .sha1}/{@code .md5} checksum siblings alongside every write,
|
||||
* the same upkeep {@link #recordVersionDisposed} already owes this exact file: left out, a
|
||||
* Maven client that verifies checksums could never trust even the first metadata response
|
||||
* this merge ever produces. Raised by Greptile's review: the no-op return below, taken once
|
||||
* every external version is already listed locally, repairs those same two checksums against
|
||||
* the existing metadata first, the same way {@link #recordVersionDisposed}'s own early
|
||||
* returns already do. Without that, a prior attempt whose metadata write succeeded but whose
|
||||
* checksum write then failed would leave a stale checksum in place forever: every later
|
||||
* request for this exact package would keep finding nothing new to add and keep taking this
|
||||
* same no-op path, never repairing it, so a client verifying checksums could keep failing
|
||||
* indefinitely even once the sidecar itself has long since recovered.
|
||||
*/
|
||||
public boolean mergeExternalConnectionReleaseVersions(String repositoryContainerId, String namespace,
|
||||
String packageName, byte[] externalMetadataXml, Predicate<String> versionAllowed) {
|
||||
ensureRepository(repositoryContainerId);
|
||||
String externalXml = new String(externalMetadataXml, StandardCharsets.UTF_8);
|
||||
List<String> externalReleaseVersions = XmlParser.extractAll(externalXml, "version").stream()
|
||||
.filter(v -> !v.endsWith("-SNAPSHOT"))
|
||||
.filter(versionAllowed)
|
||||
.toList();
|
||||
if (externalReleaseVersions.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String gav = artifactMetadataGav(namespace, packageName);
|
||||
Optional<FetchedArtifact> existing = fetchArtifactConfirmingMissing(repositoryContainerId, gav);
|
||||
List<String> versions = new ArrayList<>();
|
||||
String groupId = namespace;
|
||||
String artifactId = packageName;
|
||||
String latest = null;
|
||||
String release = null;
|
||||
boolean hadLocalMetadata = existing.isPresent();
|
||||
if (hadLocalMetadata) {
|
||||
String xml = new String(existing.get().content(), StandardCharsets.UTF_8);
|
||||
versions.addAll(XmlParser.extractAll(xml, "version"));
|
||||
groupId = XmlParser.extractFirst(xml, "groupId", namespace);
|
||||
artifactId = XmlParser.extractFirst(xml, "artifactId", packageName);
|
||||
latest = XmlParser.extractFirst(xml, "latest", null);
|
||||
release = XmlParser.extractFirst(xml, "release", null);
|
||||
}
|
||||
boolean addedAny = false;
|
||||
for (String version : externalReleaseVersions) {
|
||||
if (!versions.contains(version)) {
|
||||
versions.add(version);
|
||||
addedAny = true;
|
||||
}
|
||||
}
|
||||
if (!addedAny) {
|
||||
if (hadLocalMetadata) {
|
||||
writeMetadataChecksum(repositoryContainerId, gav + ".sha1",
|
||||
Digests.sha1Hex(existing.get().content()));
|
||||
writeMetadataChecksum(repositoryContainerId, gav + ".md5",
|
||||
Digests.md5Hex(existing.get().content()));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!hadLocalMetadata) {
|
||||
groupId = XmlParser.extractFirst(externalXml, "groupId", namespace);
|
||||
artifactId = XmlParser.extractFirst(externalXml, "artifactId", packageName);
|
||||
// The external source's own declared <latest>/<release> are trusted only when they
|
||||
// actually name one of this merge's own release versions: a public repository could
|
||||
// declare a SNAPSHOT (or any other value already filtered out above) as its latest,
|
||||
// which must never end up named here without also being listed in <versions>.
|
||||
String lastReleaseVersion = externalReleaseVersions.get(externalReleaseVersions.size() - 1);
|
||||
String declaredLatest = XmlParser.extractFirst(externalXml, "latest", null);
|
||||
latest = externalReleaseVersions.contains(declaredLatest) ? declaredLatest : lastReleaseVersion;
|
||||
String declaredRelease = XmlParser.extractFirst(externalXml, "release", null);
|
||||
release = externalReleaseVersions.contains(declaredRelease) ? declaredRelease : lastReleaseVersion;
|
||||
}
|
||||
XmlBuilder metadata = new XmlBuilder().start("metadata")
|
||||
.elem("groupId", groupId)
|
||||
.elem("artifactId", artifactId)
|
||||
.start("versioning")
|
||||
.elem("latest", latest)
|
||||
.elem("release", release)
|
||||
.start("versions");
|
||||
for (String v : versions) {
|
||||
metadata.elem("version", v);
|
||||
}
|
||||
metadata.end("versions")
|
||||
.elem("lastUpdated", METADATA_TIMESTAMP.format(Instant.now()))
|
||||
.end("versioning")
|
||||
.end("metadata");
|
||||
byte[] metadataBytes = metadata.build().getBytes(StandardCharsets.UTF_8);
|
||||
DeployOutcome outcome = deployArtifact(repositoryContainerId, gav, metadataBytes);
|
||||
if (!outcome.wroteNewContent()) {
|
||||
throw new IllegalStateException("Could not merge external connection release versions into "
|
||||
+ packageName + "'s maven-metadata.xml on the Reposilite sidecar: upstream returned "
|
||||
+ outcome.status());
|
||||
}
|
||||
writeMetadataChecksum(repositoryContainerId, gav + ".sha1", Digests.sha1Hex(metadataBytes));
|
||||
writeMetadataChecksum(repositoryContainerId, gav + ".md5", Digests.md5Hex(metadataBytes));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #recordVersionAvailable}'s dispose-time counterpart (found missing by Qodo review on
|
||||
* the PR that added {@code DisposePackageVersions}): without this, a disposed Maven version's
|
||||
|
||||
+17
@@ -67,6 +67,23 @@ public interface RepositorySidecarManager {
|
||||
boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName);
|
||||
|
||||
/**
|
||||
* {@code true} when this sidecar has written anything at all under this package, even content
|
||||
* that would not count as "holding a version" for {@link #packageExists}: a Maven
|
||||
* group/artifact directory that only ever got a {@code maven-metadata.xml} merged into it to
|
||||
* advertise a public repository's release list, with no version ever actually retained, is
|
||||
* real content a {@code DeletePackage} still has to clear, even though {@link #packageExists}
|
||||
* correctly answers {@code false} for it. Defaults to exactly {@link #packageExists}, since no
|
||||
* other format currently has an equivalent metadata-but-no-version state; {@code
|
||||
* ReposiliteSidecarClient} is the only implementation that overrides this, so a package left
|
||||
* in that state is still actually deleted rather than {@code DeletePackage} reporting success
|
||||
* while leaving it fetchable.
|
||||
*/
|
||||
default boolean hasAnyContentToDelete(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName) {
|
||||
return packageExists(repositoryContainerId, domain, repository, namespace, packageName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code true} when this sidecar holds exactly the named version of the named package, for
|
||||
* bridging {@code DescribePackageVersion} when there is no generic-format record to describe:
|
||||
|
||||
Reference in new issue
Block a user