Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(codeartifact): add DeletePackageVersions for every format (#6559)

Priamo Germosen5c7c84374b44
diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md
index 892883073a..b3bfa9eb00 100644
--- a/docs/services/codeartifact.md
+++ b/docs/services/codeartifact.md
@@ -50,6 +50,7 @@ behind them yet.
| `CopyPackageVersions` | Copies one or more versions of a package from one repository to another in the same domain. |
| `UpdatePackageVersionsStatus` | Moves one or more versions of a package to `Published`, `Unlisted`, or `Archived`; all-or-nothing per call, with `versionRevisions`/`expectedStatus` as optional preconditions. |
| `DisposePackageVersions` | Permanently deletes a package version's assets and sets its status to `Disposed`; irreversible, and shares `UpdatePackageVersionsStatus`'s all-or-nothing batch semantics. |
+| `DeletePackageVersions` | Permanently removes one or more versions of a package, real assets included; unlike `DisposePackageVersions`, leaves no trace, the freed coordinates can be freely republished, and it is the one action allowed on an already-`Disposed` version. |
| `TagResource` | Adds or updates tags on a domain or repository ARN. |
| `UntagResource` | Removes tags by key from a domain or repository ARN. |
| `ListTagsForResource` | Lists the tags on a domain or repository ARN. |
@@ -256,12 +257,12 @@ state.
that is not the caller's own account looks up that account's domain/repository with no
trust-policy or permissions-policy enforcement, consistent with Floci's IAM enforcement being
opt-in elsewhere, but worth knowing if you rely on domain-sharing semantics.
-- **`ListPackages` and `DeletePackageVersions` aren't implemented.** Every other package-version
- lifecycle action is: a version can be moved to `Unlisted`/`Archived`/`Published` with
- `UpdatePackageVersionsStatus`, or to `Disposed` (assets permanently deleted) with
- `DisposePackageVersions`. The only way to move a version out of `Unfinished` today is still
- either a follow-up `PublishPackageVersion` call that omits the `unfinished` flag, or
- `UpdatePackageVersionsStatus` itself.
+- **`ListPackages` isn't implemented.** Every package-version lifecycle action now is: a version
+ can be moved to `Unlisted`/`Archived`/`Published` with `UpdatePackageVersionsStatus`, to
+ `Disposed` (assets permanently deleted) with `DisposePackageVersions`, or removed outright,
+ from every status including `Disposed`, with `DeletePackageVersions`. The only way to move a
+ version out of `Unfinished` today is still either a follow-up `PublishPackageVersion` call that
+ omits the `unfinished` flag, or `UpdatePackageVersionsStatus` itself.
- **A container-backed (`maven`/`npm`/`pypi`/`nuget`) version's status override does not survive a
Floci restart.** It's kept in memory only, for the same reason the byte-count and readme
bookkeeping those formats already need are: the sidecar content it describes doesn't survive a
diff --git a/docs/services/index.md b/docs/services/index.md
index 38b6f3d92c..033e5ad214 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -124,7 +124,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS Backup](backup.md) | `/backup-vaults/*`, `/logically-air-gapped-backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 35 |
| [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 |
| [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 |
-| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 35 |
+| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 36 |
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 |
| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 27 |
| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 |
diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java
index 83ba89248c..f5e5b61669 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java
@@ -575,6 +575,28 @@ public class CodeArtifactController {
return ok(packageVersionStatusChangeResponse(result));
}
+ /**
+ * Unlike {@link #updatePackageVersionsStatus}/{@link #disposePackageVersions}, the real
+ * {@code DeletePackageVersionsRequest} has no {@code versionRevisions} member at all
+ * (confirmed against the wire model, see {@code CodeArtifactService#deletePackageVersions}'s
+ * own javadoc), so nothing here reads one.
+ */
+ @POST
+ @Path("/v1/package/versions/delete")
+ public Response deletePackageVersions(@Context HttpHeaders headers, @QueryParam("domain") String domain,
+ @QueryParam("domain-owner") String domainOwner,
+ @QueryParam("repository") String repository,
+ @QueryParam("format") String format,
+ @QueryParam("namespace") String namespace,
+ @QueryParam("package") String packageName, String body) {
+ JsonNode req = readTree(body);
+ String region = regionResolver.resolveRegion(headers);
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(region, domain,
+ domainOwner, repository, format, namespace, packageName,
+ readStringArray(req.get("versions"), "versions"), req.path("expectedStatus").asText(null));
+ return ok(packageVersionStatusChangeResponse(result));
+ }
+
private ObjectNode packageVersionStatusChangeResponse(CodeArtifactService.PackageVersionStatusChangeResult
result) {
ObjectNode response = objectMapper.createObjectNode();
diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDataPlane.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDataPlane.java
index 69053f80ec..b3b374c8d7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDataPlane.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactNpmDataPlane.java
@@ -341,6 +341,21 @@ public class CodeArtifactNpmDataPlane {
scope.region(), npmRequest.domain(), scope.owner(),
npmRequest.repository(), "npm", check.identity().namespace(),
check.identity().packageName());
+ // One snapshot per version in this envelope, narrower
+ // than fenceSnapshot above: raised by Greptile's review,
+ // a version DeletePackageVersions removes while this
+ // same callback is still in flight for it must not have
+ // its readme resurrected, something the package-wide
+ // fenceSnapshot alone (unaffected by a single version's
+ // own deletion) cannot catch.
+ Map<String, Long> readmeFenceSnapshots = new HashMap<>();
+ check.readmeByVersion().keySet().forEach(version ->
+ readmeFenceSnapshots.put(version,
+ service.currentContainerBackedVersionFence(
+ scope.region(), npmRequest.domain(),
+ scope.owner(), npmRequest.repository(), "npm",
+ check.identity().namespace(),
+ check.identity().packageName(), version)));
vertx.fileSystem().open(path, new OpenOptions().setRead(true))
.onComplete(reopened -> {
if (reopened.failed()) {
@@ -356,7 +371,7 @@ public class CodeArtifactNpmDataPlane {
reopened.result(), scope, npmRequest.domain(),
npmRequest.repository(), check.identity(),
check.totalAttachmentBytes(), fenceSnapshot,
- check.readmeByVersion(),
+ check.readmeByVersion(), readmeFenceSnapshots,
check.beforeRevisionByVersion());
});
});
@@ -673,7 +688,11 @@ public class CodeArtifactNpmDataPlane {
* when the envelope couldn't be parsed (see {@link #checkRepublish}), so both become no-ops
* in that case regardless of what Verdaccio answers. {@code fenceSnapshot} is whatever
* {@link CodeArtifactService#currentContainerBackedPackageFence} returned at the caller's own
- * earlier snapshot point, before this request was ever forwarded.
+ * earlier snapshot point, before this request was ever forwarded; {@code readmeFenceSnapshots}
+ * is the same idea, one entry per version in {@code readmeByVersion}, from {@link
+ * CodeArtifactService#currentContainerBackedVersionFence} instead, so a single version's own
+ * {@code DeletePackageVersions} in between can invalidate just that version's readme capture
+ * without the whole-package {@code fenceSnapshot} needing to change.
*
* <p>All of this bookkeeping runs in one {@code executeBlocking} call, and the response is
* only piped to the client once that call completes, not before: a client that requests this
@@ -683,7 +702,8 @@ public class CodeArtifactNpmDataPlane {
private void forwardSpooled(RoutingContext context, String backendBaseUrl, String backendPath,
ReadStream<Buffer> body, AuthorizationTokenScope scope, String domain, String repository,
PackageIdentity identity, long totalAttachmentBytes, long fenceSnapshot,
- Map<String, String> readmeByVersion, Map<String, String> beforeRevisionByVersion) {
+ Map<String, String> readmeByVersion, Map<String, Long> readmeFenceSnapshots,
+ Map<String, String> beforeRevisionByVersion) {
URI backend = URI.create(backendBaseUrl);
RequestOptions options = new RequestOptions()
.setHost(backend.getHost())
@@ -740,7 +760,8 @@ public class CodeArtifactNpmDataPlane {
readmeByVersion.forEach((version, readme) ->
service.recordPublishedPackageVersionReadme(scope.region(), domain,
scope.owner(), repository, "npm", identity.namespace(),
- identity.packageName(), version, readme, fenceSnapshot));
+ identity.packageName(), version, readme,
+ readmeFenceSnapshots.get(version)));
// Found by Qodo review: readmeByVersion's own keys are every version in
// this publish envelope, independent of whether any of them actually
// carried a readme, so reusing it here clears a stale Archived/Disposed
diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiController.java
index 4d3fff686e..e8acacd91e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactPypiController.java
@@ -238,6 +238,13 @@ public class CodeArtifactPypiController {
// order matters.
long fenceSnapshot = service.currentContainerBackedPackageFence(handle.region(), domain, handle.owner(),
repository, "pypi", null, packageName);
+ // Narrower than fenceSnapshot above, for the readme capture below specifically: raised
+ // by Greptile's review, a DeletePackageVersions for this exact version landing while
+ // this upload is in flight must invalidate just this version's own readme capture,
+ // which the package-wide fenceSnapshot alone would not catch.
+ long readmeFenceSnapshot = version == null || version.isBlank() ? 0L
+ : service.currentContainerBackedVersionFence(handle.region(), domain, handle.owner(),
+ repository, "pypi", null, packageName, version);
Response response = forwardUpload(handle.baseUrl(), contentType, content);
boolean uploadSucceeded = response.getStatus() == 200 || response.getStatus() == 201;
if (uploadSucceeded) {
@@ -264,7 +271,7 @@ public class CodeArtifactPypiController {
// version coordinate to record the readme against.
if (uploadSucceeded && version != null && !version.isBlank()) {
service.recordPublishedPackageVersionReadme(handle.region(), domain, handle.owner(), repository,
- "pypi", null, packageName, version, form.fields().get("description"), fenceSnapshot);
+ "pypi", null, packageName, version, form.fields().get("description"), readmeFenceSnapshot);
}
return response;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java
index 406ebb49ee..c8a6aa0f2f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java
@@ -193,6 +193,11 @@ public class CodeArtifactService implements Resettable {
// currentContainerBackedPackageFence's own javadoc for what this protects against.
private final ConcurrentHashMap<String, Long> containerBackedPackageDeletionFence = new ConcurrentHashMap<>();
private final AtomicLong containerBackedPackageDeletionCounter = new AtomicLong();
+ // Same race guard, scoped to one version instead of the whole package: see
+ // currentContainerBackedVersionFence's own javadoc. Shares containerBackedPackageDeletionCounter
+ // rather than a counter of its own, so a snapshot that compares equal at write time still proves
+ // neither this version nor the whole package was removed in between, with a single scalar.
+ private final ConcurrentHashMap<String, Long> containerBackedVersionDeletionFence = new ConcurrentHashMap<>();
// Maven, npm, pypi, and nuget publishes go straight to their own sidecar and never create a
// packageVersions record (see CONTAINER_BACKED_FORMATS), so DescribeDomain's assetSizeBytes
// can't see their bytes by summing packageVersions the way it does for generic. Each format's
@@ -1299,6 +1304,282 @@ public class CodeArtifactService implements Resettable {
packageName, "disposing", versions, versionRevisions, expectedStatus, "Disposed", true);
}
+ /**
+ * Permanently removes one or more versions of a package, every real asset included. Confirmed
+ * against the wire model and the User Guide rather than assumed from the shared {@code
+ * PackageVersionError} enum alone, the same discipline {@link #disposePackageVersions}'s own
+ * javadoc used:
+ * <ul>
+ * <li>{@code DeletePackageVersionsRequest} has no {@code versionRevisions} field at all
+ * (confirmed directly against {@code service-2.json}'s member list), only a single {@code
+ * expectedStatus} applied to the whole batch. Unlike {@link #updatePackageVersionsStatus}/
+ * {@link #disposePackageVersions}, this can never fail {@code MISMATCHED_REVISION}.
+ * <li>{@code expectedStatus} reuses the full, unrestricted {@code PackageVersionStatus} shape
+ * (confirmed against the wire model: unlike {@code targetStatus}, it is not narrowed to its
+ * own request-specific enum the way {@link #UPDATE_EXPECTED_STATUSES}/{@link
+ * #DISPOSE_EXPECTED_STATUSES} are), so every one of the six real status values is accepted.
+ * <li>Deleting is explicitly documented as allowed from every status, {@code Disposed}
+ * included: "the only action that can be taken on a package version that has been disposed is
+ * for it to be deleted." This never reuses {@link #checkStatusTransitionAllowed}, whose
+ * Disposed-blocks-further-change rule is specific to {@link #updatePackageVersionsStatus}/
+ * {@link #disposePackageVersions} and would otherwise wrongly reject exactly the one case AWS
+ * says this action must accept.
+ * <li>Unlike {@link #disposePackageVersions}, which keeps a tombstone record so {@link
+ * #describePackageVersion} can keep answering {@code Disposed}, a deleted version is
+ * documented as "no longer in the repository" at all, the same as one that was never
+ * published. {@link #describePackageVersion}/{@link #getPackageVersionAsset} must 404 on it
+ * afterward, and the freed coordinate can be freely republished (unlike Archived/Disposed,
+ * which {@link #publishPackageVersion}'s own check blocks).
+ * <li>The whole call is still all-or-nothing, the same documented behavior {@link
+ * #disposePackageVersions} shares: every version that would otherwise have succeeded is
+ * reported {@code SKIPPED} rather than partially applied.
+ * </ul>
+ *
+ * <p>{@code synchronized} for the same reason every other package-mutating method here is.
+ */
+ public synchronized PackageVersionStatusChangeResult deletePackageVersions(String region, String domain,
+ String domainOwner, String repository, String format, String namespace, String packageName,
+ List<String> versions, String expectedStatus) {
+ validatePackageCoordinates(format, namespace, packageName, "deleting versions of");
+ requireNonBlank(domain, "domain");
+ requireNonBlank(repository, "repository");
+ if (expectedStatus != null && !PACKAGE_VERSION_STATUSES.contains(expectedStatus)) {
+ throw validation("expectedStatus must be one of " + PACKAGE_VERSION_STATUSES + ".");
+ }
+ if (versions == null || versions.isEmpty()) {
+ throw validation("versions is required and must specify at least one version.");
+ }
+ if (versions.size() > MAX_PACKAGE_VERSIONS_PER_BATCH_CALL) {
+ throw validation("A single call can process at most " + MAX_PACKAGE_VERSIONS_PER_BATCH_CALL
+ + " versions.");
+ }
+ List<String> requestedVersions = List.copyOf(new LinkedHashSet<>(versions));
+ for (String version : requestedVersions) {
+ validatePackageToken("packageVersion", version);
+ }
+ String owner = effectiveOwner(domainOwner);
+ requireRepository(owner, repositoryKey(region, domain, repository), repository);
+
+ if (CONTAINER_BACKED_FORMATS.contains(format)) {
+ return deleteContainerBackedPackageVersions(region, domain, owner, repository, format, namespace,
+ packageName, requestedVersions, expectedStatus);
+ }
+ return deleteGenericPackageVersions(region, domain, owner, repository, format, namespace, packageName,
+ requestedVersions, expectedStatus);
+ }
+
+ /**
+ * The one check shared by every requested version in {@link #deletePackageVersions}, for
+ * either storage branch: {@code null} means the version is eligible to actually be deleted; a
+ * non-null result is the exact failure to report. Deliberately does not reuse {@link
+ * #checkStatusTransitionAllowed}: that method's Disposed-blocks-further-change rule does not
+ * apply here (see {@link #deletePackageVersions}'s own javadoc), and there is no revision to
+ * check against at all, since the real request shape has no {@code versionRevisions} field.
+ */
+ private static PackageVersionError checkDeletionAllowed(String currentStatus, String expectedStatus) {
+ if (expectedStatus != null && !expectedStatus.equals(currentStatus)) {
+ return new PackageVersionError("MISMATCHED_STATUS", "current status: " + currentStatus
+ + ", expected status: " + expectedStatus);
+ }
+ return null;
+ }
+
+ /**
+ * The {@code generic} branch of {@link #deletePackageVersions}: removes the version's record
+ * from {@code packageVersions} first, exactly the way {@link #deletePackage} already does for
+ * a whole package's worth of versions, and for the same reason: once the record is gone, no
+ * caller can reach its bytes through it regardless of whether the best-effort cleanup below
+ * succeeds, so a cleanup failure (logged, not thrown) can never leave a surviving record
+ * pointing at bytes that are already gone. This differs from {@link #disposePackageVersions}'s
+ * own stricter ordering deliberately: that action keeps a tombstone a failed cleanup could
+ * misrepresent, this one does not.
+ */
+ private PackageVersionStatusChangeResult deleteGenericPackageVersions(String region, String domain, String owner,
+ String repository, String format, String namespace, String packageName, List<String> requestedVersions,
+ String expectedStatus) {
+ Map<String, PackageVersionError> failures = new LinkedHashMap<>();
+ List<String> pending = new ArrayList<>();
+ Map<String, CodeArtifactPackageVersion> byVersion = new LinkedHashMap<>();
+ for (String version : requestedVersions) {
+ String key = packageVersionKey(region, domain, repository, format, namespace, packageName, version);
+ CodeArtifactPackageVersion pv = packageVersions.getForAccount(owner, key).orElse(null);
+ if (pv == null) {
+ failures.put(version, new PackageVersionError("NOT_FOUND", "Could not find version " + version));
+ continue;
+ }
+ PackageVersionError failure = checkDeletionAllowed(pv.getStatus(), expectedStatus);
+ if (failure != null) {
+ failures.put(version, failure);
+ continue;
+ }
+ byVersion.put(version, pv);
+ pending.add(version);
+ }
+ if (!failures.isEmpty()) {
+ for (String version : pending) {
+ failures.put(version, new PackageVersionError("SKIPPED", "Version " + version + " is skipped"));
+ }
+ return new PackageVersionStatusChangeResult(Map.of(), failures);
+ }
+
+ Map<String, SuccessfulPackageVersionInfo> successes = new LinkedHashMap<>();
+ for (String version : pending) {
+ CodeArtifactPackageVersion pv = byVersion.get(version);
+ String key = packageVersionKey(region, domain, repository, format, namespace, packageName, version);
+ packageVersions.deleteForAccount(owner, key);
+ for (PackageAsset asset : pv.getAssets().values()) {
+ try {
+ deleteAssetContent(owner, key, asset.getName());
+ } catch (UncheckedIOException e) {
+ LOG.warnv(e, "Could not delete CodeArtifact asset file for {0}/{1}: {2}", key,
+ asset.getName(), e.getMessage());
+ }
+ }
+ successes.put(version, new SuccessfulPackageVersionInfo(pv.getRevision(), "Deleted"));
+ }
+ return new PackageVersionStatusChangeResult(successes, Map.of());
+ }
+
+ /**
+ * The container-backed branch of {@link #deletePackageVersions}: deletes every one of the
+ * version's real assets first, through the exact same {@link #deleteContainerBackedVersionAssets}
+ * {@link #disposePackageVersions} already uses (real deletion, byte accounting, and Maven
+ * metadata cleanup are identical regardless of which action triggered them), propagating any
+ * sidecar failure rather than swallowing it, the same ordering {@link #deletePackage}'s own
+ * container-backed branch already uses for a whole package. The status override is only
+ * cleared afterward, with {@link #clearContainerBackedStatusOverride} rather than {@link
+ * #writeContainerBackedStatusOverride}: unlike {@link #disposePackageVersions}, this leaves no
+ * tombstone, so {@link #containerBackedVersionExists} reports the version gone entirely once
+ * both steps finish, matching the User Guide's "no longer in the repository" wording.
+ */
+ private PackageVersionStatusChangeResult deleteContainerBackedPackageVersions(String region, String domain,
+ String owner, String repository, String format, String namespace, String packageName,
+ List<String> requestedVersions, String expectedStatus) {
+ String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
+ RepositorySidecarManager manager = sidecarRegistry.forFormat(format)
+ .orElseThrow(() -> notFound("Package '" + packageName + "' was not found.", packageName, "package"));
+ List<RepositorySidecarManager.PackageVersionTimestamp> raw;
+ try {
+ raw = manager.listPackageVersions(repoId, domain, repository, namespace, packageName);
+ } catch (UnsupportedOperationException e) {
+ throw new AwsException("InternalServerException", "Deleting " + format + " package versions is not "
+ + "yet supported by this emulator.", 500);
+ }
+ // Keyed by normalized version (see normalizedContainerBackedVersion), the same as
+ // applyContainerBackedStatusChange's own realPublishedTimes. Raised by Greptile's review:
+ // BaGetter's own listing can spell a NuGet version differently than a caller's own
+ // request does, and the override side index already normalizes on write, so comparing
+ // both against the same normalized form here is what keeps existence checks, override
+ // reads, and the deletion gate below consistent with every other container-backed lookup.
+ Map<String, Instant> realPublishedTimes = new LinkedHashMap<>();
+ for (RepositorySidecarManager.PackageVersionTimestamp v : raw) {
+ realPublishedTimes.put(normalizedContainerBackedVersion(format, v.version()), v.publishedTime());
+ }
+ Map<String, PackageVersionStatusOverride> overridesByVersion = containerBackedOverridesForPackage(owner,
+ region, domain, repository, format, namespace, packageName);
+
+ Map<String, PackageVersionError> failures = new LinkedHashMap<>();
+ List<String> pending = new ArrayList<>();
+ Map<String, String> finalRevisionByVersion = new LinkedHashMap<>();
+ for (String version : requestedVersions) {
+ String matchVersion = normalizedContainerBackedVersion(format, version);
+ boolean existsNow = realPublishedTimes.containsKey(matchVersion)
+ || overridesByVersion.containsKey(matchVersion);
+ if (!existsNow) {
+ failures.put(version, new PackageVersionError("NOT_FOUND", "Could not find version " + version));
+ continue;
+ }
+ PackageVersionStatusOverride override = overridesByVersion.get(matchVersion);
+ String currentStatus = override != null ? override.status() : "Published";
+ String currentRevision = override != null ? override.revision()
+ : synthesizeContainerBackedRevision(format, repoId, namespace, packageName, version);
+ PackageVersionError failure = checkDeletionAllowed(currentStatus, expectedStatus);
+ if (failure != null) {
+ failures.put(version, failure);
+ continue;
+ }
+ finalRevisionByVersion.put(version, currentRevision);
+ pending.add(version);
+ }
+ if (!failures.isEmpty()) {
+ for (String version : pending) {
+ failures.put(version, new PackageVersionError("SKIPPED", "Version " + version + " is skipped"));
+ }
+ return new PackageVersionStatusChangeResult(Map.of(), failures);
+ }
+
+ Map<String, SuccessfulPackageVersionInfo> successes = new LinkedHashMap<>();
+ for (String version : pending) {
+ String matchVersion = normalizedContainerBackedVersion(format, version);
+ PackageVersionStatusOverride override = overridesByVersion.get(matchVersion);
+ boolean retryingPendingAssets = override != null && !override.pendingAssetNames().isEmpty();
+ boolean sidecarStillListsIt = realPublishedTimes.containsKey(matchVersion);
+ if (retryingPendingAssets || sidecarStillListsIt) {
+ List<String> assetNames;
+ if (retryingPendingAssets) {
+ // A retry of a previously partially-failed dispose, or of this same delete
+ // call (see the write below): reuse exactly what is still known to need
+ // cleanup rather than asking the sidecar again, since npm's own listing can no
+ // longer answer this once a prior attempt's own per-asset delete already
+ // updated the packument (see PackageVersionStatusOverride's own javadoc).
+ // Raised by Greptile's review: this case used to fall through to the sidecar
+ // listing below, which for npm no longer named the version at all once its
+ // packument update had landed, so these assets were silently skipped and the
+ // override cleared anyway, orphaning the tarball on disk.
+ assetNames = override.pendingAssetNames();
+ } else {
+ try {
+ assetNames = manager.listPackageVersionAssetNames(repoId, domain, repository, namespace,
+ packageName, version);
+ } catch (UnsupportedOperationException e) {
+ throw new AwsException("InternalServerException", "Deleting a package version of this "
+ + "format is not yet supported by this emulator.", 500);
+ }
+ }
+ // Written before deleting, exactly like disposePackageVersions's own ordering: a
+ // sidecar failing partway through this version's own asset deletions must leave
+ // pendingAssetNames naming only what genuinely remains, so a retry (another
+ // DeletePackageVersions call on the same coordinate) can still find it afterward.
+ Instant publishedTime = realPublishedTimes.get(matchVersion);
+ writeContainerBackedStatusOverride(owner, region, domain, repository, format, namespace,
+ packageName, version,
+ new PackageVersionStatusOverride(override != null ? override.status() : "Published",
+ override != null ? override.revision() : finalRevisionByVersion.get(version),
+ override != null ? override.publishedEpochSeconds()
+ : (publishedTime == null ? null : publishedTime.getEpochSecond()),
+ assetNames));
+ // Called even when assetNames ends up empty here (every real asset already
+ // deleted by an earlier attempt): raised by Greptile's review, {@code
+ // deleteContainerBackedVersionAssets}'s own trailing {@code recordVersionDisposed}
+ // call is what retries Maven's metadata.xml/checksum cleanup, and gating this call
+ // on a non-empty list, as an earlier version of this fix did, meant a retry whose
+ // only remaining failure was that metadata update (sidecarStillListsIt true,
+ // nothing left in a fresh asset listing) skipped retrying it and cleared the
+ // override anyway.
+ deleteContainerBackedVersionAssets(manager, repoId, owner, region, domain, repository, format,
+ namespace, packageName, version, assetNames);
+ }
+ clearContainerBackedStatusOverride(owner, region, domain, repository, format, namespace, packageName,
+ version);
+ // npm/pypi readmes are captured separately at publish time (see
+ // recordPublishedPackageVersionReadme's own javadoc) and never answered live from the
+ // sidecar the way nuget's readme is, so deleting the version here would otherwise leave
+ // getPackageVersionReadme still serving it forever.
+ String readmeKey = packageVersionKey(region, domain, repository, format, namespace,
+ accountingPackageName(format, packageName), version);
+ packageVersionReadmes.remove(ownerScopedKey(owner, readmeKey));
+ // Bumps this version's own fence (see currentContainerBackedVersionFence's own
+ // javadoc): raised by Greptile's review, without this a publish's readme capture
+ // already in flight for this exact version, delayed past this delete, would resurrect
+ // the readme just removed above, since nothing short of this would ever invalidate its
+ // own snapshot.
+ containerBackedVersionDeletionFence.put(ownerScopedKey(owner, readmeKey),
+ containerBackedPackageDeletionCounter.incrementAndGet());
+ successes.put(version, new SuccessfulPackageVersionInfo(finalRevisionByVersion.get(version), "Deleted"));
+ }
+ return new PackageVersionStatusChangeResult(successes, Map.of());
+ }
+
private PackageVersionStatusChangeResult applyPackageVersionStatusChange(String region, String domain,
String domainOwner, String repository, String format, String namespace, String packageName,
String action, List<String> versions, Map<String, String> versionRevisions, String expectedStatus,
@@ -2962,8 +3243,8 @@ public class CodeArtifactService implements Resettable {
if (readme == null) {
return;
}
- long readmeFenceSnapshot = currentContainerBackedPackageFence(region, domain, owner,
- destinationRepository, format, namespace, packageName);
+ long readmeFenceSnapshot = currentContainerBackedVersionFence(region, domain, owner,
+ destinationRepository, format, namespace, packageName, version);
recordPublishedPackageVersionReadme(region, domain, owner, destinationRepository, format, namespace,
packageName, version, readme, readmeFenceSnapshot);
} catch (RuntimeException e) {
@@ -3245,18 +3526,19 @@ public class CodeArtifactService implements Resettable {
* existence here, inside the same {@code synchronized} call that does the write, closes that
* window the same way every other mutating method here already does.
*
- * <p>{@code packageFenceSnapshot} is whatever {@link #currentContainerBackedPackageFence}
- * returned when the proxy called it, right before issuing the real write this call reports the
- * readme of, the exact same snapshot the proxy already takes to call
- * {@link #recordContainerBackedAssetBytes}. Without comparing it here too, a publish's readme
- * capture that runs on a delayed callback (npm's own, off the event loop) after a concurrent
- * {@link #deletePackage} or native unpublish has already removed this package would resurrect
- * a readme for a package {@link #getPackageVersionReadme} should now 404 on, the same window
- * {@code recordContainerBackedAssetBytes} already closes for byte accounting.
+ * <p>{@code fenceSnapshot} is whatever {@link #currentContainerBackedVersionFence} returned
+ * when the proxy called it, right before issuing the real write this call reports the readme
+ * of. Without comparing it here too, a publish's readme capture that runs on a delayed callback
+ * (npm's own, off the event loop) after a concurrent {@link #deletePackage}, native unpublish,
+ * or {@link #deletePackageVersions} call for this exact version has already removed it would
+ * resurrect a readme {@link #getPackageVersionReadme} should now 404 on. Raised by Greptile's
+ * review: this used to compare against {@link #currentContainerBackedPackageFence} alone, which
+ * only ever changes on a whole-package removal, so a single version's own deletion never
+ * invalidated a readme capture already in flight for it.
*/
public synchronized void recordPublishedPackageVersionReadme(String region, String domain, String domainOwner,
String repository, String format, String namespace, String packageName, String version,
- String readme, long packageFenceSnapshot) {
+ String readme, long fenceSnapshot) {
if (!isValidPackageToken(packageName) || !isValidPackageToken(version)
|| (namespace != null && !isValidPackageToken(namespace))) {
LOG.warnv("Skipping readme capture for {0}/{1} package ''{2}'' version ''{3}'': the namespace, name, "
@@ -3272,14 +3554,16 @@ public class CodeArtifactService implements Resettable {
}
String accountingName = accountingPackageName(format, packageName);
String fenceKey = packageKey(region, domain, repository, format, namespace, accountingName);
- long currentFence = containerBackedPackageDeletionFence.getOrDefault(ownerScopedKey(owner, fenceKey), 0L);
- if (currentFence != packageFenceSnapshot) {
- LOG.warnv("Skipping readme capture for {0}/{1} package ''{2}'': a DeletePackage removed it from the "
- + "{3} sidecar (possibly replaced by a different publish) while this publish was in flight.",
- domain, repository, packageName, format);
+ String key = packageVersionKey(region, domain, repository, format, namespace, accountingName, version);
+ long currentFence = Math.max(containerBackedPackageDeletionFence.getOrDefault(ownerScopedKey(owner,
+ fenceKey), 0L), containerBackedVersionDeletionFence.getOrDefault(ownerScopedKey(owner, key), 0L));
+ if (currentFence != fenceSnapshot) {
+ LOG.warnv("Skipping readme capture for {0}/{1} package ''{2}'' version ''{3}'': a DeletePackage or "
+ + "DeletePackageVersions removed it from the {4} sidecar (possibly replaced by a different "
+ + "publish) while this publish was in flight.", domain, repository, packageName, version,
+ format);
return;
}
- String key = packageVersionKey(region, domain, repository, format, namespace, accountingName, version);
packageVersionReadmes.put(ownerScopedKey(owner, key), readme == null ? "" : readme);
}
@@ -3391,6 +3675,7 @@ public class CodeArtifactService implements Resettable {
packageOriginConfigs.clear();
containerBackedAssetBytes.clear();
containerBackedPackageDeletionFence.clear();
+ containerBackedVersionDeletionFence.clear();
packageVersionReadmes.clear();
containerBackedPackageVersionStatusOverrides.clear();
containerBackedOverriddenVersionsByPackage.clear();
@@ -3508,6 +3793,36 @@ public class CodeArtifactService implements Resettable {
return containerBackedPackageDeletionFence.getOrDefault(ownerScopedKey(owner, key), 0L);
}
+ /**
+ * Same purpose as {@link #currentContainerBackedPackageFence}, narrowed to one version: a
+ * snapshot a format proxy takes right before issuing a real per-version write (an npm publish's
+ * own readme, or pypi's twine upload description), for {@link
+ * #recordPublishedPackageVersionReadme} to compare against once that write completes. Unlike
+ * byte accounting, which only ever runs for a whole package at a time (see {@link
+ * #recordContainerBackedAssetBytes}'s own javadoc) and so has no per-version snapshot of its
+ * own, a captured readme is keyed per version, and {@link #deletePackageVersions} can remove
+ * just one version's readme without touching its siblings'. Raised by Greptile's review:
+ * {@link #deletePackageVersions} cleared a deleted version's own captured readme without
+ * bumping any fence at all, so a publish callback already in flight for that exact version,
+ * delayed past the delete (Verdaccio's own response arriving well after this emulator's side of
+ * the delete already finished), would resurrect the readme it just removed. Returns whichever
+ * of the package-wide fence or this version's own is higher, so a snapshot taken here still
+ * catches a whole-package removal ({@link #deletePackage}, or a native {@code npm unpublish}
+ * via {@link #forgetContainerBackedPackage}) exactly the way {@link
+ * #currentContainerBackedPackageFence} already does on its own.
+ */
+ public long currentContainerBackedVersionFence(String region, String domain, String domainOwner,
+ String repository, String format, String namespace, String packageName, String version) {
+ String owner = effectiveOwner(domainOwner);
+ String accountingName = accountingPackageName(format, packageName);
+ String packageFenceKey = ownerScopedKey(owner, packageKey(region, domain, repository, format, namespace,
+ accountingName));
+ String versionFenceKey = ownerScopedKey(owner, packageVersionKey(region, domain, repository, format,
+ namespace, accountingName, version));
+ return Math.max(containerBackedPackageDeletionFence.getOrDefault(packageFenceKey, 0L),
+ containerBackedVersionDeletionFence.getOrDefault(versionFenceKey, 0L));
+ }
+
/**
* Adds {@code bytes} to the running total CodeArtifact's own storage tracks for one
* Maven/npm/pypi/nuget package, independent of whatever that sidecar could report back later:
diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java
index c61cac4dd0..e9b04bf5df 100644
--- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java
@@ -251,6 +251,49 @@ class CodeArtifactIntegrationTest {
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
}
+ @Test
+ void deletePackageVersionsRouteRemovesAVersionAndDescribeReturnsNotFound() {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{}").post("/v1/domain?domain=delete-versions-domain").then().statusCode(200);
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{}").post("/v1/repository?domain=delete-versions-domain&repository=repo")
+ .then().statusCode(200);
+ byte[] content = "delete-version-me".getBytes(StandardCharsets.UTF_8);
+ given().header("Authorization", AUTH).header("x-amz-content-sha256", Digests.sha256Hex(content))
+ .contentType("application/octet-stream").body(content)
+ .post("/v1/package/version/publish?domain=delete-versions-domain&repository=repo&format=generic"
+ + "&namespace=ns&package=my-pkg&version=1.0.0&asset=a.txt")
+ .then().statusCode(200);
+
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"versions\":[\"1.0.0\"]}")
+ .post("/v1/package/versions/delete?domain=delete-versions-domain&repository=repo&format=generic"
+ + "&namespace=ns&package=my-pkg")
+ .then().statusCode(200)
+ .body("successfulVersions.'1.0.0'.status", equalTo("Deleted"))
+ .body("failedVersions", equalTo(Map.of()));
+
+ given().header("Authorization", AUTH)
+ .get("/v1/package/version?domain=delete-versions-domain&repository=repo&format=generic"
+ + "&namespace=ns&package=my-pkg&version=1.0.0")
+ .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
+
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"versions\":[\"1.0.0\"]}")
+ .post("/v1/package/versions/delete?domain=delete-versions-domain&repository=repo&format=generic"
+ + "&namespace=ns&package=my-pkg")
+ .then().statusCode(200)
+ .body("successfulVersions", equalTo(Map.of()))
+ .body("failedVersions.'1.0.0'.errorCode", equalTo("NOT_FOUND"));
+
+ given().header("Authorization", AUTH)
+ .delete("/v1/repository?domain=delete-versions-domain&repository=repo")
+ .then().statusCode(200);
+ given().header("Authorization", AUTH)
+ .delete("/v1/domain?domain=delete-versions-domain")
+ .then().statusCode(200);
+ }
+
@Test
void putPackageOriginConfigurationCreatesAPackageAndItsRestrictionsSurviveDescribeAndDelete() {
given().contentType("application/json").header("Authorization", AUTH)
diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java
index e2518f34f4..d05d19c4f8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java
@@ -51,6 +51,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
@@ -332,8 +333,8 @@ class CodeArtifactServiceTest {
/** Same snapshot-then-report shape as {@link #recordBytes}, for readme capture instead. */
private void recordReadme(String domain, String repository, String format, String namespace, String packageName,
String version, String readme) {
- long fence = service.currentContainerBackedPackageFence(REGION, domain, null, repository, format, namespace,
- packageName);
+ long fence = service.currentContainerBackedVersionFence(REGION, domain, null, repository, format, namespace,
+ packageName, version);
service.recordPublishedPackageVersionReadme(REGION, domain, null, repository, format, namespace, packageName,
version, readme, fence);
}
@@ -4138,6 +4139,412 @@ class CodeArtifactServiceTest {
assertEquals("ValidationException", e.getErrorCode());
}
+ // --------------------------------------------- DeletePackageVersions
+
+ @Test
+ void deletePackageVersionsRemovesTheGenericRecordAndAssetsAndAllowsFreeRepublish() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
+ CodeArtifactService.PublishPackageVersionResult published = service.publishPackageVersion(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt", Digests.sha256Hex(content), "false",
+ content);
+ String revisionBeforeDelete = published.packageVersion().getRevision();
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0.0").status());
+ assertEquals(revisionBeforeDelete, result.successfulVersions().get("1.0.0").revision());
+ AwsException gone = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", "1.0.0"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+
+ // Unlike Archived/Disposed, a deleted coordinate can be freely republished.
+ byte[] newContent = "v2".getBytes(StandardCharsets.UTF_8);
+ service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
+ Digests.sha256Hex(newContent), "false", newContent);
+ CodeArtifactPackageVersion republished = service.describePackageVersion(REGION, "dom", null, "repo",
+ "generic", "ns", "my-pkg", "1.0.0");
+ assertEquals("Published", republished.getStatus());
+ }
+
+ @Test
+ void deletePackageVersionsFailsNotFoundForAVersionThatWasNeverPublished() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null);
+
+ assertEquals("NOT_FOUND", result.failedVersions().get("1.0.0").errorCode());
+ assertTrue(result.successfulVersions().isEmpty());
+ }
+
+ @Test
+ void deletePackageVersionsSkipsEveryOtherwiseEligibleVersionWhenOneFails() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
+ service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
+ Digests.sha256Hex(content), "false", content);
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0", "2.0.0"), null);
+
+ assertEquals("SKIPPED", result.failedVersions().get("1.0.0").errorCode());
+ assertEquals("NOT_FOUND", result.failedVersions().get("2.0.0").errorCode());
+ assertTrue(result.successfulVersions().isEmpty());
+ CodeArtifactPackageVersion stillThere = service.describePackageVersion(REGION, "dom", null, "repo",
+ "generic", "ns", "my-pkg", "1.0.0");
+ assertEquals("Published", stillThere.getStatus());
+ }
+
+ @Test
+ void deletePackageVersionsFailsMismatchedStatus() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
+ service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
+ Digests.sha256Hex(content), "false", content);
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), "Archived");
+
+ assertEquals("MISMATCHED_STATUS", result.failedVersions().get("1.0.0").errorCode());
+ }
+
+ /**
+ * The User Guide's one documented exception to Disposed's own immutability: "the only action
+ * that can be taken on a package version that has been disposed is for it to be deleted."
+ * Deliberately does not reuse {@code checkStatusTransitionAllowed}'s Disposed-blocks-further
+ * -change rule, which would otherwise wrongly reject exactly this case.
+ */
+ @Test
+ void deletePackageVersionsSucceedsOnAnAlreadyDisposedGenericVersion() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ byte[] content = "v1".getBytes(StandardCharsets.UTF_8);
+ service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", "1.0.0", "a.txt",
+ Digests.sha256Hex(content), "false", content);
+ service.disposePackageVersions(REGION, "dom", null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"),
+ null, null);
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0.0").status());
+ AwsException gone = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom",
+ null, "repo", "generic", "ns", "my-pkg", "1.0.0"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ }
+
+ @Test
+ void deletePackageVersionsRejectsAnInvalidExpectedStatus() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+
+ AwsException e = assertThrows(AwsException.class, () -> service.deletePackageVersions(REGION, "dom", null,
+ "repo", "generic", "ns", "my-pkg", List.of("1.0.0"), "NotAStatus"));
+ assertEquals("ValidationException", e.getErrorCode());
+ }
+
+ @Test
+ void deletePackageVersionsRequiresAtLeastOneVersion() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+
+ AwsException e = assertThrows(AwsException.class, () -> service.deletePackageVersions(REGION, "dom", null,
+ "repo", "generic", "ns", "my-pkg", List.of(), null));
+ assertEquals("ValidationException", e.getErrorCode());
+ }
+
+ @Test
+ void deletePackageVersionsDeletesEveryRealMavenAssetClearsTheOverrideAndReducesDomainBytes() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("maven");
+ recordBytes("dom", "repo", "maven", "com.example", "a", 100L);
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
+ when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
+ when(reposiliteClient.fetchPackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"), eq("1.0"), eq("a-1.0.jar"))).thenReturn(Optional.of(new byte[40]));
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", List.of("1.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0").status());
+ verify(reposiliteClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"), eq("1.0"), eq("a-1.0.jar"));
+ verify(reposiliteClient).recordVersionDisposed(eq(repoId), eq("com.example"), eq("a"), eq("1.0"));
+ assertEquals(60L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
+ // The sidecar no longer lists it and the override is gone too, so it reads as never having
+ // existed, unlike disposePackageVersions' own tombstone.
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of());
+ AwsException gone = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", "1.0"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ }
+
+ /**
+ * Raised by Greptile's review of the npm fix above: gating the call to {@link
+ * #deleteContainerBackedVersionAssets} on a non-empty asset list broke the case where every
+ * real asset is already gone but that method's own trailing {@code recordVersionDisposed}
+ * call, Maven's {@code maven-metadata.xml}/checksum cleanup, is what actually failed. A retry
+ * whose fresh listing now reads empty (the real file is gone) must still finish that metadata
+ * update rather than skip it just because there is nothing left to delete.
+ */
+ @Test
+ void deletePackageVersionsRetriesMavenMetadataCleanupEvenWhenNoRealAssetIsLeftToDelete() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("maven");
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
+ when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
+ doThrow(new IllegalStateException("metadata rewrite failed"))
+ .when(reposiliteClient).recordVersionDisposed(eq(repoId), eq("com.example"), eq("a"), eq("1.0"));
+
+ assertThrows(IllegalStateException.class, () -> service.deletePackageVersions(REGION, "dom", null, "repo",
+ "maven", "com.example", "a", List.of("1.0"), null));
+
+ // The real jar is already gone (its own delete call succeeded before the metadata update
+ // threw), so a fresh listing now reads empty, but the sidecar's own listPackageVersions
+ // still names the version since the metadata rewrite that would drop it never finished.
+ when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"), eq("1.0"))).thenReturn(List.of());
+ doNothing().when(reposiliteClient).recordVersionDisposed(eq(repoId), eq("com.example"), eq("a"), eq("1.0"));
+
+ CodeArtifactService.PackageVersionStatusChangeResult retry = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", List.of("1.0"), null);
+
+ assertEquals("Deleted", retry.successfulVersions().get("1.0").status());
+ // The real asset delete never needed a second attempt, but the metadata cleanup does:
+ // once from the failed first attempt, once from the retry that actually finishes it.
+ verify(reposiliteClient, times(1)).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"),
+ eq("com.example"), eq("a"), eq("1.0"), eq("a-1.0.jar"));
+ verify(reposiliteClient, times(2)).recordVersionDisposed(eq(repoId), eq("com.example"), eq("a"), eq("1.0"));
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of());
+ AwsException gone = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", "1.0"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ }
+
+ /**
+ * The container-backed counterpart to {@link #deletePackageVersionsSucceedsOnAnAlreadyDisposedGenericVersion}:
+ * a Disposed version's real sidecar content is already gone, so this must clear the override
+ * without ever calling back into the sidecar for assets that no longer exist.
+ */
+ @Test
+ void deletePackageVersionsSucceedsOnAnAlreadyDisposedMavenVersionWithoutTouchingTheSidecarAssets() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("maven");
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0", Instant.ofEpochSecond(1000))));
+ when(reposiliteClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"), eq("1.0"))).thenReturn(List.of("a-1.0.jar"));
+ service.disposePackageVersions(REGION, "dom", null, "repo", "maven", "com.example", "a", List.of("1.0"),
+ null, null);
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of());
+ clearInvocations(reposiliteClient);
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", List.of("1.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0").status());
+ verify(reposiliteClient, never()).deletePackageVersionAsset(any(), any(), any(), any(), any(), eq("1.0"),
+ any());
+ AwsException gone = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", "1.0"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ }
+
+ /**
+ * Raised by Greptile's review: this used to reach the branch below at all only when the
+ * sidecar still listed the version with real content. Verdaccio's own real npm unpublish
+ * (packument update before the tarball delete, confirmed live, see {@code
+ * VerdaccioSidecarClient#deletePackageVersionAsset}'s own javadoc) already leaves a fresh
+ * listing empty once a prior dispose attempt's packument update landed, even though its own
+ * tarball delete then failed. That used to fall straight through to clearing the override,
+ * silently reporting {@code Deleted} with the real tarball still on disk. {@code
+ * DeletePackageVersions} is documented as the one thing still allowed on an already Disposed
+ * version, so it must finish the job by reading the override's own {@code pendingAssetNames}
+ * instead, exactly like {@link #disposePackageVersionsRetriesAnNpmTarballDeleteEvenAfterTheSidecarsOwnListingGoesEmpty}'s
+ * own retry does for a second dispose.
+ */
+ @Test
+ void deletePackageVersionsFinishesAPreviouslyPartiallyFailedNpmDisposeInsteadOfOrphaningTheTarball() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("npm");
+ when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
+ .thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
+ when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
+ doThrow(new IllegalStateException("sidecar unreachable"))
+ .when(verdaccioClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
+
+ assertThrows(IllegalStateException.class, () -> service.disposePackageVersions(REGION, "dom", null, "repo",
+ "npm", null, "my-pkg", List.of("1.0.0"), null, null));
+
+ // Simulates exactly what Greptile's review describes: Verdaccio's own packument update
+ // already landed, so a fresh listing now reads empty even though the tarball itself
+ // never actually got deleted.
+ when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
+ .thenReturn(List.of());
+ when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of());
+ doNothing().when(verdaccioClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "npm", null, "my-pkg", List.of("1.0.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0.0").status());
+ // Twice in total across both attempts: the first (from the failed dispose) threw, the
+ // delete's own retry call is the one that actually finished removing the tarball.
+ verify(verdaccioClient, times(2)).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"), eq("my-pkg-1.0.0.tgz"));
+ AwsException gone = assertThrows(AwsException.class, () -> service.describePackageVersion(REGION, "dom",
+ null, "repo", "npm", null, "my-pkg", "1.0.0"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ }
+
+ /**
+ * The delete counterpart to {@link
+ * #updatePackageVersionsStatusMatchesAnEquivalentNuGetVersionSpellingAgainstAnExistingOverride}.
+ * Raised by Greptile's review: {@code DeletePackageVersions} compared the raw requested
+ * version against both BaGetter's own listing and the override index without normalizing
+ * either side first, unlike every other container-backed lookup, so an equivalent spelling
+ * (AWS's own worked example, {@code 1.00} and {@code 1.0.0}) found neither the real sidecar
+ * content nor an override for the version it actually names, turning one such entry in a
+ * batch into a {@code SKIPPED} failure for every other, otherwise valid, version too.
+ */
+ @Test
+ void deletePackageVersionsMatchesAnEquivalentNuGetVersionSpellingAgainstRealSidecarContent() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("nuget");
+ when(bagetterClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
+ .thenReturn(List.of(new RepositorySidecarManager.PackageVersionTimestamp("1.0.0",
+ Instant.ofEpochSecond(1000))));
+ when(bagetterClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.00"))).thenReturn(List.of("my-pkg.1.00.nupkg"));
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "nuget", null, "my-pkg", List.of("1.00"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.00").status());
+ verify(bagetterClient).deletePackageVersionAsset(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg"),
+ eq("1.00"), eq("my-pkg.1.00.nupkg"));
+ }
+
+ @Test
+ void deletePackageVersionsFailsNotFoundForAContainerBackedVersionThatWasNeverPublished() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("maven");
+ when(reposiliteClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), eq("com.example"),
+ eq("a"))).thenReturn(List.of());
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "maven", "com.example", "a", List.of("1.0"), null);
+
+ assertEquals("NOT_FOUND", result.failedVersions().get("1.0").errorCode());
+ }
+
+ /**
+ * Greptile's review: unlike nuget, which answers {@code GetPackageVersionReadme} live against
+ * the sidecar, npm's readme is captured separately at publish time into this service's own
+ * store and never consulted again by anything else, so deleting the version must clear it
+ * there too or the readme keeps answering for a version that no longer exists.
+ */
+ @Test
+ void deletePackageVersionsClearsTheCapturedNpmReadmeSoGetPackageVersionReadmeStops404ing() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("npm");
+ recordReadme("dom", "repo", "npm", null, "my-pkg", "1.0.0", "# Real Readme");
+ when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
+ .thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
+ when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "npm", null, "my-pkg", List.of("1.0.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0.0").status());
+ AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionReadme(REGION, "dom",
+ null, "repo", "npm", null, "my-pkg", "1.0.0"));
+ assertEquals("ResourceNotFoundException", e.getErrorCode());
+ }
+
+ /** Same captured-readme cleanup as npm's own, confirmed separately since pypi captures readmes independently. */
+ @Test
+ void deletePackageVersionsClearsTheCapturedPypiReadmeSoGetPackageVersionReadmeStops404ing() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("pypi");
+ recordReadme("dom", "repo", "pypi", null, "my-pkg", "1.0.0", "A pypi description");
+ when(pypiserverClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
+ .thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
+ when(pypiserverClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my_pkg-1.0.0.tar.gz"));
+
+ CodeArtifactService.PackageVersionStatusChangeResult result = service.deletePackageVersions(REGION, "dom",
+ null, "repo", "pypi", null, "my-pkg", List.of("1.0.0"), null);
+
+ assertEquals("Deleted", result.successfulVersions().get("1.0.0").status());
+ AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionReadme(REGION, "dom",
+ null, "repo", "pypi", null, "my-pkg", "1.0.0"));
+ assertEquals("ResourceNotFoundException", e.getErrorCode());
+ }
+
+ /**
+ * Greptile's review of the readme-clearing fix above: a delayed npm publish callback for this
+ * exact version, its own fence snapshot taken before {@code DeletePackageVersions} ran, must
+ * not resurrect the readme that delete just removed once the callback finally completes.
+ */
+ @Test
+ void deletePackageVersionsInvalidatesAStaleInFlightNpmReadmeCaptureForThatSameVersion() {
+ service.createDomain(REGION, "dom", null, Map.of());
+ CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
+ String repoId = created.getSidecarContainerIds().get("npm");
+ // Simulates the proxy's own snapshot, taken right before issuing the real publish write,
+ // long before Verdaccio's delayed response ever lets the callback below run.
+ long staleFenceSnapshot = service.currentContainerBackedVersionFence(REGION, "dom", null, "repo", "npm",
+ null, "my-pkg", "1.0.0");
+ when(verdaccioClient.listPackageVersions(eq(repoId), eq("dom"), eq("repo"), isNull(), eq("my-pkg")))
+ .thenReturn(List.of(
+ new RepositorySidecarManager.PackageVersionTimestamp("1.0.0", Instant.ofEpochSecond(1000))));
+ when(verdaccioClient.listPackageVersionAssetNames(eq(repoId), eq("dom"), eq("repo"), isNull(),
+ eq("my-pkg"), eq("1.0.0"))).thenReturn(List.of("my-pkg-1.0.0.tgz"));
+
+ service.deletePackageVersions(REGION, "dom", null, "repo", "npm", null, "my-pkg", List.of("1.0.0"), null);
+ // The delayed callback finally runs, well after the delete above, using the snapshot it
+ // took before either of them.
+ service.recordPublishedPackageVersionReadme(REGION, "dom", null, "repo", "npm", null, "my-pkg", "1.0.0",
+ "resurrected text", staleFenceSnapshot);
+
+ AwsException e = assertThrows(AwsException.class, () -> service.getPackageVersionReadme(REGION, "dom",
+ null, "repo", "npm", null, "my-pkg", "1.0.0"));
+ assertEquals("ResourceNotFoundException", e.getErrorCode());
+ }
+
/**
* Qodo review finding on this PR: {@code DescribeDomain.assetSizeBytes} kept counting a
* container-backed version's bytes forever after disposal, since the per-package running