feat(cache): wire cache.ttl_overrides to metadata freshness

This commit is contained in:
2026-11-23 14:26:29 +00:00
parent 1256756057
commit 9b4659218c
11 changed files with 191 additions and 21 deletions
+1
View File
@@ -232,6 +232,7 @@ func (a *App) initializeComponents() error {
}
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
DefaultTTL: a.config.Cache.DefaultTTL,
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
+32
View File
@@ -3,6 +3,7 @@ package app
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"io"
"net"
@@ -18,6 +19,7 @@ import (
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
// newTestApp builds a full App on temp storage with the given config tweaks.
@@ -284,3 +286,33 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
}
}
func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`))
}))
t.Cleanup(upstream.Close)
a := newTestApp(t, func(c *config.Config) {
c.Handlers.NPM.UpstreamRegistry = upstream.URL
c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute}
})
if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK {
t.Fatalf("status = %d, body %q", code, body)
}
pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"})
if err != nil {
t.Fatal(err)
}
for _, p := range pkgs {
if p.ExpiresAt == nil {
continue
}
if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute {
t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got)
}
return
}
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
}
+19 -10
View File
@@ -80,15 +80,16 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
// Config holds cache manager configuration
type Config struct {
Now func() time.Time // Clock; nil means time.Now
DefaultTTL time.Duration // Freshness TTL for metadata entries
CleanupInterval time.Duration // How often to run cleanup
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
FailClosed bool // Refuse a package whose scan did not finish in time
Now func() time.Time // Clock; nil means time.Now
TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL
DefaultTTL time.Duration // Freshness TTL for metadata entries
CleanupInterval time.Duration // How often to run cleanup
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
FailClosed bool // Refuse a package whose scan did not finish in time
}
const defaultScanWaitTimeout = 30 * time.Second
@@ -586,7 +587,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
// entries must refresh and keep a freshness expiry.
var expiresAt *time.Time
if isMetadataEntry {
exp := now.Add(m.config.DefaultTTL)
exp := now.Add(m.metadataTTL(registry))
expiresAt = &exp
}
@@ -737,6 +738,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er
return m.deletePackage(ctx, pkg)
}
// metadataTTL returns the freshness window for a registry's metadata entries.
func (m *Manager) metadataTTL(registry string) time.Duration {
if ttl, ok := m.config.TTLOverrides[registry]; ok {
return ttl
}
return m.config.DefaultTTL
}
// deletePackage deletes a package from both storage and metadata
func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error {
// Delete from storage
+38
View File
@@ -0,0 +1,38 @@
package cache
import (
"context"
"io"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry {
t.Helper()
entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) {
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
return entry
}
func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) {
h := newIdleHarness(t, Config{
DefaultTTL: 6 * time.Hour,
TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour},
})
require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()))
require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now()))
require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl")
}
func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) {
h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}})
require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry")
}
+20 -5
View File
@@ -142,6 +142,18 @@ const DefaultMetadataTTL = 24 * time.Hour
// that send OIDC session cookies plus a long Referer or URL with 431.
const DefaultReadBufferSize = 16384
// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name.
var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"}
// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name.
func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
out := make(map[string]time.Duration, len(c.TTLOverrides))
for key, ttl := range c.TTLOverrides {
out[ttlOverrideRegistries[key]] = ttl
}
return out
}
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
const DefaultIdleTTL = 7 * 24 * time.Hour
@@ -370,11 +382,6 @@ func Default() *Config {
IdleTTL: DefaultIdleTTL,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
TTLOverrides: map[string]time.Duration{
"npm": DefaultMetadataTTL,
"pip": DefaultMetadataTTL,
"go": DefaultMetadataTTL,
},
},
Security: SecurityConfig{
Enabled: false,
@@ -526,6 +533,14 @@ func (c *Config) Validate() error {
if c.Cache.IdleTTL < 0 {
return fmt.Errorf("cache.idle_ttl cannot be negative")
}
for key, ttl := range c.Cache.TTLOverrides {
if _, ok := ttlOverrideRegistries[key]; !ok {
return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key)
}
if ttl <= 0 {
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
}
}
if c.Cache.MaxSizeBytes < 0 {
return fmt.Errorf("cache.max_size_bytes cannot be negative")
}
+49
View File
@@ -2,6 +2,7 @@ package config
import (
"os"
"path/filepath"
"regexp"
"testing"
"time"
@@ -37,3 +38,51 @@ func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) {
}
}
}
func TestTTLOverridesValidation(t *testing.T) {
for name, tc := range map[string]struct {
overrides map[string]time.Duration
wantErr string
}{
"known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""},
"pip alias": {map[string]time.Duration{"pip": time.Hour}, ""},
"unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"},
"zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"},
"negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"},
} {
t.Run(name, func(t *testing.T) {
c := Default()
c.Cache.TTLOverrides = tc.overrides
err := c.Validate()
if tc.wantErr == "" {
require.NoError(t, err)
return
}
require.ErrorContains(t, err, tc.wantErr)
})
}
}
func TestMetadataTTLOverridesNormalisesPip(t *testing.T) {
c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}}
require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides())
}
func TestDefaultsKeepNoTTLOverrides(t *testing.T) {
require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl")
}
func TestLoadReadsTTLOverridesFromYAML(t *testing.T) {
write := func(body string) string {
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return path
}
cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n"))
require.NoError(t, err)
require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides())
_, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n"))
require.ErrorContains(t, err, "cache.ttl_overrides")
}