Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -1420,7 +1420,7 @@ nuget.org reports 1900-01-01 as the publish time of an unlisted version. For a d

Helm uses each release's `created` time from the repository's `index.yaml`. Releases in cooldown are left out of the index the proxy serves, and their archives aren't served; a release without `created` is let through. Charts pulled over OCI have no publish time and aren't held back.

Cargo, RubyGems, Hex, pub.dev, Conda and Helm check artifact downloads against cooldown, including files cached before the policy changed. When a publish-time lookup fails, an already-cached file is still served; an uncached download fails with 502, or 503 with `Retry-After` when the rate-limit gate holds the request. Metadata cached within `metadata_ttl`, or served stale, can predate a release; a download of a version (or, for Conda, a file) it doesn't list fetches it again, as for npm and PyPI, and is decided on what the upstream lists now. If it can't be fetched, the lookup has failed. Helm charts are downloaded by digest and aren't covered by this yet. Conda checks timestamps per file because builds of one version can have different publish times. As in conda, a repodata `timestamp` is read as milliseconds when it is above 253402300799 (the end of year 9999 in seconds) and as seconds otherwise, since some older entries use seconds.
Cargo, RubyGems, Hex, pub.dev, Conda and Helm check artifact downloads against cooldown, including files cached before the policy changed. When a publish-time lookup fails, an already-cached file is still served; an uncached download fails with 502, or 503 with `Retry-After` when the rate-limit gate holds the request. Metadata cached within `metadata_ttl`, or served stale, can predate a release; a download of a version (or, for Conda, a file, and for Helm, a chart digest and filename) it doesn't list fetches it again, as for npm and PyPI, and is decided on what the upstream lists now. If it can't be fetched, the lookup has failed. Conda checks timestamps per file because builds of one version can have different publish times. As in conda, a repodata `timestamp` is read as milliseconds when it is above 253402300799 (the end of year 9999 in seconds) and as seconds otherwise, since some older entries use seconds.

Conda repodata and Helm indexes are parsed once per cached document for download checks. With `cache_metadata` off, the parsed index is kept for one minute, including the fetch, so an install can reuse it across files. Conda streams repodata when its compressed copy exceeds `metadata_max_size`, under the same decompressed size bound as the metadata filter.

Expand Down
52 changes: 9 additions & 43 deletions internal/handler/conda.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,53 +571,19 @@ func (h *CondaHandler) publishTime(r *http.Request, channel, arch, filename stri
}
return h.indexRepodata(res.body, res.contentEncoding)
}
// loaded is what the index was built from, unless an index built
// earlier was reused.
var loaded *metadataResult
indexKey := "conda\x00" + cacheKey
index, err := publishIndex(h.proxy, indexKey, func() metadataResult {
res := h.proxy.lookupMetadata(ctx, "conda", cacheKey, upstreamURL, "*/*", "gzip", nil)
loaded = &res
return res
}, build)
if err != nil {
return time.Time{}, false, err
}
published, listed := index[filename]
current := loaded != nil && !loaded.fromCache && !loaded.stale
if !listed && !current {
// A concurrent refetch may have replaced the index read above, so
// the file is looked up in the refetched one.
if recent, ok := recentRefetch(h.proxy, indexKey); ok {
published, listed = recent.(map[string]time.Time)[filename]
current = true
}
}
if listed || current {
// Listed, just read from upstream (streamed past metadata_max_size
// included), or refetched for a missing file within the last
// minute, without a digest to check it is current.
return published, listed && !published.IsZero(), nil
}
// Downloads that found the file missing from the same index share one
// refetch and build, which for repodata past metadata_max_size streams
// it. Later downloads use the refetched index.
refetched, err, _ := h.proxy.sharedProxy().publishIndexes.group.Do(indexKey+"\x00refetch", func() (any, error) {
res := h.proxy.refetchLacking(ctx, "conda", cacheKey, upstreamURL, "*/*", "gzip", nil)
if index, ok := keptPublishIndex(h.proxy, indexKey, res); ok {
return index, nil
}
index, err := build(res)
if err != nil {
return nil, err
}
storePublishIndex(h.proxy, indexKey, res, index, true)
return index, nil
index, err := listingPublishIndex(h.proxy, "conda\x00"+cacheKey, func() metadataResult {
return h.proxy.lookupMetadata(ctx, "conda", cacheKey, upstreamURL, "*/*", "gzip", nil)
}, func() metadataResult {
// For repodata past metadata_max_size, build streams it again.
return h.proxy.refetchLacking(ctx, "conda", cacheKey, upstreamURL, "*/*", "gzip", nil)
}, build, func(index map[string]time.Time) bool {
_, listed := index[filename]
return listed
})
if err != nil {
return time.Time{}, false, err
}
published = refetched.(map[string]time.Time)[filename]
published := index[filename]
return published, !published.IsZero(), nil
}

Expand Down
41 changes: 41 additions & 0 deletions internal/handler/download_cooldown.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,47 @@ func storePublishIndex(p *Proxy, key string, res metadataResult, index any, refe
c.entries[key] = entry
}

// listingPublishIndex is publishIndex for a download that lists checks.
// An index built from a copy cached within metadata_ttl, or served stale,
// can predate the download; when lists reports it missing, the document is
// fetched again (refetch) and the index built from what upstream lists now.
// Downloads that find it missing from the same index share one refetch, and
// for a minute after it later ones use the refetched index.
func listingPublishIndex[V any](p *Proxy, key string, load, refetch func() metadataResult, build func(metadataResult) (V, error), lists func(V) bool) (V, error) { //nolint:ireturn // V is what build returns.
// loaded is what the index was built from, unless an index built
// earlier was reused.
var loaded *metadataResult
index, err := publishIndex(p, key, func() metadataResult {
res := load()
loaded = &res
return res
}, build)
if err != nil || lists(index) || loaded != nil && !loaded.fromCache && !loaded.stale {
return index, err
}
// A concurrent refetch may have replaced the index read above.
if recent, ok := recentRefetch(p, key); ok {
return recent.(V), nil
}
refetched, err, _ := p.sharedProxy().publishIndexes.group.Do(key+"\x00refetch", func() (any, error) {
res := refetch()
if index, ok := keptPublishIndex(p, key, res); ok {
return index, nil
}
index, err := build(res)
if err != nil {
return nil, err
}
storePublishIndex(p, key, res, index, true)
return index, nil
})
if err != nil {
var zero V
return zero, err
}
return refetched.(V), nil
}

// readListed reads a version's entry from a metadata document fetched
// through the metadata cache. read reports whether the document lists the
// version at all. A copy cached within metadata_ttl, or served stale, can
Expand Down
85 changes: 77 additions & 8 deletions internal/handler/download_cooldown_missing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ func TestDownloadCooldownRefetchesMetadataLackingTheVersion(t *testing.T) {
}

for _, c := range downloadCooldownCases() {
if c.ecosystem == "helm" {
// Charts are downloaded by digest, which a stale index lacks
// differently; not covered here.
continue
}
// expired has the cached copy past metadata_ttl, so it is served
// stale while the upstream is down.
for _, variant := range []struct {
Expand Down Expand Up @@ -125,9 +120,6 @@ func checkRefetch(t *testing.T, c downloadCooldownCase, before, after map[string
func TestDownloadCooldownFetchesUnlistedVersionOnce(t *testing.T) {
times := map[string]time.Time{cooldownOldVersion: time.Now().Add(-30 * 24 * time.Hour)}
for _, c := range downloadCooldownCases() {
if c.ecosystem == "helm" {
continue
}
t.Run(c.ecosystem, func(t *testing.T) {
requests := func(version string) int32 {
var n atomic.Int32
Expand Down Expand Up @@ -509,3 +501,80 @@ func TestRecentRefetchReturnsTheRefetchedIndex(t *testing.T) {
t.Errorf("new.conda published %v, want %v", got, released)
}
}

// TestHelmChartMissingFromCachedIndexIsFetched checks a chart download that
// an index cached within metadata_ttl doesn't list, past its cooldown, is
// served from what upstream's index lists now.
func TestHelmChartMissingFromCachedIndexIsFetched(t *testing.T) {
c := helmCooldownCase(t)
old := time.Now().Add(-30 * 24 * time.Hour)
var released atomic.Bool
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
times := map[string]time.Time{cooldownOldVersion: old}
if released.Load() {
times[cooldownRecentVersion] = old
}
c.metadata(w, r, times)
}))
defer upstream.Close()
proxy, _, _, fetcher := setupTestProxy(t)
proxy.HTTPClient = upstream.Client()
proxy.CacheMetadata = true
proxy.MetadataTTL = time.Hour
proxy.Cooldown = &cooldown.Config{Default: "7d"}
fetcher.artifact = &fetch.Artifact{Body: io.NopCloser(strings.NewReader(chartContent(cooldownRecentVersion)))}
handler := c.handler(proxy, upstream.URL)
get := func(version string) int {
w := httptest.NewRecorder()
handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, c.path(version), nil))
return w.Code
}

c.seedCachedArtifact(t, proxy, cooldownOldVersion)
if code := get(cooldownOldVersion); code != http.StatusOK {
t.Fatalf("old chart: status %d", code)
}
released.Store(true)
if code := get(cooldownRecentVersion); code != http.StatusOK {
t.Errorf("chart listed upstream past its cooldown: status %d, want 200", code)
}
}

// TestHelmNeverListedChartRefetchesOncePerKeep is
// TestCondaNeverListedFileRefetchesOncePerKeep for Helm.
func TestHelmNeverListedChartRefetchesOncePerKeep(t *testing.T) {
c := helmCooldownCase(t)
var requests atomic.Int32
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
c.metadata(w, r, map[string]time.Time{cooldownOldVersion: time.Now().Add(-30 * 24 * time.Hour)})
}))
defer upstream.Close()
proxy, _, _, fetcher := setupTestProxy(t)
fetcher.fetchErr = errors.New("not fetched")
proxy.HTTPClient = upstream.Client()
proxy.Cooldown = &cooldown.Config{Default: "7d"}
handler := c.handler(proxy, upstream.URL)
for range 3 {
w := httptest.NewRecorder()
handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, c.path("9.9.9"), nil))
if w.Code != http.StatusNotFound {
t.Fatalf("unlisted chart: status %d, want 404", w.Code)
}
}
// The first download reads the index, the second refetches it.
if got := requests.Load(); got != 2 {
t.Errorf("index fetched %d times, want 2", got)
}
}

func helmCooldownCase(t *testing.T) downloadCooldownCase {
t.Helper()
for _, c := range downloadCooldownCases() {
if c.ecosystem == "helm" {
return c
}
}
t.Fatal("no helm case")
return downloadCooldownCase{}
}
32 changes: 27 additions & 5 deletions internal/handler/helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
const (
helmMetadataEcosystem = "helm"
helmIndexFilename = "index.yaml"
helmIndexAccept = "application/x-yaml, text/yaml;q=0.9, */*;q=0.1"
sha256HexLength = 64
)

Expand Down Expand Up @@ -123,7 +124,7 @@ func (h *HelmHandler) handleChart(w http.ResponseWriter, r *http.Request) {
var charts *helmChartLookup
if h.proxy.cooldownEnabled() {
var err error
charts, err = h.downloadChartLookup(r, repository, upstreamURL)
charts, err = h.downloadChartLookup(r, repository, upstreamURL, digest, filename)
if err != nil {
cached, cacheErr := h.proxy.GetCachedArtifact(r.Context(), helmMetadataEcosystem, repository, digest, filename)
if cacheErr == nil && cached != nil {
Expand Down Expand Up @@ -211,7 +212,7 @@ func (h *HelmHandler) fetchIndex(ctx context.Context, repository, upstreamURL st
helmMetadataEcosystem,
h.indexCacheKey(repository, upstreamURL),
upstreamURL+"/"+helmIndexFilename,
"application/x-yaml, text/yaml;q=0.9, */*;q=0.1",
helmIndexAccept,
nil,
)
}
Expand Down Expand Up @@ -402,18 +403,39 @@ func (h *HelmHandler) buildChartLookup(upstreamURL string, body []byte) (*helmCh
return lookup, nil
}

func (h *HelmHandler) downloadChartLookup(r *http.Request, repository, upstreamURL string) (*helmChartLookup, error) {
key := "helm\x00" + h.indexCacheKey(repository, upstreamURL)
return publishIndex(h.proxy, key, func() metadataResult {
// downloadChartLookup returns the charts the index lists, for a download
// checked against cooldown. An index that doesn't list the download can
// predate the chart, and is fetched again (listingPublishIndex).
func (h *HelmHandler) downloadChartLookup(r *http.Request, repository, upstreamURL, digest, filename string) (*helmChartLookup, error) {
cacheKey := h.indexCacheKey(repository, upstreamURL)
return listingPublishIndex(h.proxy, "helm\x00"+cacheKey, func() metadataResult {
return h.fetchIndex(r.Context(), repository, upstreamURL)
}, func() metadataResult {
return h.proxy.refetchLacking(r.Context(), helmMetadataEcosystem, cacheKey,
upstreamURL+"/"+helmIndexFilename, helmIndexAccept, "", nil)
}, func(res metadataResult) (*helmChartLookup, error) {
if res.err != nil {
return nil, res.err
}
return h.chartLookup(repository, upstreamURL, res)
}, func(charts *helmChartLookup) bool {
return charts.lists(digest, filename)
})
}

// lists reports whether the index lists an HTTP download of filename with
// the digest.
func (c *helmChartLookup) lists(digest, filename string) bool {
for _, chart := range c.byDigest[digest] {
for _, download := range chart.downloads {
if download.filename == filename {
return true
}
}
}
return false
}

func (h *HelmHandler) withholdChart(w http.ResponseWriter, charts *helmChartLookup, digest, filename string) bool {
withheld := false
for _, chart := range charts.byDigest[digest] {
Expand Down
Loading