mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
fix(pypi): record the release version and skip metadata sidecars
A PyPI package row held the file name as its version, and each PEP 658 sidecar became its own package. The version now comes from the file name, and a wheel or zip adds a local-version suffix so distinct files keep distinct cache keys. The sidecar streams from upstream without a package row. Rows written before this change age out through the cache TTL.
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func TestPyPIRecordsOneRowPerArtifactAndNeverTheSidecar(t *testing.T) {
|
||||
const wheel = "six-1.17.0-py2.py3-none-any.whl"
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/six/" + wheel:
|
||||
_, _ = w.Write([]byte("WHEEL"))
|
||||
case "/six/" + wheel + ".metadata":
|
||||
_, _ = w.Write([]byte("Metadata-Version: 2.1\nName: six\n"))
|
||||
case "/six/six-1.17.0.tar.gz":
|
||||
_, _ = w.Write([]byte("SDIST"))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
a := newTestApp(t, func(c *config.Config) { c.Handlers.PyPI.SimpleAPIURL = upstream.URL })
|
||||
|
||||
for target, want := range map[string]string{
|
||||
"/pypi/six/" + wheel: "WHEEL",
|
||||
"/pypi/six/" + wheel + ".metadata": "Metadata-Version: 2.1\nName: six\n",
|
||||
"/pypi/six/six-1.17.0.tar.gz": "SDIST",
|
||||
} {
|
||||
// Twice: the second request is the cache hit.
|
||||
for i := 0; i < 2; i++ {
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK || body != want {
|
||||
t.Fatalf("GET %s = %d %q, want 200 %q", target, code, body, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
code, _, body := doRequest(t, a, "/api/packages?registry=pypi", nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("/api/packages: %d %s", code, body)
|
||||
}
|
||||
var resp struct {
|
||||
Packages []struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
} `json:"packages"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &resp); err != nil {
|
||||
t.Fatalf("decode %q: %v", body, err)
|
||||
}
|
||||
got := map[string]bool{}
|
||||
for _, p := range resp.Packages {
|
||||
if p.Name != "six" {
|
||||
continue
|
||||
}
|
||||
got[p.Version] = true
|
||||
}
|
||||
want := map[string]bool{"1.17.0": true, "1.17.0+py2.py3-none-any": true}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("six versions = %v, want %v (body %s)", got, want, body)
|
||||
}
|
||||
for v := range want {
|
||||
if !got[v] {
|
||||
t.Errorf("missing six version %q in %v", v, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
-7
@@ -236,17 +236,12 @@ func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter,
|
||||
func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter, r *http.Request, path string) {
|
||||
packageName, version := extractPackageFileInfo(path)
|
||||
|
||||
// cacheVersion is the cache key's version portion. It must be unique per
|
||||
// distinct artifact. PyPI publishes many files per release (multiple
|
||||
// wheels with different build tags, sdists, zips, .egg files, and
|
||||
// .metadata files for PEP 658), so the bare version is too coarse:
|
||||
// distinct files of the same version would collide on the same cache
|
||||
// key. The full unique basename guarantees one cache entry per artifact.
|
||||
filename := path
|
||||
if i := strings.LastIndex(filename, "/"); i >= 0 {
|
||||
filename = filename[i+1:]
|
||||
}
|
||||
cacheVersion := filename
|
||||
isSidecar := strings.HasSuffix(filename, metadataSuffix)
|
||||
cacheVersion := artifactCacheVersion(filename, version)
|
||||
|
||||
// Extract credentials from request
|
||||
credentials := h.credExtractor.Extract(r)
|
||||
@@ -290,6 +285,13 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
|
||||
}
|
||||
}
|
||||
|
||||
// A PEP 658 sidecar is a view of its wheel, not a package: stream it
|
||||
// without writing a package row.
|
||||
if isSidecar {
|
||||
h.serveMetadataSidecar(ctx, w, originalURL, credentials)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().
|
||||
Str("path", path).
|
||||
Str("package", packageName).
|
||||
@@ -425,6 +427,48 @@ func isPackageFile(path string) bool {
|
||||
strings.HasSuffix(path, ".metadata")
|
||||
}
|
||||
|
||||
// artifactCacheVersion returns the cache key's version portion. PyPI publishes
|
||||
// several files per release, so the bare version would make distinct wheels
|
||||
// share one cache entry. A wheel's build and tags, or a non-tarball sdist's
|
||||
// extension, are appended as a local-version suffix (PEP 440, "+") to keep
|
||||
// each artifact's key unique while the package version stays readable.
|
||||
func artifactCacheVersion(filename, version string) string {
|
||||
base := strings.TrimSuffix(filename, metadataSuffix)
|
||||
switch {
|
||||
case strings.HasSuffix(base, ".whl"):
|
||||
rest := strings.TrimSuffix(base, ".whl")
|
||||
if parts := strings.SplitN(rest, "-", 3); len(parts) == 3 && parts[2] != "" {
|
||||
return version + "+" + parts[2]
|
||||
}
|
||||
case strings.HasSuffix(base, ".zip"):
|
||||
return version + "+zip"
|
||||
case strings.HasSuffix(base, ".egg"):
|
||||
return version + "+egg"
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
// serveMetadataSidecar streams a PEP 658 .metadata file straight from upstream.
|
||||
func (h *Handler) serveMetadataSidecar(ctx context.Context, w http.ResponseWriter, upstreamURL, credentials string) {
|
||||
headers := make(map[string]string)
|
||||
if credentials != "" {
|
||||
headers["Authorization"] = credentials
|
||||
}
|
||||
body, status, err := h.client.Get(ctx, upstreamURL, headers)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("url", upstreamURL).Msg("Failed to fetch PEP 658 metadata")
|
||||
http.Error(w, "Failed to fetch package metadata", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer func() { _ = body.Close() }()
|
||||
if status != http.StatusOK {
|
||||
http.Error(w, "package metadata unavailable", status)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
|
||||
_, _ = io.Copy(w, body) // #nosec G104 -- HTTP response write
|
||||
}
|
||||
|
||||
// extractPackageName extracts package name from path
|
||||
func extractPackageName(path string) string {
|
||||
// Remove leading and trailing slashes
|
||||
|
||||
@@ -207,3 +207,19 @@ func TestCacheVersionUniquePerArtifact(t *testing.T) {
|
||||
t.Errorf("expected %d distinct cache keys, got %d", len(paths), len(seenKeys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactCacheVersion(t *testing.T) {
|
||||
tests := []struct{ filename, want string }{
|
||||
{"six-1.17.0.tar.gz", "1.17.0"},
|
||||
{"six-1.17.0-py2.py3-none-any.whl", "1.17.0+py2.py3-none-any"},
|
||||
{"numpy-1.26.0-1-cp312-cp312-manylinux.whl", "1.26.0+1-cp312-cp312-manylinux"},
|
||||
{"foo-1.0.zip", "1.0+zip"},
|
||||
{"foo-1.0.egg", "1.0+egg"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
_, ver := extractPackageFileInfo("/x/" + tt.filename)
|
||||
if got := artifactCacheVersion(tt.filename, ver); got != tt.want {
|
||||
t.Errorf("artifactCacheVersion(%q) = %q, want %q", tt.filename, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user