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

@@ -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;
}