fix(codeartifact): resolve upstreams in AWS's order, through their external connections (#8356)

Three ways a read through upstream repositories differed from the User
Guide:

- Upstreams were searched breadth-first. "If an upstream repository has
  its own upstream repositories, the same logic is used to find a package
  version before moving to the next upstream repository": the guide's
  own example, my_repo with upstreams A and B, A with C and D and D with
  E, is searched my_repo, A, C, D, E, B. The walk is depth-first in each
  repository's listed order now.
- A version an upstream had itself retained named that upstream as its
  origin, and one the upstream got from public:npmjs came back INTERNAL.
  A version's DomainEntryPoint is where it "originally entered" the
  domain, so a retained version now carries its upstream's own entry
  point: the external connection, EXTERNAL, or the repository it was
  published to, however many upstreams it came through. It is read
  again when the version's claim is confirmed, so a copy made while the
  upstream's own fetch is still finishing gets that fetch's connection.
- An upstream's external connection was never consulted, so a version no
  upstream had fetched yet was a 404. AWS fetches it through the
  upstream's connection and retains it there and in the repository the
  request was made to. A miss at every upstream now tries the external
  connections of the upstreams in the same order, for npm, Maven, PyPI
  and NuGet, and a packument, Simple index or maven-metadata.xml read
  through such an upstream offers what its connection has. That fetch
  skips a version Archived or Disposed at the upstream, or here in the
  Simple index, reads this repository's fences before it starts, so a
  deletion during it is not undone, and passes on an npm client's ask
  for the full packument. The four formats share it in
  UpstreamExternalConnectionFetch.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 15:42:29 -04:00
1 parent 045ecc4eeb
commit e286aef015
23 files changed
+984 -149

No files matched your search

+18 -13
View File
@@ -419,19 +419,24 @@ state.
A repository-to-repository upstream chain resolves the same way, for all four formats, reusing
the exact claim/fence/origin-tracking machinery above: a GET/HEAD/tarball-download/packument
miss searches the repository's own `upstreams`, transitively (an upstream's own upstreams are
searched too, breadth-first, matching AWS's documented priority order) and not just its direct
list, for the first repository with a usable copy. Two real differences from the
external-connection case: an Archived or Disposed version *at the resolved upstream repository
itself* is skipped, the walk continuing to the next candidate, since a same-domain upstream has
a real CodeArtifact-shaped status to check that a public registry never does; and each candidate
is checked only for what it already has retained, not what it could itself still pull from its
own configured external connection (AWS documents a downstream request chaining through an
upstream's own external connection too, so a version a candidate upstream hasn't fetched yet
from its own `public:*` connection stays a miss here, even though AWS would resolve it). Since a
same-domain upstream read never leaves this process, pypi's own version here needs none of the
real external connection's PEP 691 sha256 re-verification or background-thread split: every
asset of the resolved version is imported synchronously, in one pass.
miss searches the repository's own `upstreams`, transitively, for the first repository with a
usable copy. The order is AWS's documented priority order: depth-first, in each repository's
listed order, an upstream's own upstreams searched before the next one, so `my_repo` with
upstreams `A` and `B`, `A` with `C` and `D` and `D` with `E` is searched `A, C, D, E, B`. An
Archived or Disposed version *at the resolved upstream repository itself* is skipped, the walk
continuing to the next candidate, since a same-domain upstream has a real CodeArtifact-shaped
status to check that a public registry never does. A version no upstream holds is fetched
through an upstream's own external connection, the first in that same order that has one, and
retained both there and in the repository the request was made to, as AWS documents for a
downstream request chaining through an upstream's `public:*` connection; a packument, Simple
index or `maven-metadata.xml` read through such an upstream offers what its connection has too.
A retained version's `origin.domainEntryPoint` names where it entered the domain: the external
connection it was fetched through, `EXTERNAL`, or the repository it was published to, however
many upstreams it was retained through. Since the copy from a same-domain upstream never leaves
this process (a fetch through an upstream's connection is that connection's own import), pypi's
own copy here needs none of the real external connection's PEP 691 sha256 re-verification or
background-thread split: every asset of the resolved version is copied synchronously, in one
pass.
- **Maven external-connection retention is the one place this emulator makes a real outbound
call to the public internet**, rather than only ever talking to a container it started itself.
An offline environment, or a real outage of the public repository being connected to, means a
@@ -372,6 +372,18 @@ public class CodeArtifactMavenExternalConnectionImporter {
false);
}
/**
* Whether {@code repository} has a Maven external connection to fetch through. A repository
* deleted since its name was read, as an upstream in a search order can be, has none.
*/
boolean hasExternalConnection(String region, String domain, String owner, String repository) {
try {
return mavenExternalConnectionName(region, domain, owner, repository) != null;
} catch (AwsException e) {
return false;
}
}
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()))
@@ -26,11 +26,15 @@ import java.util.function.Predicate;
* <ul>
* <li><b>Transitive search, in priority order.</b> {@link
* CodeArtifactService#resolveUpstreamSearchOrder} walks {@code repository}'s own direct
* upstreams first, then theirs, breadth-first, matching AWS's own documented "Upstream
* repository priority order." The first candidate with the requested asset wins; it may be
* several hops deep, not necessarily a direct upstream of {@code repository} itself. Reposilite
* upstreams in their listed order, each one's own upstreams before the next one, depth-first,
* matching AWS's own documented "Upstream repository priority order." The first candidate with
* the requested asset wins; it may be several hops deep, not necessarily a direct upstream of
* {@code repository} itself. Reposilite
* scopes entirely by its own {@code repoId}, never by path, so the same {@code gav} string is
* checked against each candidate's own id in turn.</li>
* <li><b>Through an upstream's external connection.</b> An artifact no upstream holds is fetched
* through the first upstream, in the same order, with an external connection, and retained there
* and then here, as the User Guide's chain example has it.</li>
* <li><b>No SNAPSHOT exclusion.</b> The external-connection importer's "release versions only"
* rule is AWS's own documented restriction for a real public registry, which never has a
* Floci-internal SNAPSHOT concept at all; nothing says the same for a same-domain upstream, and
@@ -56,12 +60,14 @@ public class CodeArtifactMavenUpstreamRepositoryImporter {
private final CodeArtifactService service;
private final ReposiliteSidecarClient reposilite;
private final CodeArtifactMavenExternalConnectionImporter externalConnectionImporter;
@Inject
public CodeArtifactMavenUpstreamRepositoryImporter(CodeArtifactService service,
ReposiliteSidecarClient reposilite) {
public CodeArtifactMavenUpstreamRepositoryImporter(CodeArtifactService service, ReposiliteSidecarClient reposilite,
CodeArtifactMavenExternalConnectionImporter externalConnectionImporter) {
this.service = service;
this.reposilite = reposilite;
this.externalConnectionImporter = externalConnectionImporter;
}
/**
@@ -92,6 +98,14 @@ public class CodeArtifactMavenUpstreamRepositoryImporter {
"INTERNAL_UPSTREAM")) {
return false;
}
// Snapshotted before the walk, not once a candidate is found, the same ordering
// CodeArtifactMavenExternalConnectionImporter#tryImport relies on: the walk's last leg can
// fetch through an upstream's external connection, and a deletion here during that fetch
// must still move the fence away from the snapshot.
long fenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, "maven",
namespace, packageName);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"maven", namespace, packageName, version);
String upstreamRepository = null;
String upstreamRepoId = null;
@@ -130,13 +144,24 @@ public class CodeArtifactMavenUpstreamRepositoryImporter {
}
}
}
if (upstreamRepository == null) {
Optional<UpstreamExternalConnectionFetch.Fetched> fetched = UpstreamExternalConnectionFetch.firstFetched(
service, reposilite, "maven", region, domain, owner, repository, namespace, packageName,
candidate -> externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate),
(candidate, candidateRepoId) -> externalConnectionImporter.tryImport(region, domain, owner,
candidate, candidateRepoId, gav) ? Optional.of(version) : Optional.empty());
if (fetched.isPresent()) {
upstreamRepository = fetched.get().repository();
upstreamRepoId = fetched.get().repoId();
}
}
if (upstreamRepository == null) {
return false;
}
try {
return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, gav, namespace,
packageName, version, upstreamRepository, upstreamRepoId);
packageName, version, upstreamRepository, upstreamRepoId, fenceSnapshot, versionFenceSnapshot);
} finally {
reposilite.endUse(upstreamRepoId);
}
@@ -144,13 +169,7 @@ public class CodeArtifactMavenUpstreamRepositoryImporter {
private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository,
String repoId, String gav, String namespace, String packageName, String version,
String upstreamRepository, String upstreamRepoId) {
// Snapshotted before the claim and the real writes below, not after, the same ordering
// CodeArtifactMavenExternalConnectionImporter#tryImport already relies on.
long fenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository, "maven",
namespace, packageName);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"maven", namespace, packageName, version);
String upstreamRepository, String upstreamRepoId, long fenceSnapshot, long versionFenceSnapshot) {
CodeArtifactService.MavenClaimOutcome claim = service.claimMavenRetainedVersionOrigin(region, domain, owner,
repository, namespace, packageName, version, upstreamRepository,
RetentionOriginKind.UPSTREAM_REPOSITORY, fenceSnapshot);
@@ -277,6 +296,19 @@ public class CodeArtifactMavenUpstreamRepositoryImporter {
// within this same candidate's lease), so it is always released before moving on,
// whether this candidate won or not.
try {
// A candidate with an external connection offers what that connection has too, as a
// request to it would: the public releases are merged into its metadata first. A merge
// that fails leaves the candidate's own metadata to read, as it was.
if (externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate)) {
try {
externalConnectionImporter.tryImport(region, domain, owner, candidate, candidateRepoId,
metadataGav);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not merge {0}/{1}''s public releases into upstream repository {2}''s "
+ "maven-metadata.xml through its external connection; reading its own as it is.",
namespace, packageName, candidate);
}
}
Optional<ReposiliteSidecarClient.StreamedArtifact> fetched;
try {
fetched = reposilite.fetchArtifactStreamed(candidateRepoId, metadataGav);
@@ -199,8 +199,8 @@ public class CodeArtifactNpmDataPlane {
* never both, so at most one of these two ever finds anything, and the other's own no-op is a
* single cheap in-memory check (see {@code CodeArtifactNpmUpstreamRepositoryImporter}'s own
* javadoc). Runs on the blocking worker thread {@link #handle}'s own {@code executeBlocking}
* call already dispatched to; both calls only ever touch local sidecar state here, never a
* real external network call for the upstream one.
* call already dispatched to; the upstream one makes a real external network call only through
* an upstream's own external connection.
*/
private ObjectNode mergedPackumentFromEitherSource(AuthorizationTokenScope tokenScope, NpmRequest npmRequest,
String repoId, PackageIdentity identity, boolean fullMetadata) {
@@ -208,7 +208,7 @@ public class CodeArtifactNpmDataPlane {
tokenScope.owner(), npmRequest.repository(), repoId, identity.namespace(), identity.packageName(),
fullMetadata).or(() -> upstreamRepositoryImporter.mergedPackument(tokenScope.region(),
npmRequest.domain(), tokenScope.owner(), npmRequest.repository(), repoId,
identity.namespace(), identity.packageName())).orElse(null);
identity.namespace(), identity.packageName(), fullMetadata)).orElse(null);
}
/**
@@ -416,6 +416,18 @@ public class CodeArtifactNpmExternalConnectionImporter {
return packageName + "-" + version + ".tgz";
}
/**
* Whether {@code repository} has an npm external connection to fetch through. A repository
* deleted since its name was read, as an upstream in a search order can be, has none.
*/
boolean hasExternalConnection(String region, String domain, String owner, String repository) {
try {
return npmExternalConnectionName(region, domain, owner, repository) != null;
} catch (AwsException e) {
return false;
}
}
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()))
@@ -39,8 +39,12 @@ import java.util.Optional;
* source.</li>
* <li><b>Transitive search, in priority order.</b> {@link
* CodeArtifactService#resolveUpstreamSearchOrder} walks {@code repository}'s own direct
* upstreams first, then theirs, breadth-first. The first candidate whose own packument names the
* requested version wins; it may be several hops deep.</li>
* upstreams in their listed order, each one's own upstreams before the next one, depth-first.
* The first candidate whose own packument names the requested version wins; it may be several
* hops deep.</li>
* <li><b>Through an upstream's external connection.</b> A version no upstream holds is fetched
* through the first upstream, in the same order, with an external connection, and retained there
* and then here, as the User Guide's chain example has it.</li>
* <li><b>Archived/Disposed propagation.</b> A candidate's own copy of the version must still be
* downloadable there (checked via {@link
* CodeArtifactService#requireContainerBackedVersionDownloadable}): the walk skips an Archived or
@@ -59,13 +63,15 @@ public class CodeArtifactNpmUpstreamRepositoryImporter {
private final CodeArtifactService service;
private final VerdaccioSidecarClient verdaccio;
private final ObjectMapper mapper;
private final CodeArtifactNpmExternalConnectionImporter externalConnectionImporter;
@Inject
public CodeArtifactNpmUpstreamRepositoryImporter(CodeArtifactService service, VerdaccioSidecarClient verdaccio,
ObjectMapper mapper) {
ObjectMapper mapper, CodeArtifactNpmExternalConnectionImporter externalConnectionImporter) {
this.service = service;
this.verdaccio = verdaccio;
this.mapper = mapper;
this.externalConnectionImporter = externalConnectionImporter;
}
/**
@@ -73,10 +79,11 @@ public class CodeArtifactNpmUpstreamRepositoryImporter {
* sourced from the first eligible upstream candidate's own stored packument instead of a real
* registry fetch. Always merges every package-level descriptive field the candidate's document
* has (there is no abbreviated-vs-full distinction for a same-domain read, see this class's own
* javadoc).
* javadoc). {@code fullMetadata}, the client's own ask, goes on to a candidate's external
* connection, whose document leaves those fields out when it is the abbreviated one.
*/
public Optional<ObjectNode> mergedPackument(String region, String domain, String owner, String repository,
String repoId, String namespace, String packageName) {
String repoId, String namespace, String packageName, boolean fullMetadata) {
if (service.describeRepository(region, domain, owner, repository).getUpstreams().isEmpty()) {
return Optional.empty();
}
@@ -98,7 +105,14 @@ public class CodeArtifactNpmUpstreamRepositoryImporter {
try {
String candidateBaseUrl = verdaccio.ensureReady(candidateRepoId,
verdaccio.publicUrl(domain, candidate));
JsonNode external = verdaccio.fetchPackageDocument(candidateBaseUrl, namespace, packageName)
// A candidate with an external connection offers what that connection has too, as
// a request to it would: a version it has not fetched yet is fetched there first.
JsonNode external = (externalConnectionImporter.hasExternalConnection(region, domain, owner,
candidate)
? externalConnectionImporter.mergedPackument(region, domain, owner, candidate,
candidateRepoId, namespace, packageName, fullMetadata).<JsonNode>map(merged -> merged)
: Optional.<JsonNode>empty())
.or(() -> verdaccio.fetchPackageDocument(candidateBaseUrl, namespace, packageName))
.orElse(null);
if (external == null) {
continue;
@@ -203,6 +217,13 @@ public class CodeArtifactNpmUpstreamRepositoryImporter {
"INTERNAL_UPSTREAM")) {
return false;
}
// Snapshotted before the walk, not once a candidate is found: its last leg can fetch through
// an upstream's external connection, and a deletion here during that fetch must still move
// the fence away from the snapshot (see claimRetainedVersionOrigin's own javadoc).
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"npm", namespace, packageName);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"npm", namespace, packageName, version);
String upstreamRepository = null;
String upstreamRepoId = null;
@@ -242,13 +263,26 @@ public class CodeArtifactNpmUpstreamRepositoryImporter {
}
}
}
if (upstreamRepository == null) {
Optional<UpstreamExternalConnectionFetch.Fetched> fetched = UpstreamExternalConnectionFetch.firstFetched(
service, verdaccio, "npm", region, domain, owner, repository, namespace, packageName,
candidate -> externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate),
(candidate, candidateRepoId) -> externalConnectionImporter.tryImportAsset(region, domain, owner,
candidate, candidateRepoId, namespace, packageName, version, assetName)
? Optional.of(version) : Optional.empty());
if (fetched.isPresent()) {
upstreamRepository = fetched.get().repository();
upstreamRepoId = fetched.get().repoId();
}
}
if (upstreamRepository == null) {
return false;
}
try {
return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, namespace, packageName,
version, assetName, upstreamRepository, upstreamRepoId);
version, assetName, upstreamRepository, upstreamRepoId, packageFenceSnapshot,
versionFenceSnapshot);
} finally {
verdaccio.endUse(upstreamRepoId);
}
@@ -256,11 +290,7 @@ public class CodeArtifactNpmUpstreamRepositoryImporter {
private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository,
String repoId, String namespace, String packageName, String version, String assetName,
String upstreamRepository, String upstreamRepoId) {
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"npm", namespace, packageName);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"npm", namespace, packageName, version);
String upstreamRepository, String upstreamRepoId, long packageFenceSnapshot, long versionFenceSnapshot) {
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
domain, owner, repository, "npm", namespace, packageName, version, upstreamRepository,
RetentionOriginKind.UPSTREAM_REPOSITORY, packageFenceSnapshot);
@@ -1,5 +1,6 @@
package io.floci.aws.services.codeartifact;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.ExternalConnection;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -191,6 +192,18 @@ public class CodeArtifactNuGetExternalConnectionImporter {
}
}
/**
* Whether {@code repository} has a NuGet external connection to fetch through. A repository
* deleted since its name was read, as an upstream in a search order can be, has none.
*/
boolean hasExternalConnection(String region, String domain, String owner, String repository) {
try {
return nugetExternalConnectionName(region, domain, owner, repository) != null;
} catch (AwsException e) {
return false;
}
}
private String nugetExternalConnectionName(String region, String domain, String owner, String repository) {
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
.filter(ec -> "nuget".equals(ec.getPackageFormat()))
@@ -22,9 +22,13 @@ import java.util.Optional;
* <ul>
* <li><b>Transitive search, in priority order.</b> {@link
* CodeArtifactService#resolveUpstreamSearchOrder} walks {@code repository}'s own direct
* upstreams first, then theirs, breadth-first, matching AWS's own documented "Upstream
* repository priority order." The first candidate with the requested version wins; it may be
* several hops deep, not necessarily a direct upstream of {@code repository} itself.</li>
* upstreams in their listed order, each one's own upstreams before the next one, depth-first,
* matching AWS's own documented "Upstream repository priority order." The first candidate with
* the requested version wins; it may be several hops deep, not necessarily a direct upstream of
* {@code repository} itself.</li>
* <li><b>Through an upstream's external connection.</b> A version no upstream holds is fetched
* through the first upstream, in the same order, with an external connection, and retained there
* and then here, as the User Guide's chain example has it.</li>
* <li><b>Archived/Disposed propagation.</b> A candidate's own copy of the version must still be
* downloadable there (checked via {@link
* CodeArtifactService#requireContainerBackedVersionDownloadable}): an Archived or Disposed
@@ -40,11 +44,14 @@ public class CodeArtifactNuGetUpstreamRepositoryImporter {
private final CodeArtifactService service;
private final BagetterSidecarClient bagetter;
private final CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter;
@Inject
public CodeArtifactNuGetUpstreamRepositoryImporter(CodeArtifactService service, BagetterSidecarClient bagetter) {
public CodeArtifactNuGetUpstreamRepositoryImporter(CodeArtifactService service, BagetterSidecarClient bagetter,
CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter) {
this.service = service;
this.bagetter = bagetter;
this.externalConnectionImporter = externalConnectionImporter;
}
/**
@@ -64,6 +71,14 @@ public class CodeArtifactNuGetUpstreamRepositoryImporter {
"INTERNAL_UPSTREAM")) {
return false;
}
// Snapshotted before the walk, not once a candidate is found, the same ordering
// CodeArtifactNuGetExternalConnectionImporter#tryImport relies on: the walk's last leg can
// fetch through an upstream's external connection, and a deletion here during that fetch
// must still move the fence away from the snapshot.
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"nuget", null, packageId);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"nuget", null, packageId, version);
String upstreamRepository = null;
String upstreamRepoId = null;
@@ -108,26 +123,32 @@ public class CodeArtifactNuGetUpstreamRepositoryImporter {
}
}
}
if (upstreamRepository == null) {
Optional<UpstreamExternalConnectionFetch.Fetched> fetched = UpstreamExternalConnectionFetch.firstFetched(
service, bagetter, "nuget", region, domain, owner, repository, null, packageId,
candidate -> externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate),
(candidate, candidateRepoId) -> externalConnectionImporter.tryImport(region, domain, owner,
candidate, candidateRepoId, packageId, version) ? Optional.of(version) : Optional.empty());
if (fetched.isPresent()) {
upstreamRepository = fetched.get().repository();
upstreamRepoId = fetched.get().repoId();
}
}
if (upstreamRepository == null) {
return false;
}
try {
return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, packageId, version,
upstreamRepository, upstreamRepoId);
upstreamRepository, upstreamRepoId, packageFenceSnapshot, versionFenceSnapshot);
} finally {
bagetter.endUse(upstreamRepoId);
}
}
private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository,
String repoId, String packageId, String version, String upstreamRepository, String upstreamRepoId) {
// Snapshotted before the claim and the real write below, not after, the same ordering
// CodeArtifactNuGetExternalConnectionImporter#tryImport already relies on.
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"nuget", null, packageId);
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"nuget", null, packageId, version);
String repoId, String packageId, String version, String upstreamRepository, String upstreamRepoId,
long packageFenceSnapshot, long versionFenceSnapshot) {
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
domain, owner, repository, "nuget", null, packageId, version, upstreamRepository,
RetentionOriginKind.UPSTREAM_REPOSITORY, packageFenceSnapshot);
@@ -23,6 +23,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
/**
* Retains pypi package versions from the real public repository a repository's {@code
@@ -148,6 +149,19 @@ public class CodeArtifactPypiExternalConnectionImporter {
*/
public List<ExternalIndexFile> additionalExternalFilenames(String region, String domain, String owner,
String repository, String repoId, String packageName, Set<String> alreadyKnownFilenames) {
return additionalExternalFilenames(region, domain, owner, repository, repoId, packageName,
alreadyKnownFilenames, version -> true);
}
/**
* {@link #additionalExternalFilenames(String, String, String, String, String, String, Set)},
* leaving out as well a file whose version {@code listable} refuses: a downstream repository
* listing this one's files through its upstreams leaves out a version it marked Archived or
* Disposed itself.
*/
List<ExternalIndexFile> additionalExternalFilenames(String region, String domain, String owner,
String repository, String repoId, String packageName, Set<String> alreadyKnownFilenames,
Predicate<String> listable) {
String externalConnectionName = pypiExternalConnectionName(region, domain, owner, repository);
if (externalConnectionName == null) {
return List.of();
@@ -168,7 +182,7 @@ public class CodeArtifactPypiExternalConnectionImporter {
continue;
}
Optional<String> version = resolveVersion(versions, packageName, filename);
if (version.isEmpty()) {
if (version.isEmpty() || !listable.test(version.get())) {
continue;
}
try {
@@ -583,6 +597,18 @@ public class CodeArtifactPypiExternalConnectionImporter {
.findFirst();
}
/**
* Whether {@code repository} has a PyPI external connection to fetch through. A repository
* deleted since its name was read, as an upstream in a search order can be, has none.
*/
boolean hasExternalConnection(String region, String domain, String owner, String repository) {
try {
return pypiExternalConnectionName(region, domain, owner, repository) != null;
} catch (AwsException e) {
return false;
}
}
private String pypiExternalConnectionName(String region, String domain, String owner, String repository) {
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
.filter(ec -> "pypi".equals(ec.getPackageFormat()))
@@ -10,6 +10,7 @@ import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -36,8 +37,12 @@ import java.util.concurrent.ConcurrentHashMap;
* multi-asset copy.</li>
* <li><b>Transitive search, in priority order.</b> {@link
* CodeArtifactService#resolveUpstreamSearchOrder} walks {@code repository}'s own direct
* upstreams first, then theirs, breadth-first. The first candidate whose own version list names
* a version {@code filename} belongs to wins; it may be several hops deep.</li>
* upstreams in their listed order, each one's own upstreams before the next one, depth-first.
* The first candidate whose own version list names a version {@code filename} belongs to wins;
* it may be several hops deep.</li>
* <li><b>Through an upstream's external connection.</b> A file no upstream holds is fetched
* through the first upstream, in the same order, with an external connection, and retained there
* and then here, as the User Guide's chain example has it.</li>
* <li><b>Archived/Disposed propagation.</b> A candidate's own copy of the version must still be
* downloadable there (checked via {@link
* CodeArtifactService#requireContainerBackedVersionDownloadable}): the walk skips an Archived or
@@ -59,11 +64,14 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
// since a repository has either an external connection or upstreams, never both.
private final ConcurrentHashMap<String, Object> assetWriteLocks = new ConcurrentHashMap<>();
private final CodeArtifactPypiExternalConnectionImporter externalConnectionImporter;
@Inject
public CodeArtifactPypiUpstreamRepositoryImporter(CodeArtifactService service,
PypiserverSidecarClient pypiserver) {
PypiserverSidecarClient pypiserver, CodeArtifactPypiExternalConnectionImporter externalConnectionImporter) {
this.service = service;
this.pypiserver = pypiserver;
this.externalConnectionImporter = externalConnectionImporter;
}
/**
@@ -95,17 +103,10 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
}
try {
List<String> versions = packageVersionsAt(candidateRepoId, domain, candidate, packageName);
if (versions.isEmpty()) {
continue;
}
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional = new ArrayList<>();
for (String version : versions) {
try {
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "pypi",
null, packageName, version, repoId);
service.requireContainerBackedVersionDownloadable(owner, region, domain, candidate, "pypi",
null, packageName, version, candidateRepoId);
} catch (AwsException e) {
if (!downloadable(owner, region, domain, repository, packageName, version, repoId)
|| !downloadable(owner, region, domain, candidate, packageName, version, candidateRepoId)) {
continue;
}
for (String filename : assetNamesAt(candidateRepoId, domain, candidate, packageName, version)) {
@@ -115,6 +116,15 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
}
}
}
// A candidate with an external connection offers what that connection has too, as a
// request to it would: a file it has not fetched yet is fetched there first.
if (externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate)) {
Set<String> known = new HashSet<>(alreadyKnownFilenames);
additional.forEach(file -> known.add(file.filename()));
additional.addAll(externalConnectionImporter.additionalExternalFilenames(region, domain, owner,
candidate, candidateRepoId, packageName, known,
version -> downloadable(owner, region, domain, repository, packageName, version, repoId)));
}
if (!additional.isEmpty()) {
return additional;
}
@@ -148,6 +158,13 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
"INTERNAL_UPSTREAM")) {
return false;
}
// Snapshotted before the walk, not once a candidate is found, the same ordering
// CodeArtifactPypiExternalConnectionImporter#tryImportAsset relies on: the walk's last leg
// can fetch through an upstream's external connection, and a DeletePackage here during that
// fetch must still move the fence away from the snapshot. The version fence waits for the
// version, which only the walk resolves.
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"pypi", null, packageName.get());
String upstreamRepository = null;
String upstreamRepoId = null;
@@ -166,12 +183,8 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
// below are entirely done with it (see the try/finally right after this loop).
boolean eligible = false;
try {
Optional<String> matchedVersion = packageVersionsAt(candidateRepoId, domain, candidate,
packageName.get()).stream()
.filter(v -> PypiserverSidecarClient.filenameEmbedsVersion(filename, packageName.get(), v))
.filter(v -> assetNamesAt(candidateRepoId, domain, candidate, packageName.get(), v)
.contains(filename))
.findFirst();
Optional<String> matchedVersion = versionHolding(candidateRepoId, domain, candidate,
packageName.get(), filename);
if (matchedVersion.isEmpty()) {
continue;
}
@@ -194,13 +207,27 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
}
}
}
if (upstreamRepository == null) {
Optional<UpstreamExternalConnectionFetch.Fetched> fetched = UpstreamExternalConnectionFetch.firstFetched(
service, pypiserver, "pypi", region, domain, owner, repository, null, packageName.get(),
candidate -> externalConnectionImporter.hasExternalConnection(region, domain, owner, candidate),
(candidate, candidateRepoId) -> externalConnectionImporter.tryImportAsset(region, domain, owner,
candidate, candidateRepoId, filename)
? versionHolding(candidateRepoId, domain, candidate, packageName.get(), filename)
: Optional.empty());
if (fetched.isPresent()) {
upstreamRepository = fetched.get().repository();
upstreamRepoId = fetched.get().repoId();
version = fetched.get().version();
}
}
if (upstreamRepository == null) {
return false;
}
try {
return tryImportFromClaimedCandidate(region, domain, owner, repository, repoId, filename,
packageName.get(), version, upstreamRepository, upstreamRepoId);
packageName.get(), version, upstreamRepository, upstreamRepoId, packageFenceSnapshot);
} finally {
pypiserver.endUse(upstreamRepoId);
}
@@ -208,9 +235,7 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
private boolean tryImportFromClaimedCandidate(String region, String domain, String owner, String repository,
String repoId, String filename, String packageName, String version, String upstreamRepository,
String upstreamRepoId) {
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
"pypi", null, packageName);
String upstreamRepoId, long packageFenceSnapshot) {
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
"pypi", null, packageName, version);
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
@@ -334,6 +359,27 @@ public class CodeArtifactPypiUpstreamRepositoryImporter {
}
}
/** The version of {@code packageName} at {@code repository} that holds {@code filename}, if one does. */
private Optional<String> versionHolding(String repoId, String domain, String repository, String packageName,
String filename) {
return packageVersionsAt(repoId, domain, repository, packageName).stream()
.filter(v -> PypiserverSidecarClient.filenameEmbedsVersion(filename, packageName, v))
.filter(v -> assetNamesAt(repoId, domain, repository, packageName, v).contains(filename))
.findFirst();
}
/** Whether {@code version} is neither Archived nor Disposed at {@code repository}. */
private boolean downloadable(String owner, String region, String domain, String repository, String packageName,
String version, String repoId) {
try {
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, "pypi", null,
packageName, version, repoId);
return true;
} catch (AwsException e) {
return false;
}
}
private List<String> packageVersionsAt(String repoId, String domain, String repository, String packageName) {
try {
return pypiserver.listPackageVersions(repoId, domain, repository, null, packageName).stream()
@@ -388,9 +388,37 @@ public class CodeArtifactService implements Resettable {
* claim is created from nothing (never on an increment of an existing one), so a finish call
* for an episode already torn down and replaced by a new one under the same source name
* can never be mistaken for a finish of that new episode (see the field's own javadoc above).
* {@code entryPoint} is where the version entered the domain, which is what the version's
* origin reports (see {@link #entryPointThrough}).
*/
private record RetainedVersionOriginClaim(String originName, RetentionOriginKind originKind,
int inFlightAttempts, boolean confirmed, long episodeId) {
int inFlightAttempts, boolean confirmed, long episodeId, EntryPoint entryPoint) {
}
/**
* Where a package version entered the domain, AWS's {@code DomainEntryPoint}: the external
* connection it was fetched from, or the repository it was published to.
*/
private record EntryPoint(RetentionOriginKind kind, String name) {
}
/**
* The entry point of a version retained from {@code upstreamRepository}: the one its copy there
* has when that copy was itself retained, from an external connection or from a repository
* further up, and the upstream repository when the version was published there. A claim still
* in flight there counts: the copy read from the upstream can be the one that claim just wrote,
* before the attempt that wrote it confirms it. Read when the version is retained, and again
* when its own claim is confirmed (see {@link #finishRetainedVersionOriginAttempt}), so a later
* change at the upstream does not move it, as the retained version itself is not affected by
* one.
*/
private EntryPoint entryPointThrough(String owner, String region, String domain, String upstreamRepository,
String format, String namespace, String packageName, String version) {
RetainedVersionOriginClaim upstreamClaim = retainedVersionOriginConnections.get(ownerScopedKey(owner,
packageVersionKey(region, domain, upstreamRepository, format, namespace,
accountingPackageName(format, packageName), normalizedContainerBackedVersion(format, version))));
return upstreamClaim != null ? upstreamClaim.entryPoint()
: new EntryPoint(RetentionOriginKind.UPSTREAM_REPOSITORY, upstreamRepository);
}
/**
@@ -2791,16 +2819,14 @@ public class CodeArtifactService implements Resettable {
}
/**
* {@code originType} plus the domain entry point a caller needs to render it: for {@code
* EXTERNAL}, the exact external connection a version was retained from; for an {@code
* INTERNAL} version genuinely retained from a same-domain upstream repository (real AWS has
* no third {@code originType} value for this, confirmed against the live {@code
* PackageVersionOrigin} API reference, which lists only {@code INTERNAL}/{@code EXTERNAL}/
* {@code UNKNOWN}), {@code upstreamRepositoryName}; for a true direct publish, neither is set.
* AWS's own {@code DomainEntryPoint} reference describes an ingested package's entry point as
* the source it came from, {@code repositoryName} only for one published directly, so a caller
* surfacing a domain entry point needs the real source's name itself, not just the originType
* flag.
* {@code originType} plus the domain entry point a caller needs to render it, where the version
* "originally entered" the domain ({@code DomainEntryPoint}): for {@code EXTERNAL}, the external
* connection it was fetched through, this repository's or an upstream's; for an {@code INTERNAL}
* version retained from a same-domain upstream repository (real AWS has no third {@code
* originType} value for this, confirmed against the live {@code PackageVersionOrigin} API
* reference, which lists only {@code INTERNAL}/{@code EXTERNAL}/{@code UNKNOWN}), the repository
* it was published to, as {@code upstreamRepositoryName}, however many upstreams it came
* through; for a true direct publish, neither is set.
*/
private record VersionOrigin(String originType, String externalConnectionName, String upstreamRepositoryName) {}
@@ -2808,9 +2834,9 @@ public class CodeArtifactService implements Resettable {
String namespace, String packageName, String version) {
return confirmedRetainedVersionOriginClaim(region, domain, owner, repository, format, namespace, packageName,
version)
.map(c -> c.originKind() == RetentionOriginKind.EXTERNAL_CONNECTION
? new VersionOrigin("EXTERNAL", c.originName(), null)
: new VersionOrigin("INTERNAL", null, c.originName()))
.map(c -> c.entryPoint().kind() == RetentionOriginKind.EXTERNAL_CONNECTION
? new VersionOrigin("EXTERNAL", c.entryPoint().name(), null)
: new VersionOrigin("INTERNAL", null, c.entryPoint().name()))
.orElse(new VersionOrigin("INTERNAL", null, null));
}
@@ -3473,15 +3499,18 @@ public class CodeArtifactService implements Resettable {
RetainedVersionOriginClaim existing = retainedVersionOriginConnections.get(key);
if (existing == null) {
long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet();
EntryPoint entryPoint = originKind == RetentionOriginKind.EXTERNAL_CONNECTION
? new EntryPoint(originKind, originName)
: entryPointThrough(owner, region, domain, originName, format, namespace, packageName, version);
retainedVersionOriginConnections.put(key,
new RetainedVersionOriginClaim(originName, originKind, 1, false, episodeId));
new RetainedVersionOriginClaim(originName, originKind, 1, false, episodeId, entryPoint));
return new RetainedVersionOriginClaimOutcome(true, episodeId);
}
if (!existing.originName().equals(originName) || existing.originKind() != originKind) {
return new RetainedVersionOriginClaimOutcome(false, 0L);
}
retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(originName, originKind,
existing.inFlightAttempts() + 1, existing.confirmed(), existing.episodeId()));
existing.inFlightAttempts() + 1, existing.confirmed(), existing.episodeId(), existing.entryPoint()));
return new RetainedVersionOriginClaimOutcome(true, existing.episodeId());
}
@@ -3527,8 +3556,15 @@ public class CodeArtifactService implements Resettable {
if (remaining == 0 && !confirmed) {
retainedVersionOriginConnections.remove(key);
} else {
// Read again as the claim is confirmed: the upstream's own claim may have been confirmed,
// or given up, since this one was taken.
EntryPoint entryPoint = confirmed && !existing.confirmed()
&& existing.originKind() == RetentionOriginKind.UPSTREAM_REPOSITORY
? entryPointThrough(owner, region, domain, existing.originName(), format, namespace, packageName,
version)
: existing.entryPoint();
retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(
existing.originName(), existing.originKind(), remaining, confirmed, episodeId));
existing.originName(), existing.originKind(), remaining, confirmed, episodeId, entryPoint));
}
}
@@ -4927,7 +4963,7 @@ public class CodeArtifactService implements Resettable {
}
long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet();
retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(sourceClaim.get().originName(),
sourceClaim.get().originKind(), 0, true, episodeId));
sourceClaim.get().originKind(), 0, true, episodeId, sourceClaim.get().entryPoint()));
}
/**
@@ -4947,8 +4983,10 @@ public class CodeArtifactService implements Resettable {
namespace, accountingPackageName(format, packageName),
normalizedContainerBackedVersion(format, version)));
long episodeId = retainedVersionOriginEpisodeCounter.incrementAndGet();
EntryPoint entryPoint = entryPointThrough(owner, region, domain, upstreamRepository, format, namespace,
packageName, version);
retainedVersionOriginConnections.put(key, new RetainedVersionOriginClaim(upstreamRepository,
RetentionOriginKind.UPSTREAM_REPOSITORY, 0, true, episodeId));
RetentionOriginKind.UPSTREAM_REPOSITORY, 0, true, episodeId, entryPoint));
}
/**
@@ -6299,8 +6337,8 @@ public class CodeArtifactService implements Resettable {
/**
* The priority-ordered, deduplicated, cycle-safe chain of repositories AWS searches when
* resolving a package-manager request against {@code repository}'s own {@code upstreams}
* (never including {@code repository} itself); see {@link UpstreamRepositoryResolver}'s own
* javadoc for why this is a breadth-first walk, not a depth-first one.
* (never including {@code repository} itself), depth-first in list order; see {@link
* UpstreamRepositoryResolver}'s own javadoc.
*/
List<String> resolveUpstreamSearchOrder(String region, String domain, String domainOwner, String repository) {
String owner = effectiveOwner(domainOwner);
@@ -0,0 +1,87 @@
package io.floci.aws.services.codeartifact;
import io.floci.aws.core.common.AwsException;
import java.util.Optional;
import java.util.function.Predicate;
/**
* The last leg of the upstream walk the four formats' upstream importers share: a version no
* upstream holds is fetched through the first upstream, in the search order, with an external
* connection, and retained there before it is retained in the requested repository, as the User
* Guide's chain example has it.
*/
final class UpstreamExternalConnectionFetch {
/**
* The upstream that fetched the version and the version it now holds there. Its sidecar is
* still in use for the caller, which ends that use once it has copied the version.
*/
record Fetched(String repository, String repoId, String version) {
}
/**
* Fetches through {@code candidate}'s external connection into its sidecar {@code
* candidateRepoId}: the version {@code candidate} now holds, or empty when the connection
* has nothing for the request.
*/
@FunctionalInterface
interface Fetch {
Optional<String> fetch(String candidate, String candidateRepoId);
}
private UpstreamExternalConnectionFetch() {
}
/**
* The first upstream of {@code repository}, in {@link
* CodeArtifactService#resolveUpstreamSearchOrder}'s order, that {@code hasExternalConnection}
* admits and that {@code fetch} gets the version through, still downloadable there: a version
* an upstream holds Archived or Disposed is skipped here as the walk over what the upstreams
* hold skips it, even when its external connection answers for it.
*/
static Optional<Fetched> firstFetched(CodeArtifactService service, RepositorySidecarManager sidecar,
String format, String region, String domain, String owner, String repository, String namespace,
String packageName, Predicate<String> hasExternalConnection, Fetch fetch) {
for (String candidate : service.resolveUpstreamSearchOrder(region, domain, owner, repository)) {
if (!hasExternalConnection.test(candidate)) {
continue;
}
String candidateRepoId;
try {
candidateRepoId = service.resolveContainerIdAndBeginUse(format, region, domain, owner, candidate,
sidecar);
} catch (AwsException e) {
// The upstream was deleted since the search order was read: nothing to fetch
// through it.
continue;
}
Optional<Fetched> fetched = Optional.empty();
try {
fetched = fetch.fetch(candidate, candidateRepoId)
.filter(version -> downloadable(service, owner, region, domain, candidate, format,
namespace, packageName, version, candidateRepoId))
.map(version -> new Fetched(candidate, candidateRepoId, version));
} finally {
if (fetched.isEmpty()) {
sidecar.endUse(candidateRepoId);
}
}
if (fetched.isPresent()) {
return fetched;
}
}
return Optional.empty();
}
private static boolean downloadable(CodeArtifactService service, String owner, String region, String domain,
String repository, String format, String namespace, String packageName, String version, String repoId) {
try {
service.requireContainerBackedVersionDownloadable(owner, region, domain, repository, format, namespace,
packageName, version, repoId);
return true;
} catch (AwsException e) {
return false;
}
}
}
@@ -4,33 +4,25 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
/**
* Flattens a repository's {@code upstreams} graph into the real order AWS searches it in when
* resolving a package-manager request: confirmed against the live "Upstream repository priority
* order" documentation, a repository's own direct upstreams are searched in the order they were
* configured, and that search is transitive (a direct upstream's own upstreams are searched too,
* region-wide quota page confirms as many as 25 repositories total in one resolution), not limited
* to the one repository's own direct list.
* Flattens a repository's {@code upstreams} graph into the order AWS searches it in when resolving a
* package-manager request. The User Guide's "Upstream repository priority order": a repository's
* upstreams are searched in the order they were listed, and "if an upstream repository has its own
* upstream repositories, the same logic is used to find a package version before moving to the next
* upstream repository". That is a depth-first walk in list order: its own example, {@code my_repo}
* with upstreams {@code A} and {@code B}, {@code A} with {@code C} and {@code D}, and {@code D} with
* {@code E}, is searched {@code my_repo, A, C, D, E, B}.
*
* <p>Breadth-first, not depth-first: AWS's own ordering guarantee is that a repository's direct
* upstreams are searched, in their configured order, before any of their own transitive upstreams.
* A depth-first walk would violate this the moment a closer sibling exists alongside a deeper
* match: given {@code A -> [B, C]} and {@code B -> [D]}, a depth-first walk would recurse into
* {@code B}'s own subtree before ever reaching {@code C} (a direct upstream of {@code A}),
* producing the search order {@code [B, D, C]} rather than the correct {@code [B, C, D]}: C, one
* hop away, searched after D, two hops away. Breadth-first expands one full level (a "frontier")
* at a time, so every direct upstream is always searched before any of their own upstreams,
* matching AWS's documented guarantee exactly.
*
* <p>Cycle-safe by construction: a repository is enqueued at most once (the {@code visited} set),
* so a cycle anywhere in the graph simply stops expanding rather than looping. {@code
* validateUpstreams} independently rejects a cycle at the point it would be introduced (see its
* own javadoc), but this walk does not rely on that validation having run, since an upstream list
* can only be validated against the graph as it existed at that moment, not against every later
* <p>Cycle-safe by construction: a repository is searched at most once (the {@code visited} set),
* where it is first reached, so a cycle anywhere in the graph simply stops expanding rather than
* looping. {@code validateUpstreams} independently rejects a cycle at the point it would be introduced
* (see its own javadoc), but this walk does not rely on that validation having run, since an upstream
* list can only be validated against the graph as it existed at that moment, not against every later
* edit to a different repository's own upstreams.
*/
final class UpstreamRepositoryResolver {
@@ -57,20 +49,22 @@ final class UpstreamRepositoryResolver {
List<String> order = new ArrayList<>();
Set<String> visited = new HashSet<>();
visited.add(startingRepository);
Deque<String> frontier = new ArrayDeque<>();
frontier.add(startingRepository);
while (!frontier.isEmpty() && order.size() < MAX_RESOLUTION_REPOSITORIES) {
String current = frontier.removeFirst();
for (String upstream : upstreamsOf.apply(current)) {
if (!visited.add(upstream)) {
continue;
}
order.add(upstream);
if (order.size() >= MAX_RESOLUTION_REPOSITORIES) {
break;
}
frontier.addLast(upstream);
// A stack of each repository's remaining upstreams: the top is the list being walked, so a
// repository's own upstreams are searched before the next of its siblings.
Deque<Iterator<String>> pending = new ArrayDeque<>();
pending.push(upstreamsOf.apply(startingRepository).iterator());
while (!pending.isEmpty() && order.size() < MAX_RESOLUTION_REPOSITORIES) {
Iterator<String> siblings = pending.peek();
if (!siblings.hasNext()) {
pending.pop();
continue;
}
String upstream = siblings.next();
if (!visited.add(upstream)) {
continue;
}
order.add(upstream);
pending.push(upstreamsOf.apply(upstream).iterator());
}
return order;
}
@@ -523,4 +523,14 @@ class CodeArtifactMavenExternalConnectionImporterTest {
"com/example/widget/1.0-SNAPSHOT/widget-1.0-20231001.123456-1.jar"));
verify(externalConnectionClient, never()).exists(anyString(), anyString());
}
/** An upstream deleted since a search order named it has no connection to fetch through. */
@Test
void aDeletedRepositoryHasNoExternalConnection() {
when(service.describeRepository(REGION, DOMAIN, OWNER, "deleted"))
.thenThrow(new AwsException("ResourceNotFoundException", "Repository 'deleted' not found.", 404));
assertFalse(importer.hasExternalConnection(REGION, DOMAIN, OWNER, "deleted"));
assertTrue(importer.hasExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY));
}
}
@@ -4,6 +4,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
@@ -22,8 +23,10 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -52,13 +55,15 @@ class CodeArtifactMavenUpstreamRepositoryImporterTest {
private CodeArtifactService service;
private ReposiliteSidecarClient reposilite;
private CodeArtifactMavenExternalConnectionImporter externalConnectionImporter;
private CodeArtifactMavenUpstreamRepositoryImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
reposilite = mock(ReposiliteSidecarClient.class);
importer = new CodeArtifactMavenUpstreamRepositoryImporter(service, reposilite);
externalConnectionImporter = mock(CodeArtifactMavenExternalConnectionImporter.class);
importer = new CodeArtifactMavenUpstreamRepositoryImporter(service, reposilite, externalConnectionImporter);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setUpstreams(List.of(UPSTREAM));
@@ -298,6 +303,98 @@ class CodeArtifactMavenUpstreamRepositoryImporterTest {
PACKAGE_NAME, VERSION, EPISODE_ID, false);
}
/**
* An artifact no upstream holds is fetched through an upstream's own external connection, retained
* there first, then retained here from that upstream.
*/
@Test
void anArtifactNoUpstreamHoldsIsFetchedThroughAnUpstreamsExternalConnection() {
when(reposilite.artifactExists(UPSTREAM_REPO_ID, GAV)).thenReturn(false);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, GAV))
.thenReturn(true);
stubFetchArtifact(UPSTREAM_REPO_ID, GAV, "jar-bytes".getBytes());
assertTrue(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV));
// The fences here are read before the fetch through the upstream's connection, so a deletion
// here during that fetch moves them away from the snapshot.
InOrder order = inOrder(service, externalConnectionImporter);
order.verify(service).currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "maven",
NAMESPACE, PACKAGE_NAME);
order.verify(service).currentContainerBackedVersionFence(REGION, DOMAIN, OWNER, REPOSITORY, "maven",
NAMESPACE, PACKAGE_NAME, VERSION);
order.verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, GAV);
order.verify(service).claimMavenRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, NAMESPACE,
PACKAGE_NAME, VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
// Leased once by the walk and once for the fetch through its connection, each released.
verify(service, times(2)).resolveContainerIdAndBeginUse("maven", REGION, DOMAIN, OWNER, UPSTREAM, reposilite);
verify(reposilite, times(2)).endUse(UPSTREAM_REPO_ID);
}
/**
* The upstream's connection answers for a version the upstream already holds, Archived: the walk
* over what the upstreams hold skipped it, and the fetch through the connection skips it too.
*/
@Test
void aVersionArchivedAtTheUpstreamIsNotCopiedThroughItsExternalConnection() {
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "maven", NAMESPACE,
PACKAGE_NAME, VERSION, UPSTREAM_REPO_ID);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, GAV))
.thenReturn(true);
assertFalse(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV));
verify(service, never()).claimMavenRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), any(), anyLong());
verify(reposilite, times(2)).endUse(UPSTREAM_REPO_ID);
}
/** A merge through the connection that fails leaves the upstream's own metadata to read. */
@Test
void aFailedMergeThroughAnUpstreamsExternalConnectionStillReadsItsOwnMetadata() {
String metadataGav = "com/example/widget/maven-metadata.xml";
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, metadataGav))
.thenThrow(new IllegalStateException("sidecar write failed"));
byte[] metadataBytes = METADATA_WITH_ONE_VERSION;
when(reposilite.fetchArtifactStreamed(UPSTREAM_REPO_ID, metadataGav)).thenAnswer(invocation ->
Optional.of(new ReposiliteSidecarClient.StreamedArtifact(
new ByteArrayInputStream(metadataBytes), metadataBytes.length, "text/xml")));
when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
eq(NAMESPACE), eq(PACKAGE_NAME), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(),
eq(true))).thenReturn(true);
assertTrue(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, metadataGav));
verify(reposilite).endUse(UPSTREAM_REPO_ID);
}
@Test
void anUpstreamWithoutAnExternalConnectionIsNotAskedToFetch() {
when(reposilite.artifactExists(UPSTREAM_REPO_ID, GAV)).thenReturn(false);
assertFalse(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, GAV));
verify(externalConnectionImporter, never()).tryImport(anyString(), anyString(), anyString(), anyString(),
anyString(), anyString());
}
@Test
void anUpstreamsExternalConnectionMergesItsReleasesIntoTheMetadataReadThroughIt() {
String metadataGav = "com/example/widget/maven-metadata.xml";
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
byte[] metadataBytes = METADATA_WITH_ONE_VERSION;
when(reposilite.fetchArtifactStreamed(UPSTREAM_REPO_ID, metadataGav)).thenAnswer(invocation ->
Optional.of(new ReposiliteSidecarClient.StreamedArtifact(
new ByteArrayInputStream(metadataBytes), metadataBytes.length, "text/xml")));
when(service.mergeMavenMetadataUnderPackageFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY),
eq(NAMESPACE), eq(PACKAGE_NAME), eq(42L), eq(reposilite), eq(REPO_ID), eq(metadataBytes), any(),
eq(true))).thenReturn(true);
assertTrue(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, metadataGav));
verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID,
metadataGav);
}
/** Names at least one real version, so the eligibility pre-check lets this candidate through. */
private static final byte[] METADATA_WITH_ONE_VERSION = ("<metadata><versioning><versions>"
+ "<version>1.0</version></versions></versioning></metadata>").getBytes();
@@ -651,4 +651,14 @@ class CodeArtifactNpmExternalConnectionImporterTest {
return Optional.of(new NpmExternalConnectionClient.FetchedFile(content.length));
});
}
/** An upstream deleted since a search order named it has no connection to fetch through. */
@Test
void aDeletedRepositoryHasNoExternalConnection() {
when(service.describeRepository(REGION, DOMAIN, OWNER, "deleted"))
.thenThrow(new AwsException("ResourceNotFoundException", "Repository 'deleted' not found.", 404));
assertFalse(importer.hasExternalConnection(REGION, DOMAIN, OWNER, "deleted"));
assertTrue(importer.hasExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY));
}
}
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
@@ -23,8 +24,10 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -53,13 +56,16 @@ class CodeArtifactNpmUpstreamRepositoryImporterTest {
private CodeArtifactService service;
private VerdaccioSidecarClient verdaccio;
private CodeArtifactNpmExternalConnectionImporter externalConnectionImporter;
private CodeArtifactNpmUpstreamRepositoryImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
verdaccio = mock(VerdaccioSidecarClient.class);
importer = new CodeArtifactNpmUpstreamRepositoryImporter(service, verdaccio, new ObjectMapper());
externalConnectionImporter = mock(CodeArtifactNpmExternalConnectionImporter.class);
importer = new CodeArtifactNpmUpstreamRepositoryImporter(service, verdaccio, new ObjectMapper(),
externalConnectionImporter);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setUpstreams(List.of(UPSTREAM));
@@ -306,7 +312,7 @@ class CodeArtifactNpmUpstreamRepositoryImporterTest {
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME);
PACKAGE_NAME, false);
assertTrue(merged.isPresent());
JsonNode versionDoc = merged.get().path("versions").path(VERSION);
@@ -316,6 +322,93 @@ class CodeArtifactNpmUpstreamRepositoryImporterTest {
verify(verdaccio).endUse(UPSTREAM_REPO_ID);
}
/**
* A version no upstream holds is fetched through an upstream's own external connection, retained
* there first, then retained here from that upstream, as the User Guide's chain example has it.
*/
@Test
void aVersionNoUpstreamHoldsIsFetchedThroughAnUpstreamsExternalConnection() {
when(verdaccio.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION))
.thenReturn(false);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImportAsset(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, null,
PACKAGE_NAME, VERSION, ASSET_NAME)).thenReturn(true);
when(verdaccio.fetchPackageDocument(UPSTREAM_BASE_URL, null, PACKAGE_NAME))
.thenReturn(Optional.of(upstreamDocument("")));
byte[] tarballBytes = "tarball-content".getBytes();
when(verdaccio.fetchPackageVersionAssetStreamed(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME,
VERSION, ASSET_NAME)).thenAnswer(invocation -> Optional.of(new RepositorySidecarManager.StreamedAsset(
new ByteArrayInputStream(tarballBytes), tarballBytes.length)));
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME);
assertTrue(imported);
// The fences here are read before the fetch through the upstream's connection, so a deletion
// here during that fetch moves them away from the snapshot.
InOrder order = inOrder(service, externalConnectionImporter);
order.verify(service).currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME);
order.verify(service).currentContainerBackedVersionFence(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION);
order.verify(externalConnectionImporter).tryImportAsset(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID,
null, PACKAGE_NAME, VERSION, ASSET_NAME);
order.verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "npm", null,
PACKAGE_NAME, VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
// Leased once by the walk and once for the fetch through its connection, each released.
verify(service, times(2)).resolveContainerIdAndBeginUse("npm", REGION, DOMAIN, OWNER, UPSTREAM, verdaccio);
verify(verdaccio, times(2)).endUse(UPSTREAM_REPO_ID);
}
/**
* The upstream's connection answers for a version the upstream already holds, Archived: the walk
* over what the upstreams hold skipped it, and the fetch through the connection skips it too.
*/
@Test
void aVersionArchivedAtTheUpstreamIsNotCopiedThroughItsExternalConnection() {
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "npm", null, PACKAGE_NAME,
VERSION, UPSTREAM_REPO_ID);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImportAsset(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, null,
PACKAGE_NAME, VERSION, ASSET_NAME)).thenReturn(true);
assertFalse(importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME));
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
verify(verdaccio, times(2)).endUse(UPSTREAM_REPO_ID);
}
@Test
void anUpstreamWithoutAnExternalConnectionIsNotAskedToFetch() {
when(verdaccio.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME, VERSION))
.thenReturn(false);
assertFalse(importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null, PACKAGE_NAME,
VERSION, ASSET_NAME));
verify(externalConnectionImporter, never()).tryImportAsset(anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString(), anyString(), anyString());
}
/** The client's ask for the full document goes on to the upstream's connection, readme and all. */
@Test
void mergedPackumentOffersWhatAnUpstreamsExternalConnectionHas() {
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.mergedPackument(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, null,
PACKAGE_NAME, true)).thenReturn(Optional.of((ObjectNode) upstreamDocument("the readme")));
when(verdaccio.fetchPackageDocument(BASE_URL, null, PACKAGE_NAME)).thenReturn(Optional.empty());
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME, true);
assertTrue(merged.isPresent());
assertEquals(BASE_URL + PACKAGE_NAME + "/-/" + ASSET_NAME,
merged.get().path("versions").path(VERSION).path("dist").path("tarball").asText());
assertEquals("the readme", merged.get().path("readme").asText());
verify(verdaccio, never()).fetchPackageDocument(UPSTREAM_BASE_URL, null, PACKAGE_NAME);
}
@Test
void mergedPackumentReturnsEmptyWhenNoUpstreamsAreConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
@@ -323,7 +416,7 @@ class CodeArtifactNpmUpstreamRepositoryImporterTest {
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
Optional<ObjectNode> merged = importer.mergedPackument(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, null,
PACKAGE_NAME);
PACKAGE_NAME, false);
assertFalse(merged.isPresent());
}
@@ -1,5 +1,6 @@
package io.floci.aws.services.codeartifact;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import io.floci.aws.services.codeartifact.model.ExternalConnection;
import org.junit.jupiter.api.BeforeEach;
@@ -241,4 +242,14 @@ class CodeArtifactNuGetExternalConnectionImporterTest {
return Optional.of(new NuGetExternalConnectionClient.FetchedFile(content.length));
});
}
/** An upstream deleted since a search order named it has no connection to fetch through. */
@Test
void aDeletedRepositoryHasNoExternalConnection() {
when(service.describeRepository(REGION, DOMAIN, OWNER, "deleted"))
.thenThrow(new AwsException("ResourceNotFoundException", "Repository 'deleted' not found.", 404));
assertFalse(importer.hasExternalConnection(REGION, DOMAIN, OWNER, "deleted"));
assertTrue(importer.hasExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY));
}
}
@@ -4,6 +4,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
@@ -20,8 +21,10 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -50,13 +53,15 @@ class CodeArtifactNuGetUpstreamRepositoryImporterTest {
private CodeArtifactService service;
private BagetterSidecarClient bagetter;
private CodeArtifactNuGetExternalConnectionImporter externalConnectionImporter;
private CodeArtifactNuGetUpstreamRepositoryImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
bagetter = mock(BagetterSidecarClient.class);
importer = new CodeArtifactNuGetUpstreamRepositoryImporter(service, bagetter);
externalConnectionImporter = mock(CodeArtifactNuGetExternalConnectionImporter.class);
importer = new CodeArtifactNuGetUpstreamRepositoryImporter(service, bagetter, externalConnectionImporter);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setUpstreams(List.of(UPSTREAM));
@@ -94,6 +99,64 @@ class CodeArtifactNuGetUpstreamRepositoryImporterTest {
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
}
/**
* A version no upstream holds is fetched through an upstream's own external connection, retained
* there first, then retained here from that upstream.
*/
@Test
void aVersionNoUpstreamHoldsIsFetchedThroughAnUpstreamsExternalConnection() {
when(bagetter.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_ID, VERSION))
.thenReturn(false);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, PACKAGE_ID,
VERSION)).thenReturn(true);
assertTrue(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION));
// The fences here are read before the fetch through the upstream's connection, so a deletion
// here during that fetch moves them away from the snapshot.
InOrder order = inOrder(service, externalConnectionImporter);
order.verify(service).currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID);
order.verify(service).currentContainerBackedVersionFence(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION);
order.verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID,
PACKAGE_ID, VERSION);
order.verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "nuget", null,
PACKAGE_ID, VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
// Leased once by the walk and once for the fetch through its connection, each released.
verify(service, times(2)).resolveContainerIdAndBeginUse("nuget", REGION, DOMAIN, OWNER, UPSTREAM, bagetter);
verify(bagetter, times(2)).endUse(UPSTREAM_REPO_ID);
}
/**
* The upstream's connection answers for a version the upstream already holds, Archived: the walk
* over what the upstreams hold skipped it, and the fetch through the connection skips it too.
*/
@Test
void aVersionArchivedAtTheUpstreamIsNotCopiedThroughItsExternalConnection() {
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "nuget", null, PACKAGE_ID,
VERSION, UPSTREAM_REPO_ID);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImport(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, PACKAGE_ID,
VERSION)).thenReturn(true);
assertFalse(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION));
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
verify(bagetter, times(2)).endUse(UPSTREAM_REPO_ID);
}
@Test
void anUpstreamWithoutAnExternalConnectionIsNotAskedToFetch() {
when(bagetter.packageVersionExists(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_ID, VERSION))
.thenReturn(false);
assertFalse(importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION));
verify(externalConnectionImporter, never()).tryImport(anyString(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString());
}
@Test
void importsFromTheDirectUpstreamWhenNotFoundLocally() {
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_ID, VERSION);
@@ -370,6 +370,16 @@ class CodeArtifactPypiExternalConnectionImporterTest {
assertEquals(List.of(), additional);
}
/** A downstream repository listing these files through its upstreams leaves out what it refuses. */
@Test
void additionalExternalFilenamesLeavesOutAVersionTheCallerRefuses() {
List<CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile> additional =
importer.additionalExternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME,
Set.of(), version -> !VERSION.equals(version));
assertEquals(List.of(), additional);
}
@Test
void additionalExternalFilenamesReturnsEmptyWhenNoConnectionIsConfigured() {
CodeArtifactRepository repository = new CodeArtifactRepository();
@@ -617,4 +627,14 @@ class CodeArtifactPypiExternalConnectionImporterTest {
}
return toBytes(root);
}
/** An upstream deleted since a search order named it has no connection to fetch through. */
@Test
void aDeletedRepositoryHasNoExternalConnection() {
when(service.describeRepository(REGION, DOMAIN, OWNER, "deleted"))
.thenThrow(new AwsException("ResourceNotFoundException", "Repository 'deleted' not found.", 404));
assertFalse(importer.hasExternalConnection(REGION, DOMAIN, OWNER, "deleted"));
assertTrue(importer.hasExternalConnection(REGION, DOMAIN, OWNER, REPOSITORY));
}
}
@@ -4,6 +4,8 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
@@ -12,7 +14,9 @@ import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -21,8 +25,10 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -50,13 +56,15 @@ class CodeArtifactPypiUpstreamRepositoryImporterTest {
private CodeArtifactService service;
private PypiserverSidecarClient pypiserver;
private CodeArtifactPypiExternalConnectionImporter externalConnectionImporter;
private CodeArtifactPypiUpstreamRepositoryImporter importer;
@BeforeEach
void setUp() {
service = mock(CodeArtifactService.class);
pypiserver = mock(PypiserverSidecarClient.class);
importer = new CodeArtifactPypiUpstreamRepositoryImporter(service, pypiserver);
externalConnectionImporter = mock(CodeArtifactPypiExternalConnectionImporter.class);
importer = new CodeArtifactPypiUpstreamRepositoryImporter(service, pypiserver, externalConnectionImporter);
CodeArtifactRepository repository = new CodeArtifactRepository();
repository.setUpstreams(List.of(UPSTREAM));
@@ -97,6 +105,100 @@ class CodeArtifactPypiUpstreamRepositoryImporterTest {
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
}
/**
* A file no upstream holds is fetched through an upstream's own external connection, retained
* there first, then retained here from that upstream.
*/
@Test
void aFileNoUpstreamHoldsIsFetchedThroughAnUpstreamsExternalConnection() {
// Nothing listed at the upstream until its external connection has fetched the version.
when(pypiserver.listPackageVersions(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME))
.thenReturn(List.of())
.thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp(VERSION,
Instant.ofEpochSecond(1000))));
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImportAsset(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, FILENAME))
.thenReturn(true);
assertTrue(importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME));
// The package fence here is read before the fetch through the upstream's connection, so a
// DeletePackage here during that fetch moves it away from the snapshot.
InOrder order = inOrder(service, externalConnectionImporter);
order.verify(service).currentContainerBackedPackageFence(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME);
order.verify(externalConnectionImporter).tryImportAsset(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID,
FILENAME);
order.verify(service).claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "pypi", null,
PACKAGE_NAME, VERSION, UPSTREAM, RetentionOriginKind.UPSTREAM_REPOSITORY, 42L);
// Leased once by the walk and once for the fetch through its connection, each released.
verify(service, times(2)).resolveContainerIdAndBeginUse("pypi", REGION, DOMAIN, OWNER, UPSTREAM, pypiserver);
verify(pypiserver, times(2)).endUse(UPSTREAM_REPO_ID);
}
/**
* The upstream's connection answers for a version the upstream already holds, Archived: the walk
* over what the upstreams hold skipped it, and the fetch through the connection skips it too.
*/
@Test
void aVersionArchivedAtTheUpstreamIsNotCopiedThroughItsExternalConnection() {
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, UPSTREAM, "pypi", null, PACKAGE_NAME,
VERSION, UPSTREAM_REPO_ID);
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
when(externalConnectionImporter.tryImportAsset(REGION, DOMAIN, OWNER, UPSTREAM, UPSTREAM_REPO_ID, FILENAME))
.thenReturn(true);
assertFalse(importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME));
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
anyString(), any(), anyString(), anyString(), anyString(), any(), anyLong());
verify(pypiserver, times(2)).endUse(UPSTREAM_REPO_ID);
}
@Test
void anUpstreamWithoutAnExternalConnectionIsNotAskedToFetch() {
when(pypiserver.listPackageVersions(UPSTREAM_REPO_ID, DOMAIN, UPSTREAM, null, PACKAGE_NAME))
.thenReturn(List.of());
assertFalse(importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME));
verify(externalConnectionImporter, never()).tryImportAsset(anyString(), anyString(), anyString(),
anyString(), anyString(), anyString());
}
@Test
void additionalInternalFilenamesOffersWhatAnUpstreamsExternalConnectionHas() {
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
String publicOnly = "widget-2.0.0.tar.gz";
when(externalConnectionImporter.additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER), eq(UPSTREAM),
eq(UPSTREAM_REPO_ID), eq(PACKAGE_NAME), eq(Set.of(FILENAME)), any())).thenReturn(List.of(
new CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile(publicOnly, false, null)));
List<String> offered = importer.additionalInternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID,
PACKAGE_NAME, Set.of()).stream()
.map(CodeArtifactPypiExternalConnectionImporter.ExternalIndexFile::filename).toList();
assertEquals(List.of(FILENAME, publicOnly), offered);
}
/**
* A version this repository marked Archived or Disposed is left out of what an upstream's external
* connection offers here, as it is left out of what the upstream itself holds.
*/
@Test
void additionalInternalFilenamesLeavesOutAVersionArchivedHereFromAnUpstreamsExternalConnection() {
when(externalConnectionImporter.hasExternalConnection(REGION, DOMAIN, OWNER, UPSTREAM)).thenReturn(true);
doThrow(new AwsException("ResourceNotFoundException", "archived", 404)).when(service)
.requireContainerBackedVersionDownloadable(OWNER, REGION, DOMAIN, REPOSITORY, "pypi", null,
PACKAGE_NAME, "2.0.0", REPO_ID);
importer.additionalInternalFilenames(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, Set.of());
ArgumentCaptor<Predicate<String>> listable = ArgumentCaptor.forClass(Predicate.class);
verify(externalConnectionImporter).additionalExternalFilenames(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(UPSTREAM), eq(UPSTREAM_REPO_ID), eq(PACKAGE_NAME), any(), listable.capture());
assertFalse(listable.getValue().test("2.0.0"));
assertTrue(listable.getValue().test(VERSION));
}
@Test
void importsFromTheDirectUpstreamWhenNotFoundLocally() {
boolean imported = importer.tryImportAsset(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, FILENAME);
@@ -2639,6 +2639,117 @@ class CodeArtifactServiceTest {
"repo", "maven", "com.example", "widget", "1.0"));
}
/** Retains npm {@code widget@1.0} into {@code repository} from {@code origin}, a connection or a repository. */
private void retainNpmWidget(String repository, String origin, RetentionOriginKind kind) {
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, repository, "npm", null,
"widget");
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(REGION,
"dom", null, repository, "npm", null, "widget", "1.0", origin, kind, fence);
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, repository, "npm", null, "widget", "1.0",
claim.episodeId(), true);
}
private CodeArtifactService.PackageVersionSummary listedNpmWidget(String repository) {
when(verdaccioClient.listPackageVersions(anyString(), eq("dom"), eq(repository), isNull(), eq("widget")))
.thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0",
Instant.ofEpochSecond(1000))));
return service.listPackageVersions(REGION, "dom", null, repository, "npm", null, "widget", null, null, null,
null, null).versions().get(0);
}
/**
* A version's origin names where it "originally entered" the domain: one retained through an
* upstream that had itself retained it from a repository further up names that repository, not
* the upstream it was read through.
*/
@Test
void aVersionRetainedThroughAnIntermediateUpstreamNamesTheRepositoryItWasPublishedTo() {
service.createDomain(REGION, "dom", null, Map.of());
for (String repository : List.of("origin", "mid", "repo")) {
service.createRepository(REGION, "dom", null, repository, null, null, Map.of());
}
retainNpmWidget("mid", "origin", RetentionOriginKind.UPSTREAM_REPOSITORY);
retainNpmWidget("repo", "mid", RetentionOriginKind.UPSTREAM_REPOSITORY);
CodeArtifactService.PackageVersionSummary summary = listedNpmWidget("repo");
assertEquals("INTERNAL", summary.originType());
assertEquals("origin", summary.upstreamRepositoryName());
assertEquals(null, summary.externalConnectionName());
assertEquals("origin", listedNpmWidget("mid").upstreamRepositoryName());
}
/** One an upstream fetched through its external connection entered the domain there, so it is EXTERNAL. */
@Test
void aVersionRetainedThroughAnUpstreamThatFetchedItExternallyIsExternal() {
service.createDomain(REGION, "dom", null, Map.of());
for (String repository : List.of("up", "repo")) {
service.createRepository(REGION, "dom", null, repository, null, null, Map.of());
}
retainNpmWidget("up", "public:npmjs", RetentionOriginKind.EXTERNAL_CONNECTION);
retainNpmWidget("repo", "up", RetentionOriginKind.UPSTREAM_REPOSITORY);
CodeArtifactService.PackageVersionSummary summary = listedNpmWidget("repo");
assertEquals("EXTERNAL", summary.originType());
assertEquals("public:npmjs", summary.externalConnectionName());
assertEquals(null, summary.upstreamRepositoryName());
assertEquals(Optional.of("up"), service.retainedUpstreamRepositoryOrigin(REGION, "dom", null, "repo", "npm",
null, "widget", "1.0"));
}
/**
* The upstream has written what it fetched through its connection but not yet confirmed it when
* the copy here is claimed and confirmed: the copy is still the one that entered the domain
* through that connection, and stays so once the upstream confirms.
*/
@Test
void aVersionCopiedWhileTheUpstreamsExternalFetchIsUnconfirmedIsExternal() {
service.createDomain(REGION, "dom", null, Map.of());
for (String repository : List.of("up", "repo")) {
service.createRepository(REGION, "dom", null, repository, null, null, Map.of());
}
long upFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "up", "npm", null, "widget");
CodeArtifactService.RetainedVersionOriginClaimOutcome upClaim = service.claimRetainedVersionOrigin(REGION,
"dom", null, "up", "npm", null, "widget", "1.0", "public:npmjs",
RetentionOriginKind.EXTERNAL_CONNECTION, upFence);
retainNpmWidget("repo", "up", RetentionOriginKind.UPSTREAM_REPOSITORY);
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "up", "npm", null, "widget", "1.0",
upClaim.episodeId(), true);
CodeArtifactService.PackageVersionSummary summary = listedNpmWidget("repo");
assertEquals("EXTERNAL", summary.originType());
assertEquals("public:npmjs", summary.externalConnectionName());
}
/**
* The upstream's attempt gives its claim up after the copy here was claimed, the upstream's own
* copy having been published there: confirmed, the copy here names the upstream it came from.
*/
@Test
void aCopyConfirmedAfterTheUpstreamGaveItsClaimUpNamesTheUpstream() {
service.createDomain(REGION, "dom", null, Map.of());
for (String repository : List.of("up", "repo")) {
service.createRepository(REGION, "dom", null, repository, null, null, Map.of());
}
long upFence = service.currentContainerBackedPackageFence(REGION, "dom", null, "up", "npm", null, "widget");
CodeArtifactService.RetainedVersionOriginClaimOutcome upClaim = service.claimRetainedVersionOrigin(REGION,
"dom", null, "up", "npm", null, "widget", "1.0", "public:npmjs",
RetentionOriginKind.EXTERNAL_CONNECTION, upFence);
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", null, "widget");
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(REGION,
"dom", null, "repo", "npm", null, "widget", "1.0", "up", RetentionOriginKind.UPSTREAM_REPOSITORY,
fence);
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "up", "npm", null, "widget", "1.0",
upClaim.episodeId(), false);
service.finishRetainedVersionOriginAttempt(REGION, "dom", null, "repo", "npm", null, "widget", "1.0",
claim.episodeId(), true);
CodeArtifactService.PackageVersionSummary summary = listedNpmWidget("repo");
assertEquals("INTERNAL", summary.originType());
assertEquals("up", summary.upstreamRepositoryName());
}
/**
* {@code originType} stays {@code "INTERNAL"} for a same-domain upstream-repository retention
* (real AWS's own {@code PackageVersionOrigin.originType} has no third value for this), with
@@ -11,24 +11,26 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@code resolveSearchOrder}'s own javadoc works through the exact A/B/C/D counterexample this
* test locks in: a depth-first walk would wrongly search a 2-hop match before a 1-hop sibling.
* {@code resolveSearchOrder} walks the upstream graph the way the User Guide's "Upstream repository
* priority order" example does: depth-first, in each repository's listed order.
*/
class UpstreamRepositoryResolverTest {
@Test
void directUpstreamsAreSearchedBeforeAnyOfTheirOwnTransitiveUpstreams() {
// A -> [B, C], B -> [D]. A depth-first walk reaches D (via B) before C, a direct upstream
// of A; the correct, breadth-first order is B, C (both direct), then D.
void theUserGuidesExampleIsSearchedDepthFirstInListOrder() {
// "Upstream repository priority order": my_repo -> [A, B], A -> [C, D], D -> [E] is
// searched my_repo, A, C, D, E, B.
Map<String, List<String>> upstreams = Map.of(
"A", List.of("B", "C"),
"B", List.of("D"),
"my_repo", List.of("A", "B"),
"A", List.of("C", "D"),
"B", List.of(),
"C", List.of(),
"D", List.of());
"D", List.of("E"),
"E", List.of());
List<String> order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get);
List<String> order = UpstreamRepositoryResolver.resolveSearchOrder("my_repo", upstreams::get);
assertEquals(List.of("B", "C", "D"), order);
assertEquals(List.of("A", "C", "D", "E", "B"), order);
}
@Test
@@ -57,7 +59,7 @@ class UpstreamRepositoryResolverTest {
@Test
void aRepositoryReachableThroughTwoPathsAppearsExactlyOnce() {
// A -> [B, C], B -> [D], C -> [D]: D is reachable from both B and C, but must only be
// searched once, at the position its first discovery (through B) places it.
// searched once, where it is first reached, through B.
Map<String, List<String>> upstreams = Map.of(
"A", List.of("B", "C"),
"B", List.of("D"),
@@ -66,7 +68,7 @@ class UpstreamRepositoryResolverTest {
List<String> order = UpstreamRepositoryResolver.resolveSearchOrder("A", upstreams::get);
assertEquals(List.of("B", "C", "D"), order);
assertEquals(List.of("B", "D", "C"), order);
}
@Test