mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codeartifact): bridge CopyPackageVersions to every sidecar format (#5888)
CopyPackageVersions only covered the generic format; maven, npm, pypi, and nuget each publish straight to their own sidecar and keep no packageVersions record this action could read from or write to. Bridges all four, each confirmed live against a real container: maven reuses Reposilite's existing mvn-deploy write path, while npm/pypi/nuget each speak their own real wire protocol directly (Verdaccio's packument PUT, pypiserver's twine-shaped multipart upload, and BaGetter's NuGet push), the same protocol each format's own data-plane proxy already forwards unmodified for a native client. CopyPackageVersions now supports every format CodeArtifact does, matching real AWS, which places no format restriction on this action at all. An overwrite deletes a conflicting existing asset immediately before rewriting it for every format, since each sidecar rejects a plain overwrite of differing content; a best-effort compensating cleanup restores or removes whatever one version's write itself touched if a later step in that same version fails, preserving the original error. A copied Maven version is also merged into the destination's maven-metadata.xml so real clients can discover it, and copied bytes feed the same byte-accounting mechanism native publishes already use. A copied npm or pypi version's readme is propagated from this service's own captured-at-publish-time record, since neither sidecar can answer for one after the fact. The synthesized revision for every container-backed format is truncated to fit versionRevisions' own 50-character limit, so a revision obtained from DescribePackageVersion can be handed straight back into a revision-pinned copy. Also closes a cross-version batch-write gap: source assets are verified against the real sidecar before any destination write in the same batch, the same split the generic path already uses. Fixes two more real-sidecar quirks found on review: pypiserver's own delete call removes every file sharing a release's exact name and version, not just the one asset name it was asked to delete, so a release carrying both an sdist and a wheel lost one of them on overwrite when assets were deleted one at a time, interleaved with the writes. Every destination asset a version already holds is now deleted up front, in its own phase, before any new content is written, which changes nothing for Maven/npm/nuget since their own deletes are already scoped to exactly the asset (or, for npm/nuget, the single asset a version ever holds) being removed. An npm copy also used to rebuild a minimal version document from scratch, dropping dependencies and anything else npm's own protocol carries beyond dist; it now reuses the source's own version entry verbatim, with only dist itself rewritten to point at the copy.
This commit is contained in:
1 parent
c17bd49096
commit
5dcddc9dfa
14 files changed
+2124
-46
No files matched your search
@@ -19,9 +19,14 @@ public final class Digests {
|
||||
}
|
||||
}
|
||||
|
||||
/** The SHA-1 digest of {@code data} as lowercase hex. */
|
||||
public static String sha1Hex(byte[] data) {
|
||||
return HexFormat.of().formatHex(sha1(data));
|
||||
}
|
||||
|
||||
/** The SHA-1 digest of the UTF-8 bytes of {@code text} as lowercase hex. */
|
||||
public static String sha1Hex(String text) {
|
||||
return HexFormat.of().formatHex(sha1(text.getBytes(StandardCharsets.UTF_8)));
|
||||
return sha1Hex(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static byte[] sha256(byte[] data) {
|
||||
|
||||
+103
@@ -8,6 +8,7 @@ import jakarta.inject.Inject;
|
||||
import java.net.URI;
|
||||
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;
|
||||
@@ -153,6 +154,108 @@ public class BagetterSidecarClient implements RepositorySidecarManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* NuGet's one asset per version is deterministically named (AWS's own normalization rule,
|
||||
* already relied on by {@link #fetchPackageVersionAsset}), so enumerating it for {@code
|
||||
* CopyPackageVersions} needs only confirm the version exists and name it the same way; empty
|
||||
* when it doesn't.
|
||||
*/
|
||||
@Override
|
||||
public List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
String lowerId = packageName.toLowerCase(Locale.ROOT);
|
||||
Optional<String> normalizedVersion = matchVersion(repositoryContainerId, lowerId, version);
|
||||
return normalizedVersion.map(v -> List.of(lowerId + "." + v + ".nupkg")).orElse(List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes {@code content} (the whole {@code .nupkg}, NuGet's one asset per version) through
|
||||
* the real push wire shape {@code CodeArtifactNuGetController#push} already forwards
|
||||
* unmodified, confirmed against a live BaGetter container: a {@code multipart/form-data}
|
||||
* {@code PUT} to {@code /api/v2/package} whose first (only, here) part is the raw package
|
||||
* bytes — no separate {@code name}/{@code version} form field, since BaGetter reads both from
|
||||
* the {@code .nuspec} embedded in the package itself, not from {@code assetName} or this
|
||||
* method's own {@code packageName}/{@code version} parameters.
|
||||
*
|
||||
* <p>Rejected outright with a real {@code 409} ("a package with this id and version already
|
||||
* exists") if this exact id/version already exists, confirmed live, even for byte-identical
|
||||
* content: unlike Maven's Reposilite, BaGetter has no idempotent-retry short-circuit of its
|
||||
* own ({@code CodeArtifactNuGetController#push} does its own pre-check precisely because of
|
||||
* this). The caller ({@code CodeArtifactService#copyContainerBackedPackageVersions}) already
|
||||
* short-circuits an identical-content version as a no-op before ever reaching here, and is
|
||||
* expected to have deleted a conflicting, differing existing version first for a genuine
|
||||
* overwrite, the same reason {@code ReposiliteSidecarClient#storePackageVersionAsset}
|
||||
* documents for Maven.
|
||||
*
|
||||
* <p>Runs inside {@link #lockFor}, the same lock {@link #deletePackage} and {@code
|
||||
* CodeArtifactNuGetController#push} both already take for this repository: without it, a
|
||||
* native push racing this exact id/version could interleave with this call's own write.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
String boundary = "flociNuGetCopyBoundary" + System.nanoTime();
|
||||
byte[] head = ("--" + boundary + "\r\n"
|
||||
+ "Content-Disposition: form-data; name=\"package\"; filename=\"" + assetName + "\"\r\n"
|
||||
+ "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8);
|
||||
byte[] tail = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8);
|
||||
byte[] body = new byte[head.length + content.length + tail.length];
|
||||
System.arraycopy(head, 0, body, 0, head.length);
|
||||
System.arraycopy(content, 0, body, head.length, content.length);
|
||||
System.arraycopy(tail, 0, body, head.length + content.length, tail.length);
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
"/api/v2/package"))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
|
||||
.PUT(BodyPublishers.ofByteArray(body))
|
||||
.build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the BaGetter sidecar to push " + assetName, e);
|
||||
}
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 202) {
|
||||
throw new IllegalStateException("Could not push " + assetName + " to the BaGetter sidecar: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the one version this asset belongs to, confirmed against a live container: NuGet
|
||||
* has exactly one asset per version, so there is no finer grain to delete at than {@link
|
||||
* #deletePackage}'s own per-version {@code DELETE /api/v2/package/<id>/<version>} already
|
||||
* uses. Runs inside the same {@link #lockFor} lock {@link #storePackageVersionAsset} and
|
||||
* {@link #deletePackage} both take, for the same reason.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
String lowerId = packageName.toLowerCase(Locale.ROOT);
|
||||
String normalizedVersion = NuGetVersions.normalize(version);
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/api/v2/package/"
|
||||
+ SidecarUriUtils.encodeSegment(lowerId) + "/" + SidecarUriUtils.encodeSegment(normalizedVersion));
|
||||
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 BaGetter sidecar to delete " + packageName
|
||||
+ " " + version + "'s asset " + assetName, e);
|
||||
}
|
||||
if (response.statusCode() != 204 && response.statusCode() != 404) {
|
||||
throw new IllegalStateException("Could not delete " + packageName + " " + version + "'s asset "
|
||||
+ assetName + " from the BaGetter sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock {@link #deletePackage} and {@code CodeArtifactNuGetController}'s own push handler
|
||||
* both take for one repository, so a push and a delete for the same repository can never
|
||||
|
||||
+344
-21
@@ -38,6 +38,7 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
@@ -1202,23 +1203,39 @@ public class CodeArtifactService implements Resettable {
|
||||
* revision would: nothing before this helper existed ever let a client obtain a revision for
|
||||
* these formats in the first place (not even a stale one), so this isn't a regression against
|
||||
* any previously working staleness check.
|
||||
*
|
||||
* <p>Truncated to {@link #MAX_REVISION_LENGTH} (50) hex characters of the full SHA-256 digest,
|
||||
* not the full 64: {@code CopyPackageVersions}' own {@code versionRevisions} value is
|
||||
* wire-model-capped at 50 characters, so a revision this helper hands out through {@code
|
||||
* DescribePackageVersion}/{@code GetPackageVersionAsset} must itself fit back into that field
|
||||
* or a caller could never round-trip it through a revision-pinned copy. 50 hex characters
|
||||
* (200 bits) is still astronomically collision-resistant for distinguishing the handful of
|
||||
* live repository/namespace/package/version coordinates this emulator ever holds at once.
|
||||
*/
|
||||
private static String synthesizeContainerBackedRevision(String repoId, String namespace, String packageName,
|
||||
String version) {
|
||||
String revisionKey = repoId + "/" + (namespace == null ? "" : namespace) + "/" + packageName + "/" + version;
|
||||
return Digests.sha256Hex(revisionKey.getBytes(StandardCharsets.UTF_8));
|
||||
return Digests.sha256Hex(revisionKey.getBytes(StandardCharsets.UTF_8)).substring(0, MAX_REVISION_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies one or more versions of a package from one repository to another in the same
|
||||
* domain. Only {@code generic} is supported today — unlike real AWS, which does not
|
||||
* restrict this action's {@code format} the way it restricts {@link #publishPackageVersion}'s
|
||||
* to {@code generic} alone (confirmed against the wire model: {@code
|
||||
* CopyPackageVersionsRequest.format}'s own doc carries no such restriction). This is a Floci
|
||||
* implementation gap, not an AWS restriction being mirrored: Maven, npm, pypi, and nuget
|
||||
* publish straight to their own sidecar and keep no {@code packageVersions} record this could
|
||||
* read from or write to, so bridging them needs the same per-sidecar fetch-then-republish
|
||||
* shape {@code GetPackageVersionAsset}'s own bridge already uses, not yet built here.
|
||||
* domain, for every format CodeArtifact supports: {@code generic} through its own {@code
|
||||
* packageVersions} store, and {@code maven}/{@code npm}/{@code pypi}/{@code nuget} bridged to
|
||||
* their own sidecar (see {@link #copyContainerBackedPackageVersions}). Matches real AWS,
|
||||
* which does not restrict this action's {@code format} the way it restricts {@link
|
||||
* #publishPackageVersion}'s to {@code generic} alone (confirmed against the wire model:
|
||||
* {@code CopyPackageVersionsRequest.format}'s own doc carries no such restriction) — every
|
||||
* container-backed format publishes straight to its own sidecar and keeps no {@code
|
||||
* packageVersions} record this could otherwise read from or write to, so each needed the
|
||||
* same per-sidecar fetch-then-republish shape {@code GetPackageVersionAsset}'s own bridge
|
||||
* already uses, built on each sidecar's own real wire protocol and confirmed live against a
|
||||
* real container for every one of the four: {@code ReposiliteSidecarClient} reuses the write
|
||||
* path {@link CodeArtifactMavenController}'s own {@code mvn deploy} passthrough already
|
||||
* proved; {@code VerdaccioSidecarClient}, {@code PypiserverSidecarClient}, and {@code
|
||||
* BagetterSidecarClient} each speak the real {@code npm publish}/{@code twine upload}/{@code
|
||||
* nuget push} wire shape directly, the same one their own data-plane proxies already forward
|
||||
* unmodified for a native client.
|
||||
*
|
||||
* <p>Confirmed against the CodeArtifact User Guide's own worked examples ("Copy package
|
||||
* versions"), not assumed from the shared {@code PackageVersionError} error-code enum alone,
|
||||
@@ -1253,26 +1270,31 @@ public class CodeArtifactService implements Resettable {
|
||||
* has no upstream-ingestion path for any format (see {@code docs/services/codeartifact.md}'s
|
||||
* Known limitations), so there is never a separate upstream repository to also search.
|
||||
*
|
||||
* <p>A freshly copied version gets a new revision of its own ({@link #newRevision()}, never
|
||||
* the source's): the User Guide's own definition of "package version revision" is explicit
|
||||
* that "each time a package version is updated, a new package version revision is created,"
|
||||
* and landing a version in a repository it previously had no record in is such an update at
|
||||
* the destination — the same reason {@link #publishPackageVersion} always mints its own rather
|
||||
* than ever accepting a caller-supplied one. An identical-content no-op (see above) is
|
||||
* correctly the opposite case: nothing was updated at the destination, so its existing
|
||||
* revision, whatever it already was, is left untouched.
|
||||
* <p>For {@code generic}, a freshly copied version gets a new revision of its own ({@link
|
||||
* #newRevision()}, never the source's): the User Guide's own definition of "package version
|
||||
* revision" is explicit that "each time a package version is updated, a new package version
|
||||
* revision is created," and landing a version in a repository it previously had no record in
|
||||
* is such an update at the destination — the same reason {@link #publishPackageVersion}
|
||||
* always mints its own rather than ever accepting a caller-supplied one. An identical-content
|
||||
* no-op (see above) is correctly the opposite case: nothing was updated at the destination, so
|
||||
* its existing revision, whatever it already was, is left untouched. {@code maven}'s
|
||||
* destination revision is instead {@link #synthesizeContainerBackedRevision}'s own stable,
|
||||
* coordinate-derived value, the same one {@link #describeContainerBackedPackageVersion} and
|
||||
* {@link #getContainerBackedPackageVersionAsset} already return for it: there is no
|
||||
* "revision changes on update" concept for a container-backed format at all, an existing,
|
||||
* documented simplification this does not invent a new exception to.
|
||||
*
|
||||
* <p>{@code synchronized} for the same reason every other package-mutating method here is: a
|
||||
* concurrent publish or delete on either repository must never interleave with this method's
|
||||
* own read-then-write of the destination's {@code packageVersions} record.
|
||||
* own read-then-write of the destination's {@code packageVersions} record, or, for {@code
|
||||
* maven}, its sidecar's own backing storage.
|
||||
*/
|
||||
public synchronized CopyPackageVersionsResult copyPackageVersions(String region, String domain,
|
||||
String domainOwner, String sourceRepository, String destinationRepository, String format,
|
||||
String namespace, String packageName, List<String> versions, Map<String, String> versionRevisions,
|
||||
boolean allowOverwrite, boolean includeFromUpstream) {
|
||||
if (!"generic".equals(format)) {
|
||||
throw validation("format must be 'generic'; CopyPackageVersions only supports the generic package "
|
||||
+ "format.");
|
||||
if (!"generic".equals(format) && !CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
throw validation("format must be 'generic', 'maven', 'npm', 'pypi', or 'nuget'.");
|
||||
}
|
||||
boolean hasVersions = versions != null && !versions.isEmpty();
|
||||
boolean hasRevisions = versionRevisions != null && !versionRevisions.isEmpty();
|
||||
@@ -1323,6 +1345,12 @@ public class CodeArtifactService implements Resettable {
|
||||
// is part of this action's documented error list (so it's a real possible response), but
|
||||
// this codebase has no confirmed trigger for it on this action and does not guess one.
|
||||
|
||||
if (CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
return copyContainerBackedPackageVersions(region, domain, owner, sourceRepository,
|
||||
destinationRepository, format, namespace, packageName, requestedVersions, versionRevisions,
|
||||
hasRevisions, allowOverwrite);
|
||||
}
|
||||
|
||||
Map<String, PackageVersionCopyFailure> failures = new LinkedHashMap<>();
|
||||
List<String> pendingCopies = new ArrayList<>();
|
||||
Map<String, CodeArtifactPackageVersion> sourceByVersion = new LinkedHashMap<>();
|
||||
@@ -1393,6 +1421,301 @@ public class CodeArtifactService implements Resettable {
|
||||
return new CopyPackageVersionsResult(successes, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #copyPackageVersions}'s bridge for a container-backed format: the same NOT_FOUND /
|
||||
* MISMATCHED_REVISION / identical-content-no-op / ALREADY_EXISTS / all-or-nothing-SKIPPED
|
||||
* semantics as the {@code generic} path, built on the sidecar primitives {@link
|
||||
* RepositorySidecarManager#listPackageVersionAssetNames}, {@link
|
||||
* RepositorySidecarManager#fetchPackageVersionAsset}, {@link
|
||||
* RepositorySidecarManager#storePackageVersionAsset}, and {@link
|
||||
* RepositorySidecarManager#deletePackageVersionAsset} instead of the generic path's own {@code
|
||||
* packageVersions} store. {@code requestedVersions} and {@code hasRevisions} are the caller's
|
||||
* own already-validated, already-deduplicated values, not recomputed here.
|
||||
*
|
||||
* <p>Every container-backed format's {@link RepositorySidecarManager} overrides all four of
|
||||
* these today. A future format whose sidecar manager does not would have its default throw
|
||||
* {@link UnsupportedOperationException} from the first one reached, caught here and turned
|
||||
* into a real, if deliberately blunt, {@code InternalServerException}: the same convention
|
||||
* {@link #deleteContainerBackedPackageIfPresent} already uses for a sidecar capability not
|
||||
* yet built, rather than a silent no-op or an unhandled 500.
|
||||
*
|
||||
* <p>There is no persisted hash to re-verify a container-backed asset's bytes against the way
|
||||
* {@link #verifyAndReadSourceAssets} does for generic, so this only confirms an asset {@link
|
||||
* RepositorySidecarManager#listPackageVersionAssetNames} just reported is still fetchable
|
||||
* immediately afterward, failing the whole batch with {@code InternalServerException} if not
|
||||
* (the same storage-integrity failure {@link #verifyAndReadSourceAssets} reports, just without
|
||||
* a hash to compare).
|
||||
*
|
||||
* <p>{@code hasRevisions} can succeed here the same as for {@code generic}: {@link
|
||||
* #synthesizeContainerBackedRevision} is truncated to {@link #MAX_REVISION_LENGTH} (50)
|
||||
* characters specifically so a revision a caller obtained from {@code
|
||||
* DescribePackageVersion}/{@code GetPackageVersionAsset} always fits back into {@code
|
||||
* versionRevisions}' own 1-50 character value constraint and compares equal when it is in
|
||||
* fact the current one.
|
||||
*/
|
||||
private CopyPackageVersionsResult copyContainerBackedPackageVersions(String region, String domain, String owner,
|
||||
String sourceRepository, String destinationRepository, String format, String namespace,
|
||||
String packageName, List<String> requestedVersions, Map<String, String> versionRevisions,
|
||||
boolean hasRevisions, boolean allowOverwrite) {
|
||||
RepositorySidecarManager manager = sidecarRegistry.forFormat(format)
|
||||
.orElseThrow(() -> new AwsException("InternalServerException", "Copying a " + format
|
||||
+ " package version is not yet supported by this emulator.", 500));
|
||||
String sourceRepoId = ensureFormatContainerId(format, region, domain, owner, sourceRepository);
|
||||
String destRepoId = ensureFormatContainerId(format, region, domain, owner, destinationRepository);
|
||||
|
||||
Map<String, PackageVersionCopyFailure> failures = new LinkedHashMap<>();
|
||||
List<String> pendingCopies = new ArrayList<>();
|
||||
Map<String, List<String>> sourceAssetNamesByVersion = new LinkedHashMap<>();
|
||||
Map<String, List<String>> destAssetNamesByVersion = new LinkedHashMap<>();
|
||||
try {
|
||||
for (String version : requestedVersions) {
|
||||
if (!manager.packageVersionExists(sourceRepoId, domain, sourceRepository, namespace, packageName,
|
||||
version)) {
|
||||
failures.put(version, new PackageVersionCopyFailure("NOT_FOUND", "Could not find version "
|
||||
+ version));
|
||||
continue;
|
||||
}
|
||||
if (hasRevisions) {
|
||||
String expectedRevision = versionRevisions.get(version);
|
||||
String actualRevision = synthesizeContainerBackedRevision(sourceRepoId, namespace, packageName,
|
||||
version);
|
||||
if (!actualRevision.equals(expectedRevision)) {
|
||||
failures.put(version, new PackageVersionCopyFailure("MISMATCHED_REVISION",
|
||||
"current revision: " + actualRevision + ", expected revision: "
|
||||
+ expectedRevision));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
List<String> sourceAssetNames = manager.listPackageVersionAssetNames(sourceRepoId, domain,
|
||||
sourceRepository, namespace, packageName, version);
|
||||
boolean destExists = manager.packageVersionExists(destRepoId, domain, destinationRepository,
|
||||
namespace, packageName, version);
|
||||
if (destExists) {
|
||||
List<String> destAssetNames = manager.listPackageVersionAssetNames(destRepoId, domain,
|
||||
destinationRepository, namespace, packageName, version);
|
||||
if (containerBackedVersionContentMatches(manager, sourceRepoId, sourceRepository, destRepoId,
|
||||
destinationRepository, domain, namespace, packageName, version, sourceAssetNames,
|
||||
destAssetNames)) {
|
||||
// Identical in both repositories already: the same already-successful,
|
||||
// not-listed-anywhere no-op the generic path applies (see
|
||||
// #copyPackageVersions's own javadoc).
|
||||
continue;
|
||||
}
|
||||
if (!allowOverwrite) {
|
||||
failures.put(version, new PackageVersionCopyFailure("ALREADY_EXISTS",
|
||||
"Version " + version + " already exists"));
|
||||
continue;
|
||||
}
|
||||
destAssetNamesByVersion.put(version, destAssetNames);
|
||||
}
|
||||
sourceAssetNamesByVersion.put(version, sourceAssetNames);
|
||||
pendingCopies.add(version);
|
||||
}
|
||||
} catch (UnsupportedOperationException e) {
|
||||
throw new AwsException("InternalServerException", "Copying a " + format + " package version is not "
|
||||
+ "yet supported by this emulator.", 500);
|
||||
}
|
||||
|
||||
if (!failures.isEmpty()) {
|
||||
for (String version : pendingCopies) {
|
||||
failures.put(version, new PackageVersionCopyFailure("SKIPPED", "Version " + version
|
||||
+ " was skipped"));
|
||||
}
|
||||
return new CopyPackageVersionsResult(Map.of(), failures);
|
||||
}
|
||||
|
||||
// Same verify-before-write ordering as the generic path's own two-pass split: every
|
||||
// pending version's source assets are fetched and confirmed present before any version in
|
||||
// this batch has anything written to the destination.
|
||||
Map<String, Map<String, byte[]>> verifiedContentByVersion = new LinkedHashMap<>();
|
||||
for (String version : pendingCopies) {
|
||||
Map<String, byte[]> contentByAsset = new LinkedHashMap<>();
|
||||
for (String assetName : sourceAssetNamesByVersion.get(version)) {
|
||||
byte[] content = manager.fetchPackageVersionAsset(sourceRepoId, domain, sourceRepository, namespace,
|
||||
packageName, version, assetName)
|
||||
.orElseThrow(() -> new AwsException("InternalServerException", "Could not copy version '"
|
||||
+ version + "' of package '" + packageName + "': its asset '" + assetName
|
||||
+ "' disappeared from the source repository between listing and fetching it.",
|
||||
500));
|
||||
contentByAsset.put(assetName, content);
|
||||
}
|
||||
verifiedContentByVersion.put(version, contentByAsset);
|
||||
}
|
||||
|
||||
Map<String, PackageVersionCopyOutcome> successes = new LinkedHashMap<>();
|
||||
for (String version : pendingCopies) {
|
||||
List<String> destAssetNames = destAssetNamesByVersion.getOrDefault(version, List.of());
|
||||
Map<String, byte[]> originalContent = new LinkedHashMap<>();
|
||||
for (String destAssetName : destAssetNames) {
|
||||
manager.fetchPackageVersionAsset(destRepoId, domain, destinationRepository, namespace, packageName,
|
||||
version, destAssetName)
|
||||
.ifPresent(content -> originalContent.put(destAssetName, content));
|
||||
}
|
||||
List<String> touchedAssetNames = new ArrayList<>();
|
||||
// Snapshotted immediately before this version's own writes, the same way every other
|
||||
// container-backed write path already takes its fence snapshot right before issuing
|
||||
// the real write it will later report: recording this version's bytes must still
|
||||
// reflect the latest live state even if an earlier version in this same batch call
|
||||
// already changed it (there is no shared snapshot spanning the whole batch to go
|
||||
// stale as later versions are processed).
|
||||
long packageFenceSnapshot = currentContainerBackedPackageFence(region, domain, owner,
|
||||
destinationRepository, format, namespace, packageName);
|
||||
long bytesWritten = 0L;
|
||||
try {
|
||||
// Every asset this version already held at the destination is deleted first, in
|
||||
// its own phase, before anything new is written: pypiserver's own delete call
|
||||
// (confirmed live) removes every file sharing that exact package name and
|
||||
// version, not just the one asset name passed to it, so deleting a same-named
|
||||
// asset in the middle of a per-asset write loop would silently wipe a sibling
|
||||
// asset (e.g. the wheel of a release also carrying an sdist) already rewritten
|
||||
// earlier in that same loop. Clearing everything up front, before any of this
|
||||
// version's new content exists to be collaterally wiped, is correct for every
|
||||
// format: Reposilite/Verdaccio/BaGetter's own deletes are already scoped to
|
||||
// exactly the asset (or, for npm/nuget, the single asset their formats ever hold
|
||||
// per version) being removed, so doing them first changes nothing for them, and
|
||||
// still satisfies Reposilite's own redeployment:false rejection of a plain PUT
|
||||
// over differing existing content the same way the previous interleaved ordering
|
||||
// did.
|
||||
for (String destAssetName : destAssetNames) {
|
||||
manager.deletePackageVersionAsset(destRepoId, domain, destinationRepository, namespace,
|
||||
packageName, version, destAssetName);
|
||||
touchedAssetNames.add(destAssetName);
|
||||
}
|
||||
for (Map.Entry<String, byte[]> entry : verifiedContentByVersion.get(version).entrySet()) {
|
||||
String assetName = entry.getKey();
|
||||
manager.copyPackageVersionAsset(sourceRepoId, domain, sourceRepository, destRepoId,
|
||||
destinationRepository, namespace, packageName, version, assetName, entry.getValue());
|
||||
if (!touchedAssetNames.contains(assetName)) {
|
||||
touchedAssetNames.add(assetName);
|
||||
}
|
||||
bytesWritten += entry.getValue().length;
|
||||
}
|
||||
manager.recordVersionAvailable(destRepoId, domain, destinationRepository, namespace, packageName,
|
||||
version);
|
||||
} catch (RuntimeException e) {
|
||||
rollbackContainerBackedVersionWrite(manager, destRepoId, domain, destinationRepository, namespace,
|
||||
packageName, version, originalContent, touchedAssetNames);
|
||||
throw e;
|
||||
}
|
||||
if (bytesWritten > 0) {
|
||||
recordContainerBackedAssetBytes(region, domain, owner, destinationRepository, format, namespace,
|
||||
packageName, bytesWritten, packageFenceSnapshot);
|
||||
}
|
||||
copyCapturedReadmeIfApplicable(region, domain, owner, sourceRepository, destinationRepository, format,
|
||||
namespace, packageName, version);
|
||||
String revision = synthesizeContainerBackedRevision(destRepoId, namespace, packageName, version);
|
||||
successes.put(version, new PackageVersionCopyOutcome(revision, "Published"));
|
||||
}
|
||||
return new CopyPackageVersionsResult(successes, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagates the source version's captured readme to the destination for {@code npm} and
|
||||
* {@code pypi}, the only two formats {@link #getPackageVersionReadme} answers from a record
|
||||
* captured at publish time rather than live from the sidecar (see that method's own javadoc
|
||||
* for why neither sidecar can answer for a specific version after the fact). Without this, a
|
||||
* copied npm or pypi version's assets would land correctly at the destination while {@code
|
||||
* GetPackageVersionReadme} 404s on it there, even though the source genuinely has one: this
|
||||
* bridge's own asset copy has no other way to reach that text, since it lives only in this
|
||||
* service's own {@code packageVersionReadmes} map, never in the sidecar content itself.
|
||||
*
|
||||
* <p>{@code nuget} needs no equivalent call: {@link #getPackageVersionReadme} already answers
|
||||
* it live against the sidecar, and the {@code .nupkg} this bridge already copied carries its
|
||||
* own embedded readme/nuspec description with it. {@code maven} has no readme concept in
|
||||
* Floci at all (absent from {@link #README_FORMATS}).
|
||||
*
|
||||
* <p>A missing source entry (no capture ever ran for that version, only possible for data
|
||||
* from before this call existed) is silently skipped, not treated as a failure: there is
|
||||
* nothing to propagate, the same way a version genuinely published with no readme field
|
||||
* already records an empty string rather than nothing (see {@link
|
||||
* #recordPublishedPackageVersionReadme}'s own callers). Any other failure here is logged and
|
||||
* swallowed rather than thrown: this is the same best-effort side channel {@link
|
||||
* #recordPublishedPackageVersionReadme}'s own javadoc already describes it as, so it must
|
||||
* never turn a copy that otherwise fully succeeded against the real sidecar into a thrown
|
||||
* exception over this alone.
|
||||
*/
|
||||
private void copyCapturedReadmeIfApplicable(String region, String domain, String owner, String sourceRepository,
|
||||
String destinationRepository, String format, String namespace, String packageName, String version) {
|
||||
if (!"npm".equals(format) && !"pypi".equals(format)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String sourceKey = packageVersionKey(region, domain, sourceRepository, format, namespace,
|
||||
accountingPackageName(format, packageName), version);
|
||||
String readme = packageVersionReadmes.get(ownerScopedKey(owner, sourceKey));
|
||||
if (readme == null) {
|
||||
return;
|
||||
}
|
||||
long readmeFenceSnapshot = currentContainerBackedPackageFence(region, domain, owner,
|
||||
destinationRepository, format, namespace, packageName);
|
||||
recordPublishedPackageVersionReadme(region, domain, owner, destinationRepository, format, namespace,
|
||||
packageName, version, readme, readmeFenceSnapshot);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not copy {0}/{1} package ''{2}'' version ''{3}''''s readme to {4}; the copied "
|
||||
+ "version itself still succeeded.", domain, sourceRepository, packageName, version,
|
||||
destinationRepository);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort compensating cleanup for one version's partially-applied destination writes
|
||||
* after {@link #copyContainerBackedPackageVersions} hits a failure partway through them:
|
||||
* every asset this call itself touched is restored to whatever it held before (if it
|
||||
* pre-existed, from {@code originalContent}) or deleted outright (if it was new). Does not
|
||||
* attempt to re-create a stale asset it had not yet gotten to deleting, or undo a successful
|
||||
* {@link RepositorySidecarManager#recordVersionAvailable} call, since neither leaves the
|
||||
* destination in a worse state than before this version's write began. A failure during the
|
||||
* rollback itself is logged and swallowed, never thrown over the original failure that
|
||||
* triggered it: a best-effort cleanup that cannot fully complete is still strictly no worse
|
||||
* than not attempting one, and must never hide the real error behind a cleanup error instead.
|
||||
*/
|
||||
private void rollbackContainerBackedVersionWrite(RepositorySidecarManager manager, String destRepoId,
|
||||
String domain, String destinationRepository, String namespace, String packageName, String version,
|
||||
Map<String, byte[]> originalContent, List<String> touchedAssetNames) {
|
||||
for (String assetName : touchedAssetNames) {
|
||||
try {
|
||||
byte[] original = originalContent.get(assetName);
|
||||
if (original != null) {
|
||||
manager.storePackageVersionAsset(destRepoId, domain, destinationRepository, namespace,
|
||||
packageName, version, assetName, original);
|
||||
} else {
|
||||
manager.deletePackageVersionAsset(destRepoId, domain, destinationRepository, namespace,
|
||||
packageName, version, assetName);
|
||||
}
|
||||
} catch (RuntimeException rollbackFailure) {
|
||||
LOG.warnv(rollbackFailure, "Best-effort rollback could not restore {0}/{1} package ''{2}'' "
|
||||
+ "version ''{3}'' asset ''{4}'' after a failed copy; the destination may still be "
|
||||
+ "left in a partially-copied state for this version.", domain, destinationRepository,
|
||||
packageName, version, assetName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code true} only when {@code source} and {@code dest} hold the exact same asset names for
|
||||
* this version, each fetching to byte-identical content: the container-backed equivalent of
|
||||
* {@link #packageVersionContentMatches}, which compares persisted hashes instead since generic
|
||||
* assets have one and these don't.
|
||||
*/
|
||||
private static boolean containerBackedVersionContentMatches(RepositorySidecarManager manager,
|
||||
String sourceRepoId, String sourceRepository, String destRepoId, String destinationRepository,
|
||||
String domain, String namespace, String packageName, String version, List<String> sourceAssetNames,
|
||||
List<String> destAssetNames) {
|
||||
if (!new LinkedHashSet<>(sourceAssetNames).equals(new LinkedHashSet<>(destAssetNames))) {
|
||||
return false;
|
||||
}
|
||||
for (String assetName : sourceAssetNames) {
|
||||
byte[] sourceContent = manager.fetchPackageVersionAsset(sourceRepoId, domain, sourceRepository,
|
||||
namespace, packageName, version, assetName).orElse(null);
|
||||
byte[] destContent = manager.fetchPackageVersionAsset(destRepoId, domain, destinationRepository,
|
||||
namespace, packageName, version, assetName).orElse(null);
|
||||
if (!Arrays.equals(sourceContent, destContent)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads every one of {@code source}'s assets and confirms each one's actual bytes still hash
|
||||
* to what its own persisted metadata claims, returning the verified bytes keyed by asset name.
|
||||
|
||||
+121
@@ -14,6 +14,7 @@ import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -159,6 +160,126 @@ public class PypiserverSidecarClient implements RepositorySidecarManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every filename pypiserver's own per-project JSON listing records for exactly {@code
|
||||
* version}, for bridging {@code CopyPackageVersions} when there is no generic-format record
|
||||
* to enumerate assets from. Reuses the same {@code GET /<project>/json} endpoint {@link
|
||||
* #packageFiles} already does, this time keeping the filename itself rather than discarding
|
||||
* it for the recovered raw name {@link #packageFiles} needs.
|
||||
*/
|
||||
@Override
|
||||
public List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
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 List.of();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not list versions of " + packageName + " on the pypiserver "
|
||||
+ "sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
JsonNode release;
|
||||
try {
|
||||
release = mapper.readTree(response.body()).path("releases").path(version);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse pypiserver's version listing for " + packageName, e);
|
||||
}
|
||||
List<String> filenames = new ArrayList<>();
|
||||
for (JsonNode file : release) {
|
||||
String url = file.path("url").asText("");
|
||||
String filename = url.substring(url.lastIndexOf('/') + 1);
|
||||
if (!filename.isEmpty()) {
|
||||
filenames.add(filename);
|
||||
}
|
||||
}
|
||||
return filenames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads {@code content} as {@code assetName} the same real {@code twine upload} wire shape
|
||||
* {@code CodeArtifactPypiController#upload} already forwards unmodified, confirmed against a
|
||||
* live pypiserver container: a {@code multipart/form-data} {@code POST} to the repository
|
||||
* root with a {@code :action=file_upload} field (pypiserver rejects the request outright
|
||||
* without it, "Missing ':action' field!", even though neither twine's own real request nor
|
||||
* this sidecar's existing upload-forwarding path ever has to name it explicitly), {@code
|
||||
* name}/{@code version} fields, and the file itself as the {@code content} part. pypiserver
|
||||
* indexes a package by parsing {@code assetName} itself (PEP 427/517 naming), not the
|
||||
* {@code name} field, so a mismatched filename silently publishes under whatever name the
|
||||
* filename itself implies instead of {@code packageName} — the caller is expected to pass a
|
||||
* {@code version}-embedding {@code assetName} the same way {@link #fetchPackageVersionAsset}
|
||||
* already requires one to read it back.
|
||||
*
|
||||
* <p>Rejected outright with a real {@code 409} ("already exists") if {@code assetName}
|
||||
* already exists with different content, confirmed live: this container is started without
|
||||
* pypiserver's own {@code --overwrite} flag, the same as production. The caller ({@code
|
||||
* CodeArtifactService#copyContainerBackedPackageVersions}) is expected to have already
|
||||
* deleted a conflicting existing asset first for an overwrite, the same reason {@code
|
||||
* ReposiliteSidecarClient#storePackageVersionAsset} documents for Maven.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
String boundary = "flociPypiCopyBoundary" + System.nanoTime();
|
||||
byte[] head = ("--" + boundary + "\r\n"
|
||||
+ "Content-Disposition: form-data; name=\":action\"\r\n\r\nfile_upload\r\n"
|
||||
+ "--" + boundary + "\r\n"
|
||||
+ "Content-Disposition: form-data; name=\"name\"\r\n\r\n" + packageName + "\r\n"
|
||||
+ "--" + boundary + "\r\n"
|
||||
+ "Content-Disposition: form-data; name=\"version\"\r\n\r\n" + version + "\r\n"
|
||||
+ "--" + boundary + "\r\n"
|
||||
+ "Content-Disposition: form-data; name=\"content\"; filename=\"" + assetName + "\"\r\n"
|
||||
+ "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8);
|
||||
byte[] tail = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8);
|
||||
byte[] body = new byte[head.length + content.length + tail.length];
|
||||
System.arraycopy(head, 0, body, 0, head.length);
|
||||
System.arraycopy(content, 0, body, head.length, content.length);
|
||||
System.arraycopy(tail, 0, body, head.length + content.length, tail.length);
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/"))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
|
||||
.POST(BodyPublishers.ofByteArray(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 publish " + assetName, e);
|
||||
}
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201) {
|
||||
throw new IllegalStateException("Could not publish " + assetName + " to the pypiserver sidecar: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one asset via pypiserver's own {@code remove_pkg} management call, confirmed live
|
||||
* to delete by raw name/version rather than by filename: {@link #rawPkgname} recovers the
|
||||
* exact unnormalized name {@code remove_pkg} needs from {@code assetName} itself, the same way
|
||||
* {@link #deletePackage}'s own loop already does per file. A sibling file that happens to
|
||||
* share the exact same raw name and version as {@code assetName} is removed in the same call
|
||||
* (confirmed live for {@link #deletePackage}'s own multi-file case); pypiserver has no finer
|
||||
* grain than that to ask for.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
removeVersion(baseUrl, rawPkgname(assetName, version), version);
|
||||
}
|
||||
|
||||
private record PkgNameVersion(String name, String version) {}
|
||||
|
||||
private Set<PkgNameVersion> packageFiles(String baseUrl, String packageName) {
|
||||
|
||||
+180
-2
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -17,8 +19,14 @@ 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.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -36,6 +44,9 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
private static final String MAVEN_SETTINGS_PATH = "/api/settings/domain/maven";
|
||||
private static final int REPOSITORY_READY_POLL_MAX_MS = 3_000;
|
||||
private static final int REPOSITORY_READY_POLL_INTERVAL_MS = 50;
|
||||
/** Real Maven metadata's own documented {@code lastUpdated} shape: UTC, {@code yyyyMMddHHmmss}. */
|
||||
private static final DateTimeFormatter METADATA_TIMESTAMP = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private final ReposiliteSidecarManager manager;
|
||||
private final ObjectMapper mapper;
|
||||
@@ -193,8 +204,7 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
public boolean packageVersionExists(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
String path = "/api/maven/details" + packageDirectoryPath(repositoryContainerId, namespace, packageName)
|
||||
+ SidecarUriUtils.encodeSegment(version);
|
||||
String path = versionDetailsPath(repositoryContainerId, namespace, packageName, version);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader())
|
||||
@@ -211,6 +221,174 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String versionDetailsPath(String repositoryContainerId, String namespace, String packageName,
|
||||
String version) {
|
||||
return "/api/maven/details" + packageDirectoryPath(repositoryContainerId, namespace, packageName)
|
||||
+ SidecarUriUtils.encodeSegment(version);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reposilite's own details API, already relied on by {@link #packageVersionExists} to confirm
|
||||
* a version directory exists, also lists every entry directly beneath it: this reads that same
|
||||
* response's {@code files} array a second way, keeping only the {@code FILE} entries (never a
|
||||
* subdirectory, though a plain Maven version directory never has one) and returning their
|
||||
* names, for {@code CopyPackageVersions} to enumerate what it needs to fetch and copy without
|
||||
* any generic-format {@code packageVersions} record to read an asset list from.
|
||||
*/
|
||||
@Override
|
||||
public List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
String path = versionDetailsPath(repositoryContainerId, namespace, packageName, version);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader())
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = send(request, BodyHandlers.ofString());
|
||||
if (response.statusCode() == 404) {
|
||||
return List.of();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not list " + packageName + " " + version + " on the Reposilite "
|
||||
+ "sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
JsonNode details = readTree(response.body());
|
||||
List<String> names = new ArrayList<>();
|
||||
for (JsonNode entry : details.path("files")) {
|
||||
if ("FILE".equals(entry.path("type").asText())) {
|
||||
names.add(entry.path("name").asText());
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code content} straight to this version's {@code assetName} path, for {@code
|
||||
* CopyPackageVersions}'s destination write. Unlike {@link #deployArtifact}, this never
|
||||
* short-circuits on an existing byte-identical match and never leaves Reposilite's own {@code
|
||||
* redeployment: false} rejection standing in the way of a differing overwrite: the caller
|
||||
* ({@code CodeArtifactService#copyContainerBackedPackageVersions}) has already decided, from
|
||||
* its own all-or-nothing batch semantics, exactly which versions get overwritten, and has
|
||||
* already called {@link #deletePackageVersionAsset} first for any asset this would otherwise
|
||||
* conflict with, so there is nothing left here to defer to Reposilite's own native-publish
|
||||
* conflict rule for.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
ensureRepository(repositoryContainerId);
|
||||
String baseUrl = manager.ensureReady();
|
||||
String gav = versionGav(namespace, packageName, version, assetName);
|
||||
HttpRequest request = authenticated(baseUrl, repositoryContainerId, gav)
|
||||
.PUT(BodyPublishers.ofByteArray(content))
|
||||
.build();
|
||||
int status = send(request, BodyHandlers.discarding()).statusCode();
|
||||
if (status != 200 && status != 201) {
|
||||
throw new IllegalStateException("Could not copy " + packageName + " " + version + "'s asset "
|
||||
+ assetName + " to the Reposilite sidecar: upstream returned " + status);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes one already-published asset outright, confirmed working for an arbitrarily deep path
|
||||
* the same way {@link #deletePackage}'s own group/artifact-directory {@code DELETE} is already
|
||||
* confirmed to work for a shallower one: Reposilite applies the same verb to whatever path it is
|
||||
* given, file or directory. Only ever called by {@code CopyPackageVersions}'s overwrite path for
|
||||
* an asset {@link #listPackageVersionAssetNames} already confirmed exists, so unlike {@link
|
||||
* #deletePackage} this never has to special-case a never-existing path.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
String gav = versionGav(namespace, packageName, version, assetName);
|
||||
HttpRequest request = authenticated(baseUrl, repositoryContainerId, gav).DELETE().build();
|
||||
HttpResponse<Void> response = send(request, BodyHandlers.discarding());
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not delete " + packageName + " " + version + "'s asset "
|
||||
+ assetName + " from the Reposilite sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The real Maven repository layout path for one asset of one package version:
|
||||
* {@code <groupId-as-slashes>/<artifactId>/<version>/<filename>}, the same shape {@link
|
||||
* #deployArtifact} and {@link #fetchArtifact} already take as their own {@code gav} parameter
|
||||
* (and the inverse of what {@code CodeArtifactMavenController#parseNamespaceAndPackageName}
|
||||
* builds back out of it).
|
||||
*/
|
||||
private static String versionGav(String namespace, String packageName, String version, String assetName) {
|
||||
return namespace.replace('.', '/') + "/" + packageName + "/" + version + "/" + assetName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges {@code version} into the group/artifact-level {@code maven-metadata.xml} a real
|
||||
* {@code mvn deploy} always also PUTs, separately from the version directory itself: without
|
||||
* this, a version {@code CopyPackageVersions} lands straight in the version directory would
|
||||
* never show up to a real client resolving "what versions does this artifact have" against
|
||||
* the destination, the one thing this bridge's {@link #listPackageVersionAssetNames}/{@link
|
||||
* #storePackageVersionAsset} pair, scoped to one version directory each, cannot reach.
|
||||
*
|
||||
* <p>Confirmed against a live Reposilite container, same as every other wire assumption in
|
||||
* this class: unlike a release artifact, a metadata file is not subject to the repository's
|
||||
* own {@code redeployment: false} setting, so {@link #deployArtifact} can PUT one with
|
||||
* genuinely different content every time without the conflict a real artifact overwrite
|
||||
* would hit.
|
||||
*
|
||||
* <p>{@code latest} is set to {@code version}: real Maven defines it as whichever version was
|
||||
* most recently added, and this call existing at all means {@code version} just was. {@code
|
||||
* release} only moves to {@code version} when it is not a {@code -SNAPSHOT}; a snapshot copy
|
||||
* leaves whatever release version the metadata already named untouched. An existing
|
||||
* {@code groupId}/{@code artifactId} already on the file is preserved verbatim rather than
|
||||
* re-derived from {@code namespace}/{@code packageName}, since nothing here needs it to be;
|
||||
* the already-published metadata is trusted over Floci's own request-path coordinates for
|
||||
* these two fields specifically.
|
||||
*/
|
||||
@Override
|
||||
public void recordVersionAvailable(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
ensureRepository(repositoryContainerId);
|
||||
String gav = artifactMetadataGav(namespace, packageName);
|
||||
Optional<FetchedArtifact> existing = fetchArtifact(repositoryContainerId, gav);
|
||||
List<String> versions = new ArrayList<>();
|
||||
String groupId = namespace;
|
||||
String artifactId = packageName;
|
||||
String release = null;
|
||||
if (existing.isPresent()) {
|
||||
String xml = new String(existing.get().content(), StandardCharsets.UTF_8);
|
||||
versions.addAll(XmlParser.extractAll(xml, "version"));
|
||||
groupId = XmlParser.extractFirst(xml, "groupId", namespace);
|
||||
artifactId = XmlParser.extractFirst(xml, "artifactId", packageName);
|
||||
release = XmlParser.extractFirst(xml, "release", null);
|
||||
}
|
||||
if (!versions.contains(version)) {
|
||||
versions.add(version);
|
||||
}
|
||||
if (!version.endsWith("-SNAPSHOT")) {
|
||||
release = version;
|
||||
}
|
||||
XmlBuilder metadata = new XmlBuilder().start("metadata")
|
||||
.elem("groupId", groupId)
|
||||
.elem("artifactId", artifactId)
|
||||
.start("versioning")
|
||||
.elem("latest", version)
|
||||
.elem("release", release)
|
||||
.start("versions");
|
||||
for (String v : versions) {
|
||||
metadata.elem("version", v);
|
||||
}
|
||||
metadata.end("versions")
|
||||
.elem("lastUpdated", METADATA_TIMESTAMP.format(Instant.now()))
|
||||
.end("versioning")
|
||||
.end("metadata");
|
||||
deployArtifact(repositoryContainerId, gav, metadata.build().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String artifactMetadataGav(String namespace, String packageName) {
|
||||
return namespace.replace('.', '/') + "/" + packageName + "/maven-metadata.xml";
|
||||
}
|
||||
|
||||
/** Ensures a Reposilite repository named {@code repoId} exists, creating it if not. */
|
||||
public void ensureRepository(String repoId) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
|
||||
+77
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -113,4 +114,80 @@ public interface RepositorySidecarManager {
|
||||
String namespace, String packageName, String version) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the asset name of every file published under one package version, for bridging
|
||||
* {@code CopyPackageVersions} when there is no generic-format record to enumerate assets from
|
||||
* the way {@code CodeArtifactPackageVersion#getAssets} does. The default throws {@link
|
||||
* UnsupportedOperationException}, the same convention {@link #deletePackage} already uses for
|
||||
* a capability not every sidecar backs; every container-backed format's own client overrides
|
||||
* this today.
|
||||
*/
|
||||
default List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
throw new UnsupportedOperationException(format() + " package versions cannot be listed through this "
|
||||
+ "sidecar");
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes one named asset's bytes directly into this sidecar's own backing storage for the
|
||||
* given package version, for bridging {@code CopyPackageVersions}'s destination write. The
|
||||
* caller is expected to have already removed any conflicting content at this exact path first
|
||||
* (see {@link #deletePackageVersionAsset}) when overwriting, since this is a direct admin-level
|
||||
* write, not a replay of whatever conflict rule the sidecar's own native publish path enforces.
|
||||
* The default throws {@link UnsupportedOperationException}.
|
||||
*/
|
||||
default void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
throw new UnsupportedOperationException(format() + " package versions cannot be copied through this "
|
||||
+ "sidecar");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code CopyPackageVersions}' own destination write, as opposed to a bare {@link
|
||||
* #storePackageVersionAsset} call with no notion of a source: the default simply forwards to
|
||||
* it, correct for a format whose version-level metadata is entirely recoverable from the
|
||||
* asset bytes alone (Maven's POM/jar pair, pypi's sdist/wheel, nuget's one-file nupkg, none of
|
||||
* which keep anything outside what {@code content} itself carries). {@code
|
||||
* VerdaccioSidecarClient} overrides this: npm's packument carries fields ({@code
|
||||
* dependencies}, {@code scripts}, {@code engines}, ...) on the version document itself, so
|
||||
* building a fresh one from scratch the way {@link #storePackageVersionAsset} does on its own
|
||||
* drops them; this instead reuses the source's own version entry verbatim, with only {@code
|
||||
* dist.tarball}/{@code dist.shasum}/{@code dist.integrity} rewritten to point at the copy.
|
||||
*/
|
||||
default void copyPackageVersionAsset(String sourceRepositoryContainerId, String domain, String sourceRepository,
|
||||
String repositoryContainerId, String repository, String namespace, String packageName, String version,
|
||||
String assetName, byte[] content) {
|
||||
storePackageVersionAsset(repositoryContainerId, domain, repository, namespace, packageName, version,
|
||||
assetName, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes one already-confirmed-present named asset from this sidecar's own backing storage
|
||||
* for the given package version, used by {@code CopyPackageVersions}'s overwrite path to drop
|
||||
* an asset the destination version held that the source version no longer does, and to clear
|
||||
* the way for {@link #storePackageVersionAsset} to replace an asset whose content differs. The
|
||||
* default throws {@link UnsupportedOperationException}.
|
||||
*/
|
||||
default void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
throw new UnsupportedOperationException(format() + " package version assets cannot be deleted through "
|
||||
+ "this sidecar");
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that {@code version} now exists under this package, for whatever artifact-level
|
||||
* version listing this format's sidecar keeps separately from the version directory itself
|
||||
* (one {@link #storePackageVersionAsset}/{@link #deletePackageVersionAsset} call already
|
||||
* writes to), so a real client resolving "what versions does this artifact have" sees it.
|
||||
* The default is a no-op: most formats have no such separate listing, since their package
|
||||
* document is derived live from the version directories those two methods already maintain.
|
||||
* {@code ReposiliteSidecarClient} overrides this: Maven's group/artifact-level {@code
|
||||
* maven-metadata.xml} is a distinct upload a real {@code mvn deploy} always also PUTs,
|
||||
* outside the version directory {@link #listPackageVersionAssetNames} enumerates, so nothing
|
||||
* else here ever touches it on {@code maven}'s behalf.
|
||||
*/
|
||||
default void recordVersionAvailable(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
}
|
||||
}
|
||||
+213
-6
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -11,12 +13,14 @@ import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
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.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -227,17 +231,220 @@ public class VerdaccioSidecarClient implements RepositorySidecarManager {
|
||||
}
|
||||
|
||||
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
|
||||
Optional<JsonNode> document = packageDocument(baseUrl, packagePath);
|
||||
if (document.isEmpty()) {
|
||||
return false;
|
||||
return assetName.equals(tarballFilenameFor(packageDocument(baseUrl, packagePath).orElse(null), version));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tarball filename Verdaccio's own packument records for {@code version}, derived from
|
||||
* {@code versions[version].dist.tarball}'s own last path segment the same way {@link
|
||||
* #fetchPackageVersionAsset} already trusts it, rather than assuming a fixed {@code
|
||||
* <packageName>-<version>.tgz} shape: real npm names it that way, but nothing here needs to
|
||||
* assume so when the packument already states it outright. {@code null} when the document is
|
||||
* absent, the version doesn't exist, or the version has no tarball recorded.
|
||||
*/
|
||||
private static String tarballFilenameFor(JsonNode document, String version) {
|
||||
if (document == null) {
|
||||
return null;
|
||||
}
|
||||
JsonNode versionNode = document.get().path("versions").path(version);
|
||||
JsonNode versionNode = document.path("versions").path(version);
|
||||
if (versionNode.isMissingNode()) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
String tarballUrl = versionNode.path("dist").path("tarball").asText("");
|
||||
String tarballFilename = tarballUrl.substring(tarballUrl.lastIndexOf('/') + 1);
|
||||
return assetName.equals(tarballFilename);
|
||||
return tarballFilename.isEmpty() ? null : tarballFilename;
|
||||
}
|
||||
|
||||
/**
|
||||
* npm has exactly one asset per version, the tarball: unlike Maven's version directory, there
|
||||
* is no separate checksum sidecar file or secondary artifact to enumerate. Empty when the
|
||||
* package or version doesn't exist, or the existing version has no tarball recorded (should
|
||||
* not happen for anything this emulator itself ever published, but a real registry can be
|
||||
* imported from or hand-edited).
|
||||
*/
|
||||
@Override
|
||||
public List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
|
||||
String filename = tarballFilenameFor(
|
||||
packageDocument(baseUrl, packagePath(namespace, packageName)).orElse(null), version);
|
||||
return filename == null ? List.of() : List.of(filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes {@code version} straight to this sidecar's own packument, the real npm registry
|
||||
* wire shape confirmed against a live Verdaccio container: a {@code PUT} to the package path
|
||||
* carrying just the new version's metadata, its tarball as a base64 {@code _attachments}
|
||||
* entry, and {@code dist-tags.latest} pointed at it. Verdaccio merges this into whatever
|
||||
* {@code versions} the package already has rather than requiring the caller to resend them
|
||||
* (also confirmed live), so this never needs to read the existing packument first the way
|
||||
* {@link #deletePackageVersionAsset} does. Rejected outright (a real {@code 409}, "this
|
||||
* package is already present") if {@code version} already exists, even if its content is
|
||||
* identical: the caller ({@code CodeArtifactService#copyContainerBackedPackageVersions}) is
|
||||
* expected to have already deleted a conflicting existing version first for an overwrite, the
|
||||
* same reason {@code ReposiliteSidecarClient#storePackageVersionAsset} documents for Maven.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content,
|
||||
null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reuses {@code sourceRepositoryContainerId}'s own version entry verbatim (the exact document
|
||||
* its original publish wrote, including {@code dependencies}/{@code scripts}/{@code engines}
|
||||
* and anything else npm's own protocol carries on a version), rather than building a fresh,
|
||||
* minimal one from scratch the way {@link #storePackageVersionAsset} does on its own — only
|
||||
* {@code dist} is overwritten, to point at the copy's own tarball/shasum/integrity. Confirmed
|
||||
* live that a copy with no matching source version entry (should not happen for anything this
|
||||
* emulator itself ever published, but defends the same way {@link #listPackageVersionAssetNames}
|
||||
* already does for a hand-edited registry) falls back to the same minimal document {@link
|
||||
* #storePackageVersionAsset} would have built.
|
||||
*/
|
||||
@Override
|
||||
public void copyPackageVersionAsset(String sourceRepositoryContainerId, String domain, String sourceRepository,
|
||||
String repositoryContainerId, String repository, String namespace, String packageName, String version,
|
||||
String assetName, byte[] content) {
|
||||
String sourceBaseUrl = ensureReady(sourceRepositoryContainerId, publicUrl(domain, sourceRepository));
|
||||
JsonNode sourceVersionDoc = packageDocument(sourceBaseUrl, packagePath(namespace, packageName))
|
||||
.map(doc -> doc.path("versions").path(version))
|
||||
.filter(node -> !node.isMissingNode() && !node.isNull())
|
||||
.orElse(null);
|
||||
storeVersion(repositoryContainerId, domain, repository, namespace, packageName, version, assetName, content,
|
||||
sourceVersionDoc);
|
||||
}
|
||||
|
||||
private void storeVersion(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName, String version, String assetName, byte[] content, JsonNode sourceVersionDoc) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
|
||||
String path = packagePath(namespace, packageName);
|
||||
String npmName = npmPackageName(namespace, packageName);
|
||||
String tarballUrl = baseUrl + "/" + path + "/-/" + assetName;
|
||||
|
||||
ObjectNode versionDoc = sourceVersionDoc != null ? sourceVersionDoc.deepCopy() : mapper.createObjectNode();
|
||||
versionDoc.put("name", npmName);
|
||||
versionDoc.put("version", version);
|
||||
if (!versionDoc.has("description")) {
|
||||
versionDoc.put("description", "");
|
||||
}
|
||||
ObjectNode dist = versionDoc.putObject("dist");
|
||||
dist.put("shasum", Digests.sha1Hex(content));
|
||||
dist.put("integrity", "sha512-" + Base64.getEncoder().encodeToString(sha512().digest(content)));
|
||||
dist.put("tarball", tarballUrl);
|
||||
|
||||
ObjectNode body = mapper.createObjectNode();
|
||||
body.put("_id", npmName);
|
||||
body.put("name", npmName);
|
||||
body.put("description", "");
|
||||
body.putObject("dist-tags").put("latest", version);
|
||||
body.putObject("versions").set(version, versionDoc);
|
||||
ObjectNode attachment = body.putObject("_attachments").putObject(assetName);
|
||||
attachment.put("content_type", "application/octet-stream");
|
||||
attachment.put("data", Base64.getEncoder().encodeToString(content));
|
||||
attachment.put("length", content.length);
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/" + path))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Content-Type", "application/json")
|
||||
.PUT(BodyPublishers.ofByteArray(writeValue(body)))
|
||||
.build();
|
||||
HttpResponse<Void> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.discarding());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Verdaccio sidecar to publish " + npmName + "@"
|
||||
+ version, e);
|
||||
}
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201) {
|
||||
throw new IllegalStateException("Could not publish " + npmName + "@" + version + " to the Verdaccio "
|
||||
+ "sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one version from this package the same two-step way the real npm CLI's single-
|
||||
* version {@code npm unpublish <pkg>@<version>} does, both confirmed live against a Verdaccio
|
||||
* container: first a {@code PUT} of the packument with that version deleted from {@code
|
||||
* versions} (and {@code dist-tags.latest} cleared if it pointed at the removed version),
|
||||
* carrying the package's current {@code _rev} in the path for Verdaccio's own optimistic-
|
||||
* concurrency check; then, once that succeeds and the package has a fresh {@code _rev} of its
|
||||
* own, a {@code DELETE} of the tarball itself. Both steps are required: removing the version
|
||||
* from the packument alone leaves the tarball file in place on Verdaccio's own storage, which
|
||||
* then makes a same-named {@link #storePackageVersionAsset} republish fail with the same
|
||||
* {@code 409} as before, since Verdaccio checks the stored file, not just the packument.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, publicUrl(domain, repository));
|
||||
String path = packagePath(namespace, packageName);
|
||||
ObjectNode document = (ObjectNode) packageDocument(baseUrl, path)
|
||||
.orElseThrow(() -> new IllegalStateException(packageName + " no longer exists on the Verdaccio "
|
||||
+ "sidecar"));
|
||||
String revision = document.path("_rev").asText("");
|
||||
((ObjectNode) document.path("versions")).remove(version);
|
||||
ObjectNode distTags = (ObjectNode) document.path("dist-tags");
|
||||
if (version.equals(distTags.path("latest").asText(""))) {
|
||||
distTags.remove("latest");
|
||||
}
|
||||
putPackument(baseUrl, path, revision, document, packageName, version);
|
||||
|
||||
String revisionAfterRemove = packageDocument(baseUrl, path)
|
||||
.orElseThrow(() -> new IllegalStateException(packageName + " no longer exists on the Verdaccio "
|
||||
+ "sidecar"))
|
||||
.path("_rev").asText("");
|
||||
URI tarballUri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + path + "/-/"
|
||||
+ SidecarUriUtils.encodeSegment(assetName) + "/-rev/" + SidecarUriUtils.encodeSegment(
|
||||
revisionAfterRemove));
|
||||
HttpRequest deleteRequest = HttpRequest.newBuilder(tarballUri).timeout(Duration.ofSeconds(10)).DELETE()
|
||||
.build();
|
||||
HttpResponse<Void> deleteResponse;
|
||||
try {
|
||||
deleteResponse = httpClient.send(deleteRequest, BodyHandlers.discarding());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Verdaccio sidecar to delete " + packageName + "@"
|
||||
+ version + "'s asset " + assetName, e);
|
||||
}
|
||||
if (deleteResponse.statusCode() != 200 && deleteResponse.statusCode() != 201) {
|
||||
throw new IllegalStateException("Could not delete " + packageName + "@" + version + "'s asset "
|
||||
+ assetName + " from the Verdaccio sidecar: upstream returned " + deleteResponse.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
private void putPackument(String baseUrl, String path, String revision, ObjectNode document, String packageName,
|
||||
String version) {
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + path + "/-rev/"
|
||||
+ SidecarUriUtils.encodeSegment(revision));
|
||||
HttpRequest request = HttpRequest.newBuilder(uri)
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Content-Type", "application/json")
|
||||
.PUT(BodyPublishers.ofByteArray(writeValue(document)))
|
||||
.build();
|
||||
HttpResponse<Void> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.discarding());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Verdaccio sidecar to update " + packageName + "@"
|
||||
+ version, e);
|
||||
}
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201) {
|
||||
throw new IllegalStateException("Could not update " + packageName + "@" + version + " on the "
|
||||
+ "Verdaccio sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/** The real npm package name, {@code @namespace/packageName} for a scoped package. */
|
||||
private static String npmPackageName(String namespace, String packageName) {
|
||||
return namespace == null ? packageName : "@" + namespace + "/" + packageName;
|
||||
}
|
||||
|
||||
private byte[] writeValue(ObjectNode value) {
|
||||
try {
|
||||
return mapper.writeValueAsBytes(value);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not serialize a Verdaccio request body", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static MessageDigest sha512() {
|
||||
|
||||
Reference in new issue
Block a user