feat(codeartifact): release a deleted repository's Maven storage (#4210)

DeleteRepository never cleaned up the Reposilite-side storage of a deleted
repository; it was left behind, wasting space over a long-running process.
Reposilite has no bulk-delete endpoint, but DELETE on a path recursively
removes everything under it in one call, so this deletes each of the
repository's top-level entries before removing it from the shared settings
list, verified against a live instance. Order matters: the repository must
stay registered while its files are deleted, since Reposilite 404s every
path, including DELETE, for an id absent from its settings.

Release is best-effort: the CodeArtifact-side metadata delete already
committed by the time it runs, matching real CodeArtifact's own
DeleteRepository (synchronous, always succeeds once the repository exists).
A sidecar that is unreachable must not turn an already-successful delete
into a 500, and must not leave the repository stuck, since a retry would
just 404 against the already-deleted record.

Introduces RepositorySidecarManager, a small interface every per-format
sidecar can implement, and CodeArtifactSidecarRegistry, which discovers
implementations via CDI. CodeArtifactService.deleteRepository releases
storage generically over whatever formats a repository has sidecar ids
for, so a future format's sidecar needs no change here. Reposilite is the
first and only implementation for now; CodeArtifactRepository's
mavenRepositoryId field becomes a sidecarContainerIds map for the same
reason.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-23 22:48:03 -05:00
1 parent b986b95074
commit 94fc4c45bb
13 files changed
+561 -55

No files matched your search

@@ -101,7 +101,7 @@ public class CodeArtifactMavenController {
.orElseThrow(() -> new NotAuthorizedException("Basic realm=\"floci-codeartifact\""));
String repoId;
try {
repoId = service.ensureMavenRepositoryId(scope.region(), domain, scope.owner(), repository);
repoId = service.ensureFormatContainerId("maven", scope.region(), domain, scope.owner(), repository);
} catch (AwsException e) {
throw new NotFoundException();
}
@@ -64,6 +64,14 @@ public class CodeArtifactService implements Resettable {
private static final Set<String> PACKAGE_FORMATS =
Set.of("npm", "pypi", "maven", "nuget", "generic", "ruby", "swift", "cargo");
private static final Set<String> ENDPOINT_TYPES = Set.of("dualstack", "ipv4");
/**
* Formats served by a real package-manager-protocol proxy backed by a per-format sidecar, and
* so need an {@link #ensureFormatContainerId} entry assigned at creation. Adding the next
* format's proxy only needs a new entry here; {@link CodeArtifactRepository#getSidecarContainerIds()}
* and the backfill in {@link #ensureFormatContainerId} already handle it, including for
* repositories created before that format's proxy existed.
*/
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven");
private static final Logger LOG = Logger.getLogger(CodeArtifactService.class);
@@ -101,6 +109,7 @@ public class CodeArtifactService implements Resettable {
private final AccountAwareStorageBackend<CodeArtifactPackageVersion> packageVersions;
private final RegionResolver regionResolver;
private final EmulatorConfig config;
private final CodeArtifactSidecarRegistry sidecarRegistry;
// Asset bytes never go through the JSON/WAL-backed `packageVersions` store (see PackageAsset's
// @JsonIgnore content field): they're kept here instead, on disk in persistent/hybrid/wal mode
// or in this map in memory mode, so a publish only ever rewrites metadata.
@@ -113,7 +122,7 @@ public class CodeArtifactService implements Resettable {
@Inject
public CodeArtifactService(StorageFactory storageFactory, RegionResolver regionResolver, EmulatorConfig config,
ServiceConfigAccess serviceConfigAccess) {
ServiceConfigAccess serviceConfigAccess, CodeArtifactSidecarRegistry sidecarRegistry) {
this(
storageFactory.create("codeartifact", "codeartifact-domains.json",
new TypeReference<Map<String, CodeArtifactDomain>>() {}),
@@ -123,7 +132,8 @@ public class CodeArtifactService implements Resettable {
new TypeReference<Map<String, CodeArtifactPackageVersion>>() {}),
regionResolver, config,
"memory".equals(serviceConfigAccess.storageMode("codeartifact")),
Path.of(config.storage().persistentPath()).resolve(ASSET_STORAGE_DIR));
Path.of(config.storage().persistentPath()).resolve(ASSET_STORAGE_DIR),
sidecarRegistry);
}
/** Package-private constructor for testing. */
@@ -131,12 +141,13 @@ public class CodeArtifactService implements Resettable {
AccountAwareStorageBackend<CodeArtifactRepository> repositories,
AccountAwareStorageBackend<CodeArtifactPackageVersion> packageVersions,
RegionResolver regionResolver, EmulatorConfig config,
boolean inMemory, Path assetRoot) {
boolean inMemory, Path assetRoot, CodeArtifactSidecarRegistry sidecarRegistry) {
this.domains = domains;
this.repositories = repositories;
this.packageVersions = packageVersions;
this.regionResolver = regionResolver;
this.config = config;
this.sidecarRegistry = sidecarRegistry;
this.inMemory = inMemory;
this.assetRoot = assetRoot;
if (!inMemory) {
@@ -280,11 +291,17 @@ public class CodeArtifactService implements Resettable {
r.setUpstreams(upstreams != null ? new ArrayList<>(upstreams) : new ArrayList<>());
r.setCreatedTime(Instant.now().getEpochSecond());
r.setTags(validateTags(tags, Map.of(), repository, "repository"));
// A bare UUID, not a domain/repository-derived name: Reposilite rejects any repository id
// over 64 characters, and CodeArtifact domain (max 50) and repository (max 100) names can
// easily exceed that combined. The id is purely internal and never surfaced by the public
// API, so readability doesn't matter here, only fitting the limit and staying unique.
r.setMavenRepositoryId(newRevision());
// A bare UUID per container-backed format, not a domain/repository-derived name:
// Reposilite rejects any repository id over 64 characters, and CodeArtifact domain (max
// 50) and repository (max 100) names can easily exceed that combined. Each id is purely
// internal and never surfaced by the public API, so readability doesn't matter here, only
// fitting the limit and staying unique per creation, so a repository deleted and recreated
// under the same name never inherits the previous one's sidecar-side content.
Map<String, String> sidecarContainerIds = new LinkedHashMap<>();
for (String format : CONTAINER_BACKED_FORMATS) {
sidecarContainerIds.put(format, newRevision());
}
r.setSidecarContainerIds(sidecarContainerIds);
repositories.putForAccount(owner, key, r);
return r;
}
@@ -296,6 +313,25 @@ public class CodeArtifactService implements Resettable {
String key = repositoryKey(region, domain, repository);
CodeArtifactRepository r = requireRepository(owner, key, repository);
repositories.deleteForAccount(owner, key);
// Generic over whatever formats this repository actually has sidecar ids for: adding the
// next format's sidecar needs no change here, only a new RepositorySidecarManager
// implementation that CodeArtifactSidecarRegistry discovers.
//
// Best-effort: the metadata delete above already committed, matching real CodeArtifact's
// own DeleteRepository (synchronous and always succeeds once the repository exists; actual
// content cleanup is an internal detail never exposed to the caller). A sidecar that is
// unreachable when this runs must not turn an already-successful delete into a 500, and
// must not leave the repository stuck: a retry would just 404, since the record above is
// already gone.
r.getSidecarContainerIds().forEach((format, containerId) ->
sidecarRegistry.forFormat(format).ifPresent(manager -> {
try {
manager.release(containerId);
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to release {0} sidecar storage for repository {1}/{2}: {3}",
format, domain, repository, e.getMessage());
}
}));
return r;
}
@@ -307,21 +343,27 @@ public class CodeArtifactService implements Resettable {
}
/**
* {@code mavenRepositoryId} is assigned at {@link #createRepository}, but a repository
* persisted before that field existed has none; backfills it lazily on first Maven-format use
* rather than leaving every caller of {@link CodeArtifactRepository#getMavenRepositoryId()} to
* handle a null it can otherwise never see.
* A sidecar container id for one format is assigned at {@link #createRepository}, but a
* repository persisted before that format's proxy existed has none; backfills it lazily on
* first use of that format rather than leaving every caller handle a missing entry it can
* otherwise never see. {@code format} is expected to be one of
* {@link #CONTAINER_BACKED_FORMATS}, though nothing here enforces that: an unlisted format
* simply gets its own id assigned the same way.
*/
public synchronized String ensureMavenRepositoryId(String region, String domain, String domainOwner,
String repository) {
public synchronized String ensureFormatContainerId(String format, String region, String domain,
String domainOwner, String repository) {
String owner = effectiveOwner(domainOwner);
String key = repositoryKey(region, domain, repository);
CodeArtifactRepository r = requireRepository(owner, key, repository);
if (r.getMavenRepositoryId() == null) {
r.setMavenRepositoryId(newRevision());
String id = r.getSidecarContainerIds().get(format);
if (id == null) {
id = newRevision();
Map<String, String> sidecarContainerIds = new LinkedHashMap<>(r.getSidecarContainerIds());
sidecarContainerIds.put(format, id);
r.setSidecarContainerIds(sidecarContainerIds);
repositories.putForAccount(owner, key, r);
}
return r.getMavenRepositoryId();
return id;
}
public synchronized CodeArtifactRepository updateRepository(String region, String domain, String domainOwner,
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.codeartifact;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Maps a CodeArtifact package format to the {@link RepositorySidecarManager} that serves it.
* {@link CodeArtifactService} consults this to clean up a deleted repository's sidecar containers
* without knowing which formats exist or which sidecar backs any of them.
*/
@ApplicationScoped
public class CodeArtifactSidecarRegistry {
private final Map<String, RepositorySidecarManager> byFormat = new HashMap<>();
@Inject
public CodeArtifactSidecarRegistry(Instance<RepositorySidecarManager> managers) {
managers.forEach(this::register);
}
/** Factory constructor: build a registry from an explicit list, bypassing CDI (tests). */
public CodeArtifactSidecarRegistry(Collection<RepositorySidecarManager> managers) {
managers.forEach(this::register);
}
private void register(RepositorySidecarManager manager) {
RepositorySidecarManager existing = byFormat.put(manager.format(), manager);
if (existing != null) {
throw new IllegalStateException("Duplicate CodeArtifact sidecar manager for format "
+ manager.format() + ": " + existing.getClass().getSimpleName() + " and "
+ manager.getClass().getSimpleName());
}
}
public Optional<RepositorySidecarManager> forFormat(String format) {
return Optional.ofNullable(byFormat.get(format));
}
}
@@ -21,10 +21,14 @@ import java.util.Optional;
/**
* HTTP client for the shared Reposilite sidecar. A CodeArtifact repository maps to a named
* Reposilite repository ({@link #ensureRepository}), provisioned lazily via Reposilite's
* {@code maven} settings domain, which hot-reloads without a restart.
* {@code maven} settings domain, which hot-reloads without a restart. Implements
* {@link RepositorySidecarManager} so {@code CodeArtifactService} can release a deleted
* repository's Maven storage the same generic way it releases any other format's.
*/
@ApplicationScoped
public class ReposiliteSidecarClient {
public class ReposiliteSidecarClient implements RepositorySidecarManager {
private static final String FORMAT = "maven";
private static final Logger LOG = Logger.getLogger(ReposiliteSidecarClient.class);
private static final String MAVEN_SETTINGS_PATH = "/api/settings/domain/maven";
private static final int REPOSITORY_READY_POLL_MAX_MS = 3_000;
@@ -54,6 +58,26 @@ public class ReposiliteSidecarClient {
this.httpClient = httpClient;
}
@Override
public String format() {
return FORMAT;
}
/**
* {@code publicUrl} is unused: unlike npm's package metadata, Maven's wire protocol has no
* self-referential URLs to rewrite, so there is nothing here for it to do.
*/
@Override
public String ensureReady(String repositoryContainerId, String publicUrl) {
ensureRepository(repositoryContainerId);
return manager.ensureReady();
}
@Override
public void release(String repositoryContainerId) {
releaseRepository(repositoryContainerId);
}
/** Ensures a Reposilite repository named {@code repoId} exists, creating it if not. */
public void ensureRepository(String repoId) {
String baseUrl = manager.ensureReady();
@@ -124,6 +148,91 @@ public class ReposiliteSidecarClient {
return !message.startsWith("Repository ");
}
/**
* Deletes every file {@code repoId} holds, then removes it from the shared settings list.
* Reposilite has no bulk-delete endpoint (checked against its documented REST API); DELETE on
* a path recursively removes everything under it in one call, though, so this only needs one
* DELETE per top-level entry (a repository's group-id first segments, typically a handful)
* rather than walking the whole artifact tree. A repository never used through Maven has
* nothing registered on the Reposilite side at all; that is a no-op here, not an error.
*
* <p>Order matters: the repository must still be registered while its files are deleted,
* since Reposilite 404s every path, including DELETE, for a repository ID absent from its
* settings (confirmed against a live instance). Removing it from settings first would leave
* its files permanently unreachable instead of actually freeing the storage.
*
* <p>Checks {@link ReposiliteSidecarManager#isStarted()} first: every CodeArtifact repository
* gets a Maven sidecar id at creation regardless of whether it is ever actually used through
* Maven, so without this check, deleting any repository at all would start the shared
* container just to look for content that was never there. Reposilite keeps no volume, so a
* sidecar that was never started could not possibly hold anything for {@code repoId} to
* release.
*/
public void releaseRepository(String repoId) {
if (!manager.isStarted()) {
return;
}
String baseUrl = manager.ensureReady();
synchronized (provisioningLock) {
for (JsonNode entry : topLevelEntries(baseUrl, repoId)) {
deleteEntry(baseUrl, repoId, entry.path("name").asText());
}
ArrayNode repositories = currentRepositories(baseUrl);
ArrayNode remaining = mapper.createArrayNode();
for (JsonNode repository : repositories) {
if (!repoId.equals(repository.path("id").asText())) {
remaining.add(repository);
}
}
if (remaining.size() != repositories.size()) {
putMavenSettings(baseUrl, remaining);
LOG.infov("Released Reposilite repository {0}", repoId);
}
}
}
private ArrayNode topLevelEntries(String baseUrl, String repoId) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/api/maven/details/" + repoId))
.timeout(Duration.ofSeconds(10))
.header("Authorization", manager.basicAuthHeader())
.GET()
.build();
HttpResponse<String> response = send(request, BodyHandlers.ofString());
if (response.statusCode() == 404) {
// Never provisioned (no Maven use before this CodeArtifact repository was deleted):
// nothing on the Reposilite side to clean up.
return mapper.createArrayNode();
}
if (response.statusCode() != 200) {
// Anything other than a clean 404 means the repository's actual state here is
// unknown, not "nothing to clean up": proceeding to remove the settings entry anyway
// would orphan whatever this call never got to see, unreachable through the API
// afterward the same way the 404-ordering bug this method exists to avoid would.
// Propagating lets the caller's best-effort handling decide, rather than silently
// treating an error as an empty repository.
throw new IllegalStateException("Failed to list " + repoId + " on Reposilite before release: HTTP "
+ response.statusCode());
}
JsonNode details = readTree(response.body());
return details.path("files").isArray() ? ((ArrayNode) details.path("files")).deepCopy()
: mapper.createArrayNode();
}
private void deleteEntry(String baseUrl, String repoId, String entryName) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/" + repoId + "/" + entryName))
.timeout(Duration.ofSeconds(30))
.header("Authorization", manager.basicAuthHeader())
.DELETE()
.build();
HttpResponse<Void> response = send(request, BodyHandlers.discarding());
if (response.statusCode() != 200) {
throw new IllegalStateException("Failed to delete " + repoId + "/" + entryName
+ " from Reposilite: HTTP " + response.statusCode());
}
}
/** Deploys {@code content} to {@code repoId}'s {@code gav} path, returning the HTTP status. */
public int deployArtifact(String repoId, String gav, byte[] content) {
String baseUrl = manager.ensureReady();
@@ -70,6 +70,26 @@ public class ReposiliteSidecarManager {
this.managedSecret = managedSecret;
}
/**
* Whether there could possibly be anything on the Reposilite side to release: either
* {@link #ensureReady()} has already resolved an endpoint in this process, or
* {@code FLOCI_SERVICES_CODEARTIFACT_MAVEN_URL} names an external instance this process has
* simply not talked to yet. Never starts anything itself, unlike {@link #ensureReady()}.
*
* <p>The two cases are not the same guarantee. A managed container keeps no volume, so one
* that was never started this process could not hold anything, full stop. An external,
* pre-configured instance's lifecycle is independent of this process's {@code resolvedUrl}: it
* may already hold real data from an earlier Floci run, so "this process has not resolved it
* yet" must not be read as "nothing is there" the way it can for the managed case.
*/
public boolean isStarted() {
if (resolvedUrl != null) {
return true;
}
Optional<String> configuredUrl = config.services().codeartifact().mavenUrl();
return configuredUrl.isPresent() && !configuredUrl.get().isBlank();
}
/** Base URL of a ready Reposilite instance, starting the managed container if needed. */
public synchronized String ensureReady() {
if (resolvedUrl != null) {
@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.services.codeartifact;
/**
* Common contract for a CodeArtifact sidecar backing one package format: get one repository ready
* to serve that format, and release whatever backing storage it holds once the repository is
* deleted. Implementations are discovered via CDI by {@link CodeArtifactSidecarRegistry}, so
* adding the next format's sidecar (npm, pypi, nuget) needs no change to
* {@link CodeArtifactService} or any other format's manager.
*
* <p>Named around the effect ("release this repository's backing storage"), not the mechanism,
* because the mechanism is expected to differ per sidecar. {@code ReposiliteSidecarClient}, the
* first implementation, deletes files and removes one entry from a settings list shared by every
* maven repository in a single Reposilite instance; a future format whose sidecar runs one
* container per repository would instead stop and remove that container. Both are legitimate
* implementations of the same contract even though neither necessarily "stops a container" the
* way the other might.
*/
public interface RepositorySidecarManager {
/** The CodeArtifact package format this sidecar backs, e.g. {@code "maven"}. */
String format();
/**
* Base URL of a ready backend for {@code repositoryContainerId}, provisioning it if this is
* the first use.
*
* @param publicUrl the externally reachable proxy URL for this specific repository, passed
* through so any self-referential URLs the sidecar returns in its own
* protocol responses point back through Floci instead of an internal,
* client-unreachable address. Not every sidecar's protocol has this problem
* (Maven's does not); an implementation that doesn't need it ignores it.
*/
String ensureReady(String repositoryContainerId, String publicUrl);
/**
* Releases the backing storage for one repository (deletes its files, edits a shared settings
* list, stops a container, whatever this sidecar's own shape requires) so a later repository
* created under the same name never inherits it. A repository that never actually used this
* format is a no-op, not an error.
*/
void release(String repositoryContainerId);
}
@@ -26,11 +26,14 @@ public class CodeArtifactRepository {
private String policyDocument;
private String policyRevision;
/**
* The Reposilite repository backing this repository's {@code maven} format, unique per
* creation so a deleted-and-recreated repository of the same name never inherits a previous
* repository's leftover artifacts. Internal; never surfaced in the public API response.
* The sidecar-backed id for each package format this repository has been used through (keyed
* by format name, e.g. {@code "maven"}), unique per creation so a deleted-and-recreated
* repository of the same name never inherits a previous repository's leftover artifacts for
* that format. What the id actually names depends on the format's sidecar shape: a Reposilite
* repository name for {@code maven} (one shared container, many named repositories inside
* it). Internal; never surfaced in the public API response.
*/
private String mavenRepositoryId;
private Map<String, String> sidecarContainerIds = new LinkedHashMap<>();
public String getName() {
return name;
@@ -136,11 +139,11 @@ public class CodeArtifactRepository {
this.policyRevision = policyRevision;
}
public String getMavenRepositoryId() {
return mavenRepositoryId;
public Map<String, String> getSidecarContainerIds() {
return Collections.unmodifiableMap(sidecarContainerIds);
}
public void setMavenRepositoryId(String mavenRepositoryId) {
this.mavenRepositoryId = mavenRepositoryId;
public void setSidecarContainerIds(Map<String, String> sidecarContainerIds) {
this.sidecarContainerIds = sidecarContainerIds;
}
}