mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codeartifact): add DeletePackage for all package formats (#5320)
DeletePackage deletes a package and every one of its versions, matching PackageSummary's own field name (package, not name, confirmed against the API reference) in the deletedPackage response. A nonexistent package answers ResourceNotFoundException instead of silently succeeding. Existence and deletion go where the package actually lives: stored generic-format versions and their asset bytes for generic, and each format's sidecar for maven, npm, and pypi. Validates package and namespace shape, and requires or rejects a namespace per format, the same boundary describePackage already enforces, before touching repository or sidecar state. Synchronized like every other mutating method on this service, so a publish and a delete racing the same generic package cannot interleave. Within one generic version's own delete, its metadata record is removed before its asset bytes are cleaned up, so a cleanup failure on one asset can never leave a surviving record pointing at bytes that are now gone; the failure is logged and the rest of the package's assets still get cleaned up. Verdaccio and Reposilite can each remove a whole package in one call, confirmed against live containers: Verdaccio needs the packument's own _rev appended as npm's real unpublish protocol does (a bare DELETE with no revision is not a route at all), Reposilite removes everything under the group/artifact directory in a single DELETE. pypiserver has no single whole-package route, but its own management endpoint (POST / with :action=remove_pkg) does delete a named version for real, confirmed live against the pinned v2.4.2 image: every version is listed first through the same image's PyPI JSON API endpoint, then each file removed under its own, unnormalized name (an sdist and a wheel of the same release can legitimately differ there, so deleting by one shared name alone could silently leave the other file behind). RepositorySidecarManager.deletePackage's default still throws UnsupportedOperationException for a sidecar that genuinely cannot do this, and the service turns that into a documented InternalServerException rather than claiming a success it cannot back up or leaving an unhandled 500.
This commit is contained in:
1 parent
d0c2774564
commit
ceab47e785
17 files changed
+867
-13
No files matched your search
+33
@@ -342,6 +342,20 @@ public class CodeArtifactController {
|
||||
return ok(single("package", packageDescription(described)));
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/v1/package")
|
||||
public Response deletePackage(@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 region = regionResolver.resolveRegion(headers);
|
||||
CodeArtifactService.PackageDescription deleted = service.deletePackage(region, domain, domainOwner,
|
||||
repository, format, namespace, packageName);
|
||||
return ok(single("deletedPackage", deletedPackageDescription(deleted)));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v1/package/version")
|
||||
public Response describePackageVersion(@Context HttpHeaders headers, @QueryParam("domain") String domain,
|
||||
@@ -511,6 +525,25 @@ public class CodeArtifactController {
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code PackageSummary}, real AWS's response type for {@code deletedPackage}, names the
|
||||
* package's name field {@code package}, not {@code name}: a different field name than
|
||||
* {@code PackageDescription} uses for the same data in {@code DescribePackage}'s response,
|
||||
* confirmed against the API reference.
|
||||
*/
|
||||
private ObjectNode deletedPackageDescription(CodeArtifactService.PackageDescription described) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("format", described.format());
|
||||
if (described.namespace() != null) {
|
||||
node.put("namespace", described.namespace());
|
||||
}
|
||||
node.put("package", described.packageName());
|
||||
ObjectNode restrictions = node.putObject("originConfiguration").putObject("restrictions");
|
||||
restrictions.put("publish", described.publishRestriction());
|
||||
restrictions.put("upstream", described.upstreamRestriction());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode packageVersionDescription(CodeArtifactPackageVersion pv) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("format", pv.getFormat());
|
||||
|
||||
+111
-2
@@ -712,12 +712,121 @@ public class CodeArtifactService implements Resettable {
|
||||
|
||||
private boolean genericPackageExists(String region, String domain, String owner, String repository,
|
||||
String format, String namespace, String packageName) {
|
||||
return !genericPackageVersions(region, domain, owner, repository, format, namespace, packageName).isEmpty();
|
||||
}
|
||||
|
||||
private List<CodeArtifactPackageVersion> genericPackageVersions(String region, String domain, String owner,
|
||||
String repository, String format, String namespace, String packageName) {
|
||||
String prefix = packageVersionKey(region, domain, repository, format, namespace, packageName, "");
|
||||
String wantedNamespace = namespace == null ? "" : namespace;
|
||||
return packageVersions.scanForAccount(owner, key -> key.startsWith(prefix)).stream()
|
||||
.anyMatch(pv -> format.equals(pv.getFormat())
|
||||
.filter(pv -> format.equals(pv.getFormat())
|
||||
&& packageName.equals(pv.getPackageName())
|
||||
&& wantedNamespace.equals(pv.getNamespace() == null ? "" : pv.getNamespace()));
|
||||
&& wantedNamespace.equals(pv.getNamespace() == null ? "" : pv.getNamespace()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a package and every one of its versions. A deleted package cannot be restored,
|
||||
* matching the real API's own documented behavior. Existence is checked where the package
|
||||
* actually lives, the same way {@link #describePackage} checks it, so a nonexistent package
|
||||
* answers {@code ResourceNotFoundException} rather than silently succeeding.
|
||||
*
|
||||
* <p>{@code synchronized} for the same reason {@link #publishPackageVersion} is: without a
|
||||
* shared lock, a publish and a delete racing the same generic package could interleave (a
|
||||
* version restored after its asset bytes are already gone, or a version published mid-scan
|
||||
* silently surviving or being dropped).
|
||||
*/
|
||||
public synchronized PackageDescription deletePackage(String region, String domain, String domainOwner,
|
||||
String repository, String format, String namespace, String packageName) {
|
||||
if (format == null || !PACKAGE_FORMATS.contains(format)) {
|
||||
throw validation("format must be one of " + PACKAGE_FORMATS + ".");
|
||||
}
|
||||
validatePackageToken("package", packageName);
|
||||
if (namespace != null) {
|
||||
validatePackageToken("namespace", namespace);
|
||||
}
|
||||
// Same boundary as describePackage's own namespace rules (see its comment there for the
|
||||
// API reference citation): a missing generic/maven namespace would delete under a
|
||||
// null-namespace key nothing real ever publishes to, and a supplied pypi namespace would
|
||||
// be silently ignored by the sidecar's existence check rather than rejected.
|
||||
if (("maven".equals(format) || "generic".equals(format)) && (namespace == null || namespace.isBlank())) {
|
||||
throw validation("namespace is required when deleting a " + format + " package.");
|
||||
}
|
||||
if ("pypi".equals(format) && namespace != null) {
|
||||
throw validation("pypi packages do not have a namespace.");
|
||||
}
|
||||
requireNonBlank(domain, "domain");
|
||||
requireNonBlank(repository, "repository");
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
requireRepository(owner, repositoryKey(region, domain, repository), repository);
|
||||
if (CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
deleteContainerBackedPackage(region, domain, owner, repository, format, namespace, packageName);
|
||||
} else {
|
||||
List<CodeArtifactPackageVersion> versions = genericPackageVersions(region, domain, owner, repository,
|
||||
format, namespace, packageName);
|
||||
if (versions.isEmpty()) {
|
||||
throw notFound("Package '" + packageName + "' was not found.", packageName, "package");
|
||||
}
|
||||
for (CodeArtifactPackageVersion pv : versions) {
|
||||
String versionKey = packageVersionKey(region, domain, repository, format, namespace, packageName,
|
||||
pv.getVersion());
|
||||
// Metadata goes first: once the version record is gone, no caller can reach a
|
||||
// deleted asset's bytes through it regardless of whether the cleanup below
|
||||
// succeeds. Deleting bytes first and metadata last, if a later asset in the same
|
||||
// version failed to delete, would leave a surviving record pointing at bytes
|
||||
// already gone.
|
||||
packageVersions.deleteForAccount(owner, versionKey);
|
||||
for (PackageAsset asset : pv.getAssets().values()) {
|
||||
try {
|
||||
deleteAssetContent(owner, versionKey, asset.getName());
|
||||
} catch (UncheckedIOException e) {
|
||||
LOG.warnv(e, "Could not delete CodeArtifact asset file for {0}/{1}: {2}", versionKey,
|
||||
asset.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return new PackageDescription(format, namespace, packageName, "ALLOW", "BLOCK");
|
||||
}
|
||||
|
||||
/**
|
||||
* Each sidecar's delete capability differs enough that there is no honest shared implementation:
|
||||
* Verdaccio and Reposilite remove a whole package in one call, while pypiserver's own management
|
||||
* endpoint only deletes one exact name/version pair per call, so {@code PypiserverSidecarClient}
|
||||
* lists every file first and removes each one in turn; all three are confirmed against live
|
||||
* containers. {@link RepositorySidecarManager#deletePackage}'s default still throws
|
||||
* {@link UnsupportedOperationException} for a sidecar that genuinely cannot do this, rather than
|
||||
* silently leaving the package in place or claiming a success it cannot back up; that becomes a
|
||||
* real, if deliberately blunt, AWS error here instead of an unhandled 500.
|
||||
*/
|
||||
private void deleteContainerBackedPackage(String region, String domain, String owner, String repository,
|
||||
String format, String namespace, String packageName) {
|
||||
String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
|
||||
RepositorySidecarManager manager = sidecarRegistry.forFormat(format)
|
||||
.orElseThrow(() -> notFound("Package '" + packageName + "' was not found.", packageName, "package"));
|
||||
if (!manager.packageExists(repoId, domain, repository, namespace, packageName)) {
|
||||
throw notFound("Package '" + packageName + "' was not found.", packageName, "package");
|
||||
}
|
||||
try {
|
||||
manager.deletePackage(repoId, domain, repository, namespace, packageName);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
throw new AwsException("InternalServerException",
|
||||
"Deleting a " + format + " package is not yet supported by this emulator.", 500);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteAssetContent(String owner, String packageVersionKey, String assetName) {
|
||||
if (inMemory) {
|
||||
memoryAssetStore.remove(assetStoreKey(owner, packageVersionKey, assetName));
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveAssetPath(owner, packageVersionKey, assetName);
|
||||
try {
|
||||
Files.deleteIfExists(filePath);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to delete CodeArtifact asset file: " + filePath, e);
|
||||
}
|
||||
}
|
||||
|
||||
public PackageVersionAssetResult getPackageVersionAsset(String region, String domain, String domainOwner,
|
||||
|
||||
+118
-3
@@ -1,17 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpRequest.BodyPublishers;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -25,15 +33,17 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
|
||||
private static final Pattern SIMPLE_INDEX_HREF = Pattern.compile("href=\"([^\"]*)\"");
|
||||
|
||||
private final PypiserverSidecarManager manager;
|
||||
private final ObjectMapper mapper;
|
||||
private final HttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
public PypiserverSidecarClient(PypiserverSidecarManager manager) {
|
||||
this(manager, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
public PypiserverSidecarClient(PypiserverSidecarManager manager, ObjectMapper mapper) {
|
||||
this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
}
|
||||
|
||||
PypiserverSidecarClient(PypiserverSidecarManager manager, HttpClient httpClient) {
|
||||
PypiserverSidecarClient(PypiserverSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) {
|
||||
this.manager = manager;
|
||||
this.mapper = mapper;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@@ -112,6 +122,111 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
|
||||
return simpleIndex(baseUrl, packageName).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a whole package, every version at once, confirmed against a live container: the pinned
|
||||
* image's management endpoint ({@code POST /} with {@code :action=remove_pkg}) deletes one exact
|
||||
* {@code name}/{@code version} pair per call rather than a whole package or project at once, so
|
||||
* every file is first listed from the same PyPI JSON API endpoint this image also serves
|
||||
* ({@code GET /<project>/json}, grouped by the same normalized project the simple index uses),
|
||||
* then each one removed in turn.
|
||||
*
|
||||
* <p>{@code name} for each call is recovered from the filename that endpoint listed, not from the
|
||||
* caller's {@code packageName}: {@code remove_pkg} matches against the literal, unnormalized name
|
||||
* the server itself derived when that file was uploaded, and an sdist and a wheel of the very same
|
||||
* release can legitimately differ there (a hyphen in one, an underscore in the other), so deleting
|
||||
* by one filename's recovered name alone can silently leave the other file behind.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
for (PkgNameVersion file : packageFiles(baseUrl, packageName)) {
|
||||
removeVersion(baseUrl, file.name(), file.version());
|
||||
}
|
||||
}
|
||||
|
||||
private record PkgNameVersion(String name, String version) {}
|
||||
|
||||
private Set<PkgNameVersion> packageFiles(String baseUrl, String packageName) {
|
||||
String normalized = normalizePackageName(packageName);
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.encodeSegment(normalized)
|
||||
+ "/json");
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the pypiserver sidecar to list versions of "
|
||||
+ packageName, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return Set.of();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not list versions of " + packageName + " on the pypiserver "
|
||||
+ "sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
JsonNode releases;
|
||||
try {
|
||||
releases = mapper.readTree(response.body()).path("releases");
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse pypiserver's version listing for " + packageName, e);
|
||||
}
|
||||
Set<PkgNameVersion> files = new LinkedHashSet<>();
|
||||
for (Map.Entry<String, JsonNode> release : releases.properties()) {
|
||||
String version = release.getKey();
|
||||
for (JsonNode file : release.getValue()) {
|
||||
String url = file.path("url").asText("");
|
||||
String filename = url.substring(url.lastIndexOf('/') + 1);
|
||||
files.add(new PkgNameVersion(rawPkgname(filename, version), version));
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* The exact, unnormalized name pypiserver's own {@code remove_pkg} needs for {@code filename}, at
|
||||
* known version {@code version}: the text of {@code filename} up to (but not including) the
|
||||
* {@code -<version>} marker that {@link #versionBoundaryEndsAt} confirms really ends the version
|
||||
* field there, the same boundary {@link #filenameEmbedsVersion} already relies on. Falls back to
|
||||
* the whole filename in the (not expected in practice) case nothing satisfies that boundary: a
|
||||
* harmless no-op for {@code remove_pkg}, since no file was ever uploaded under that literal name.
|
||||
*/
|
||||
private static String rawPkgname(String filename, String version) {
|
||||
String marker = "-" + version;
|
||||
for (int idx = filename.indexOf(marker); idx >= 0; idx = filename.indexOf(marker, idx + 1)) {
|
||||
if (versionBoundaryEndsAt(filename, idx + marker.length())) {
|
||||
return filename.substring(0, idx);
|
||||
}
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
private void removeVersion(String baseUrl, String pkgname, String version) {
|
||||
String body = "%3Aaction=remove_pkg"
|
||||
+ "&name=" + URLEncoder.encode(pkgname, StandardCharsets.UTF_8)
|
||||
+ "&version=" + URLEncoder.encode(version, StandardCharsets.UTF_8);
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.POST(BodyPublishers.ofString(body))
|
||||
.build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the pypiserver sidecar to delete " + pkgname + " "
|
||||
+ version, e);
|
||||
}
|
||||
// 404 means remove_pkg found nothing for this exact name/version: already removed by an
|
||||
// earlier call in this same loop for a sibling file that happened to share it, not a real
|
||||
// failure.
|
||||
if (response.statusCode() != 200 && response.statusCode() != 404) {
|
||||
throw new IllegalStateException("Could not delete " + pkgname + " " + version + " from the "
|
||||
+ "pypiserver sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<String> simpleIndex(String baseUrl, String packageName) {
|
||||
String normalized = normalizePackageName(packageName);
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/simple/" + SidecarUriUtils.encodeSegment(normalized)
|
||||
|
||||
+35
-6
@@ -131,12 +131,8 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
StringBuilder path = new StringBuilder("/").append(SidecarUriUtils.encodeSegment(repositoryContainerId));
|
||||
for (String namespacePart : namespace.split("\\.", -1)) {
|
||||
path.append('/').append(SidecarUriUtils.encodeSegment(namespacePart));
|
||||
}
|
||||
path.append('/').append(SidecarUriUtils.encodeSegment(packageName)).append('/');
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path.toString()))
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
packageDirectoryPath(repositoryContainerId, namespace, packageName)))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader())
|
||||
.GET()
|
||||
@@ -152,6 +148,39 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a whole package, every version at once: a single {@code DELETE} on the group/artifact
|
||||
* directory. Confirmed against a live Reposilite container: it recursively removes everything
|
||||
* beneath that path in one call. {@link #packageExists} is checked by the caller first, since
|
||||
* Reposilite answers a confusing HTTP 500 for a {@code DELETE} on a path that was never there,
|
||||
* not a 404.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
packageDirectoryPath(repositoryContainerId, namespace, packageName)))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader())
|
||||
.DELETE()
|
||||
.build();
|
||||
HttpResponse<Void> response = send(request, BodyHandlers.discarding());
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not delete " + packageName
|
||||
+ " from the Reposilite sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
private static String packageDirectoryPath(String repositoryContainerId, String namespace, String packageName) {
|
||||
StringBuilder path = new StringBuilder("/").append(SidecarUriUtils.encodeSegment(repositoryContainerId));
|
||||
for (String namespacePart : namespace.split("\\.", -1)) {
|
||||
path.append('/').append(SidecarUriUtils.encodeSegment(namespacePart));
|
||||
}
|
||||
path.append('/').append(SidecarUriUtils.encodeSegment(packageName)).append('/');
|
||||
return path.toString();
|
||||
}
|
||||
|
||||
/** Ensures a Reposilite repository named {@code repoId} exists, creating it if not. */
|
||||
public void ensureRepository(String repoId) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
|
||||
+12
@@ -64,4 +64,16 @@ public interface RepositorySidecarManager {
|
||||
*/
|
||||
boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName);
|
||||
|
||||
/**
|
||||
* Deletes every version of the named package from this sidecar's own backing storage. Every
|
||||
* sidecar Floci currently backs (Reposilite, Verdaccio, pypiserver) can do this; the default
|
||||
* throws {@link UnsupportedOperationException} rather than silently leaving the package in place
|
||||
* or claiming a success it cannot back up, for a future format whose sidecar genuinely cannot. An
|
||||
* implementation that can delete overrides this.
|
||||
*/
|
||||
default void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
throw new UnsupportedOperationException(format() + " packages cannot be deleted through this sidecar");
|
||||
}
|
||||
}
|
||||
+30
@@ -100,6 +100,36 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
|
||||
return fetchPackageDocument(baseUrl, namespace, packageName).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a whole package, every version at once, the same way the real npm CLI's final
|
||||
* unpublish step does: fetch the packument for its current {@code _rev}, then {@code DELETE} the
|
||||
* package path with that revision appended as {@code /-rev/<rev>}. Confirmed against a live
|
||||
* Verdaccio container: a bare {@code DELETE} with no revision is not a route at all (404
|
||||
* "Cannot DELETE"), and the revisioned form removes every version and tarball in one call.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
|
||||
String revision = fetchPackageDocument(baseUrl, namespace, packageName)
|
||||
.orElseThrow(() -> new IllegalStateException(packageName + " no longer exists on the Verdaccio "
|
||||
+ "sidecar"))
|
||||
.path("_rev").asText("");
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath(namespace, packageName)
|
||||
+ "/-rev/" + SidecarUriUtils.encodeSegment(revision));
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).DELETE().build();
|
||||
HttpResponse<Void> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.discarding());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Verdaccio sidecar to delete " + packageName, e);
|
||||
}
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201) {
|
||||
throw new IllegalStateException("Could not delete " + packageName
|
||||
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/** One tarball by its filename, from a backend already made ready by {@link #ensureReady}. */
|
||||
public Optional<byte[]> fetchTarball(String baseUrl, String namespace, String packageName, String assetName) {
|
||||
HttpRequest request = tarballRequest(baseUrl, namespace, packageName, assetName);
|
||||
|
||||
Reference in new issue
Block a user