mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-01 07:05:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c98720c02e | ||
|
|
9a44683fbd | ||
|
|
d6edd40d79 | ||
|
|
99c885cd88 |
@@ -233,7 +233,9 @@ security:
|
||||
enabled: true
|
||||
|
||||
cache:
|
||||
default_ttl: 86400 # 24 hours in seconds
|
||||
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
|
||||
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
|
||||
cleanup_interval: 1h
|
||||
|
||||
logging:
|
||||
level: "info" # debug, info, warn, error
|
||||
@@ -245,6 +247,15 @@ upstream:
|
||||
go: "https://proxy.golang.org"
|
||||
```
|
||||
|
||||
#### Cache cleanup
|
||||
|
||||
Every `cleanup_interval` the cleanup run removes:
|
||||
|
||||
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
|
||||
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl`. They refresh on the next request.
|
||||
|
||||
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
All configuration values can be overridden with environment variables:
|
||||
|
||||
+2
-1
@@ -89,8 +89,9 @@ metadata:
|
||||
log_level: "warn" # GORM log level: silent, error, warn, info
|
||||
|
||||
cache:
|
||||
default_ttl: "168h" # 7 days
|
||||
default_ttl: "168h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
cleanup_interval: "1h"
|
||||
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
max_size_bytes: 536870912000 # 500GB
|
||||
per_project_quota: 53687091200 # 50GB
|
||||
ttl_overrides:
|
||||
|
||||
@@ -47,8 +47,9 @@
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="2">
|
||||
<span class="flex w-full min-w-0 items-center justify-between gap-4">
|
||||
<span class="min-w-0 text-start">
|
||||
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
|
||||
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<span class="w-full min-w-0 text-start sm:w-auto">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
@@ -115,6 +116,7 @@
|
||||
:page="currentPage"
|
||||
:total="allGroupedPackages.length"
|
||||
:page-size="itemsPerPage"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -207,4 +207,46 @@ describe('Stats.vue', () => {
|
||||
expect(wrapper.findAll('tbody th')).toHaveLength(0)
|
||||
expect(wrapper.text()).toContain('No registries reported')
|
||||
})
|
||||
|
||||
describe('idle eviction note', () => {
|
||||
const baseStats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
|
||||
async function render(idleTtl?: number) {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
|
||||
await wrapper.vm.$nextTick()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
it.each([
|
||||
[604800, 'Cached items not requested for 7 days are removed.'],
|
||||
[86400, 'Cached items not requested for 1 day are removed.'],
|
||||
[129600, 'Cached items not requested for 36 hours are removed.'],
|
||||
[5400, 'Cached items not requested for 90 minutes are removed.'],
|
||||
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
|
||||
const wrapper = await render(seconds)
|
||||
expect(wrapper.text()).toContain(sentence)
|
||||
})
|
||||
|
||||
it('hides the note when idle eviction is off', async () => {
|
||||
const wrapper = await render(0)
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
|
||||
it('hides the note when the API sends no idle_ttl', async () => {
|
||||
const wrapper = await render()
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<Alert v-if="idleTtl > 0" variant="info">
|
||||
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Overall statistics</CardTitle>
|
||||
@@ -91,6 +95,8 @@ import { storeToRefs } from 'pinia'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
@@ -103,7 +109,7 @@ import {
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
@@ -162,6 +168,8 @@ const registries = computed(() => {
|
||||
}))
|
||||
})
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
|
||||
|
||||
const storagePercentage = computed(() => {
|
||||
const totalSize = stats.value?.total_size || 0
|
||||
const maxSize = stats.value?.max_cache_size || 1
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatDuration } from './format'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it.each([
|
||||
[604800, '7 days'],
|
||||
[86400, '1 day'],
|
||||
[129600, '36 hours'],
|
||||
[3600, '1 hour'],
|
||||
[5400, '90 minutes'],
|
||||
[60, '1 minute'],
|
||||
])('formats %i seconds as %s', (seconds, expected) => {
|
||||
expect(formatDuration(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,21 @@ export function formatBytes(bytes: number): string {
|
||||
return Math.round((bytes / Math.pow(BYTES_PER_UNIT, i)) * 100) / 100 + ' ' + BYTE_UNITS[i]
|
||||
}
|
||||
|
||||
const SECONDS_PER_DAY = 86400
|
||||
const SECONDS_PER_HOUR = 3600
|
||||
const SECONDS_PER_MINUTE = 60
|
||||
|
||||
function plural(n: number, unit: string): string {
|
||||
return `${n} ${unit}${n === 1 ? '' : 's'}`
|
||||
}
|
||||
|
||||
/** Whole days, hours or minutes, using the largest unit that divides the span evenly. */
|
||||
export function formatDuration(seconds: number): string {
|
||||
if (seconds % SECONDS_PER_DAY === 0) return plural(seconds / SECONDS_PER_DAY, 'day')
|
||||
if (seconds % SECONDS_PER_HOUR === 0) return plural(seconds / SECONDS_PER_HOUR, 'hour')
|
||||
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
|
||||
}
|
||||
|
||||
export function formatDate(date: string): string {
|
||||
if (!date) return 'N/A'
|
||||
const parsed = new Date(date)
|
||||
|
||||
@@ -40,6 +40,8 @@ export interface Stats {
|
||||
scanned_packages: number
|
||||
vulnerable_packages: number
|
||||
blocked_packages: number
|
||||
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
|
||||
idle_ttl?: number
|
||||
}
|
||||
|
||||
export const usePackageStore = defineStore('packages', () => {
|
||||
|
||||
@@ -15,6 +15,7 @@ require (
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/lib/pq v1.12.3
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
github.com/prometheus/client_model v0.6.3
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/viper v1.21.0
|
||||
@@ -110,7 +111,6 @@ require (
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/philhofer/fwd v1.2.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.74.0 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.12.0 // indirect
|
||||
|
||||
@@ -73,6 +73,7 @@ data:
|
||||
cache:
|
||||
default_ttl: {{ .Values.cache.defaultTTL | quote }}
|
||||
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
|
||||
idle_ttl: {{ .Values.cache.idleTTL | quote }}
|
||||
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
|
||||
per_project_quota: {{ .Values.cache.perProjectQuota }}
|
||||
ttl_overrides:
|
||||
|
||||
@@ -377,6 +377,7 @@ migration:
|
||||
cache:
|
||||
defaultTTL: "168h" # 7 days
|
||||
cleanupInterval: "1h"
|
||||
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
maxSizeBytes: 536870912000 # 500GB
|
||||
perProjectQuota: 53687091200 # 50GB
|
||||
ttlOverrides:
|
||||
|
||||
@@ -233,6 +233,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,
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
})
|
||||
|
||||
@@ -407,6 +407,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
"total_downloads": cacheStats.TotalDownloads,
|
||||
"total_size": cacheStats.TotalSize,
|
||||
"max_cache_size": a.config.Cache.MaxSizeBytes,
|
||||
"idle_ttl": int64(a.config.Cache.IdleTTL / time.Second), // seconds, 0 = idle eviction off
|
||||
"cache_hits": cacheStats.TotalDownloads,
|
||||
"cache_misses": 0, // TODO: Track cache misses
|
||||
"cache_evictions": 0, // TODO: Track evictions
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func TestStatsReportsIdleTTLSeconds(t *testing.T) {
|
||||
for name, tt := range map[string]struct {
|
||||
idle time.Duration
|
||||
want float64
|
||||
}{
|
||||
"a week": {idle: 168 * time.Hour, want: 604800},
|
||||
"disabled": {idle: 0, want: 0},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Cache.IdleTTL = tt.idle })
|
||||
|
||||
code, _, body := doRequest(t, a, "/api/stats", nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("status %d, body %q", code, body)
|
||||
}
|
||||
var resp struct {
|
||||
Stats map[string]any `json:"stats"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &resp); err != nil {
|
||||
t.Fatalf("decode %q: %v", body, err)
|
||||
}
|
||||
got, ok := resp.Stats["idle_ttl"].(float64)
|
||||
if !ok || got != tt.want {
|
||||
t.Errorf("stats.idle_ttl = %v, want %v (body %s)", resp.Stats["idle_ttl"], tt.want, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -147,7 +147,16 @@ func (f *fakeStore) GetTimeSeriesStats(context.Context, string, string) (*metada
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) AggregateDownloadData(context.Context) error { return metadata.ErrNotImplemented }
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
func (f *fakeStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
|
||||
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
|
||||
func fastCfg() Config { return Config{BcryptCost: bcrypt.MinCost} }
|
||||
|
||||
Vendored
+131
-34
@@ -81,17 +81,28 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
|
||||
|
||||
// Config holds cache manager configuration
|
||||
type Config struct {
|
||||
DefaultTTL time.Duration // Default TTL for cached packages
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
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
|
||||
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
|
||||
|
||||
// cleanupBatchSize bounds how many rows one cleanup query reads.
|
||||
const cleanupBatchSize = metadata.DefaultBatchSize
|
||||
|
||||
// Eviction metric reasons.
|
||||
const (
|
||||
evictReasonTTL = "ttl"
|
||||
evictReasonIdle = "idle"
|
||||
)
|
||||
|
||||
// scannerToggle is implemented by scanners that can be switched off.
|
||||
type scannerToggle interface {
|
||||
Enabled() bool
|
||||
@@ -155,6 +166,10 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
log.Info().Msg("Cache manager initialized with analytics tracking enabled")
|
||||
}
|
||||
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
|
||||
if config.DefaultTTL == 0 {
|
||||
config.DefaultTTL = 7 * 24 * time.Hour // 7 days default
|
||||
}
|
||||
@@ -191,6 +206,9 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
// Rows cached before idle eviction existed carry an age-based expiry.
|
||||
manager.clearArtifactExpiry(bgCtx)
|
||||
|
||||
// Start background cleanup worker
|
||||
manager.cleanupWG.Add(1)
|
||||
go manager.cleanupWorker()
|
||||
@@ -241,9 +259,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err == nil {
|
||||
// Package found in metadata, check if expired
|
||||
if pkg.ExpiresAt != nil && time.Now().After(*pkg.ExpiresAt) {
|
||||
if pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt) {
|
||||
log.Debug().Str("package", name).Str("version", version).Msg("Package expired, re-fetching")
|
||||
metrics.RecordCacheEviction("ttl")
|
||||
metrics.RecordCacheEviction(evictReasonTTL)
|
||||
// Delete expired package
|
||||
_ = m.deletePackage(ctx, pkg) // #nosec G104 -- Async cleanup
|
||||
} else {
|
||||
@@ -297,8 +315,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
// entries (index pages, lists, .mod/.info) are not scannable
|
||||
// packages, so skip them to avoid a bogus "clean" verdict and
|
||||
// the extra database round-trip.
|
||||
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
|
||||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
|
||||
isMetadataEntry := metadata.IsMetadataEntry(name, version)
|
||||
if m.scanner != nil && !isMetadataEntry {
|
||||
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
|
||||
if vulnErr != nil {
|
||||
@@ -553,8 +570,16 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
_ = tempFile.Close() // #nosec G104 -- cleanup; scan may still read the file
|
||||
|
||||
// Create metadata entry
|
||||
now := time.Now()
|
||||
expiresAt := now.Add(m.config.DefaultTTL)
|
||||
now := m.now()
|
||||
isMetadataEntry := metadata.IsMetadataEntry(name, version)
|
||||
|
||||
// Artifacts are immutable, so only idle eviction removes them; metadata
|
||||
// entries must refresh and keep a freshness expiry.
|
||||
var expiresAt *time.Time
|
||||
if isMetadataEntry {
|
||||
exp := now.Add(m.config.DefaultTTL)
|
||||
expiresAt = &exp
|
||||
}
|
||||
|
||||
pkg := &metadata.Package{
|
||||
ID: uuid.New().String(),
|
||||
@@ -570,7 +595,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
AuthProvider: authProvider,
|
||||
CachedAt: now,
|
||||
LastAccessed: now,
|
||||
ExpiresAt: &expiresAt,
|
||||
ExpiresAt: expiresAt,
|
||||
DownloadCount: 0,
|
||||
Metadata: make(map[string]string),
|
||||
}
|
||||
@@ -583,8 +608,6 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
// TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed
|
||||
// based on upstream Cache-Control. Plumbing per-response TTL from registry handlers
|
||||
// is out of scope here and tracked separately.
|
||||
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
|
||||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
|
||||
if err := m.metadata.SavePackage(ctx, pkg); err != nil {
|
||||
// Clean up storage if metadata save fails
|
||||
_ = m.storage.Delete(ctx, storageKey) // #nosec G104 -- Cleanup, error logged
|
||||
@@ -738,7 +761,7 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanupWorker runs periodic cleanup of expired packages.
|
||||
// cleanupWorker runs periodic cleanup of expired and idle packages.
|
||||
// Exits when stopCh is closed (via Close()).
|
||||
func (m *Manager) cleanupWorker() {
|
||||
defer m.cleanupWG.Done()
|
||||
@@ -751,39 +774,113 @@ func (m *Manager) cleanupWorker() {
|
||||
case <-m.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
ctx := context.Background()
|
||||
m.cleanup(ctx)
|
||||
m.cleanup(m.bgCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cleanup removes expired packages
|
||||
func (m *Manager) cleanup(ctx context.Context) {
|
||||
log.Debug().Msg("Starting cleanup worker")
|
||||
func (m *Manager) now() time.Time {
|
||||
return m.config.Now()
|
||||
}
|
||||
|
||||
// List all packages
|
||||
packages, err := m.metadata.ListPackages(ctx, &metadata.ListOptions{})
|
||||
// clearArtifactExpiry drops the age-based expiry that older versions set on artifacts.
|
||||
func (m *Manager) clearArtifactExpiry(ctx context.Context) {
|
||||
cleared, err := m.metadata.ClearArtifactExpiry(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages for cleanup")
|
||||
log.Error().Err(err).Msg("Failed to clear artifact expiry")
|
||||
return
|
||||
}
|
||||
if cleared > 0 {
|
||||
log.Info().Int64("count", cleared).Msg("Cleared age-based expiry from cached artifacts")
|
||||
}
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var cleaned int
|
||||
// purgeResult totals the packages one purge pass removed.
|
||||
type purgeResult struct {
|
||||
bytes int64
|
||||
count int
|
||||
}
|
||||
|
||||
for _, pkg := range packages {
|
||||
if pkg.ExpiresAt != nil && now.After(*pkg.ExpiresAt) {
|
||||
if err := m.deletePackage(ctx, pkg); err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to clean up expired package")
|
||||
// purge deletes packages in bounded batches until the list query runs dry.
|
||||
// stillDue re-checks each package just before deletion so one requested after
|
||||
// the batch was read is kept.
|
||||
func (m *Manager) purge(
|
||||
ctx context.Context,
|
||||
reason string,
|
||||
list func(limit int) ([]*metadata.Package, error),
|
||||
stillDue func(*metadata.Package) bool,
|
||||
) purgeResult {
|
||||
var res purgeResult
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
for ctx.Err() == nil {
|
||||
batch, err := list(cleanupBatchSize)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("reason", reason).Msg("Failed to list packages for cleanup")
|
||||
return res
|
||||
}
|
||||
|
||||
unseen := 0
|
||||
for _, pkg := range batch {
|
||||
key := m.generateStorageKey(pkg.Registry, pkg.Name, pkg.Version)
|
||||
if _, dup := seen[key]; dup {
|
||||
continue
|
||||
}
|
||||
cleaned++
|
||||
seen[key] = struct{}{}
|
||||
unseen++
|
||||
|
||||
current, err := m.metadata.GetPackage(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if err != nil || current == nil || !stillDue(current) {
|
||||
continue
|
||||
}
|
||||
if err := m.deletePackage(ctx, current); err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Str("reason", reason).Msg("Failed to clean up package")
|
||||
continue
|
||||
}
|
||||
res.count++
|
||||
res.bytes += current.Size
|
||||
metrics.RecordCacheEviction(reason)
|
||||
}
|
||||
|
||||
// A short batch is the last one; a batch of only repeats means every
|
||||
// remaining row failed to delete.
|
||||
if len(batch) < cleanupBatchSize || unseen == 0 {
|
||||
return res
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
if cleaned > 0 {
|
||||
log.Info().Int("count", cleaned).Msg("Cleanup completed")
|
||||
// cleanup removes metadata entries past their freshness expiry and, when
|
||||
// IdleTTL is set, every package not requested within IdleTTL.
|
||||
func (m *Manager) cleanup(ctx context.Context) {
|
||||
start := m.now()
|
||||
log.Debug().Msg("Starting cleanup worker")
|
||||
|
||||
m.clearArtifactExpiry(ctx)
|
||||
|
||||
expired := m.purge(ctx, evictReasonTTL,
|
||||
func(limit int) ([]*metadata.Package, error) {
|
||||
return m.metadata.ListExpiredPackages(ctx, start, limit)
|
||||
},
|
||||
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(start) })
|
||||
|
||||
var idle purgeResult
|
||||
if m.config.IdleTTL > 0 {
|
||||
cutoff := start.Add(-m.config.IdleTTL)
|
||||
idle = m.purge(ctx, evictReasonIdle,
|
||||
func(limit int) ([]*metadata.Package, error) {
|
||||
return m.metadata.ListIdlePackages(ctx, cutoff, limit)
|
||||
},
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Int("expired", expired.count).
|
||||
Int("idle", idle.count).
|
||||
Int64("bytes_freed", expired.bytes+idle.bytes).
|
||||
Dur("idle_ttl", m.config.IdleTTL).
|
||||
Msg("Cleanup completed")
|
||||
}
|
||||
|
||||
// generateStorageKey generates a storage key for a package
|
||||
|
||||
Vendored
+11
@@ -230,6 +230,17 @@ func (m *MockMetadataStore) AggregateDownloadData(ctx context.Context) error {
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
// The idle-eviction queries are not mocked per test: no expiry, no idle rows.
|
||||
func (m *MockMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
|
||||
// API key methods are not used by the cache package; stub them out so the
|
||||
// mock continues to satisfy metadata.MetadataStore after the interface gained
|
||||
// API key persistence methods.
|
||||
|
||||
Vendored
+398
@@ -0,0 +1,398 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func evictions(c prometheus.Counter) float64 {
|
||||
var m dto.Metric
|
||||
if err := c.Write(&m); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return m.GetCounter().GetValue()
|
||||
}
|
||||
|
||||
type fakeClock struct {
|
||||
now time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newFakeClock() *fakeClock {
|
||||
return &fakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
|
||||
}
|
||||
|
||||
func (c *fakeClock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
|
||||
func (c *fakeClock) Advance(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.now = c.now.Add(d)
|
||||
}
|
||||
|
||||
type memStorage struct {
|
||||
storage.StorageBackend
|
||||
objects map[string][]byte
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newMemStorage() *memStorage { return &memStorage{objects: map[string][]byte{}} }
|
||||
|
||||
func (s *memStorage) Get(_ context.Context, key string) (io.ReadCloser, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
b, ok := s.objects[key]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(b)), nil
|
||||
}
|
||||
|
||||
func (s *memStorage) Put(_ context.Context, key string, data io.Reader, _ *storage.PutOptions) error {
|
||||
b, err := io.ReadAll(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.objects[key] = b
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStorage) Delete(_ context.Context, key string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStorage) GetQuota(context.Context) (*storage.QuotaInfo, error) {
|
||||
return &storage.QuotaInfo{}, nil
|
||||
}
|
||||
|
||||
func (s *memStorage) Close() error { return nil }
|
||||
|
||||
func (s *memStorage) has(key string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.objects[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// memMetadata mirrors the real store's contract: UpdateDownloadCount stamps
|
||||
// last_accessed, and the list queries are ordered and bounded.
|
||||
type memMetadata struct {
|
||||
metadata.MetadataStore
|
||||
clock *fakeClock
|
||||
pkgs map[string]*metadata.Package
|
||||
onList func()
|
||||
maxLimit int
|
||||
mu sync.Mutex
|
||||
idleCalls int
|
||||
}
|
||||
|
||||
func newMemMetadata(clock *fakeClock) *memMetadata {
|
||||
return &memMetadata{clock: clock, pkgs: map[string]*metadata.Package{}}
|
||||
}
|
||||
|
||||
func pkgKey(registry, name, version string) string { return registry + "/" + name + "/" + version }
|
||||
|
||||
func (m *memMetadata) SavePackage(_ context.Context, pkg *metadata.Package) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cp := *pkg
|
||||
m.pkgs[pkgKey(pkg.Registry, pkg.Name, pkg.Version)] = &cp
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) GetPackage(_ context.Context, registry, name, version string) (*metadata.Package, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
p, ok := m.pkgs[pkgKey(registry, name, version)]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
cp := *p
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) DeletePackage(_ context.Context, registry, name, version string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.pkgs, pkgKey(registry, name, version))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) UpdateDownloadCount(_ context.Context, registry, name, version string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
p, ok := m.pkgs[pkgKey(registry, name, version)]
|
||||
if !ok {
|
||||
return errors.New("not found")
|
||||
}
|
||||
p.DownloadCount++
|
||||
p.LastAccessed = m.clock.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) list(limit int, match func(*metadata.Package) bool, less func(a, b *metadata.Package) bool) []*metadata.Package {
|
||||
m.mu.Lock()
|
||||
if limit > m.maxLimit {
|
||||
m.maxLimit = limit
|
||||
}
|
||||
var out []*metadata.Package
|
||||
for _, p := range m.pkgs {
|
||||
if match(p) {
|
||||
cp := *p
|
||||
out = append(out, &cp)
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
sort.Slice(out, func(i, j int) bool { return less(out[i], out[j]) })
|
||||
if limit > 0 && len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
if m.onList != nil {
|
||||
m.onList()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *memMetadata) ListIdlePackages(_ context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
m.mu.Lock()
|
||||
m.idleCalls++
|
||||
m.mu.Unlock()
|
||||
return m.list(limit,
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
|
||||
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) ListExpiredPackages(_ context.Context, before time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return m.list(limit,
|
||||
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(before) },
|
||||
func(a, b *metadata.Package) bool { return a.ExpiresAt.Before(*b.ExpiresAt) }), nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
var n int64
|
||||
for _, p := range m.pkgs {
|
||||
if p.ExpiresAt != nil && !metadata.IsMetadataEntry(p.Name, p.Version) {
|
||||
p.ExpiresAt = nil
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (m *memMetadata) Close() error { return nil }
|
||||
|
||||
func (m *memMetadata) count() int {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return len(m.pkgs)
|
||||
}
|
||||
|
||||
type idleHarness struct {
|
||||
mgr *Manager
|
||||
clock *fakeClock
|
||||
meta *memMetadata
|
||||
store *memStorage
|
||||
fetches int
|
||||
}
|
||||
|
||||
func newIdleHarness(t *testing.T, cfg Config) *idleHarness {
|
||||
t.Helper()
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
h.meta = newMemMetadata(h.clock)
|
||||
cfg.Now = h.clock.Now
|
||||
if cfg.CleanupInterval == 0 {
|
||||
cfg.CleanupInterval = 24 * time.Hour
|
||||
}
|
||||
return h.start(t, cfg)
|
||||
}
|
||||
|
||||
func (h *idleHarness) start(t *testing.T, cfg Config) *idleHarness {
|
||||
t.Helper()
|
||||
mgr, err := New(h.store, h.meta, nil, nil, cfg)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
h.mgr = mgr
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *idleHarness) get(t *testing.T, name, version string) *CacheEntry {
|
||||
t.Helper()
|
||||
entry, err := h.mgr.Get(context.Background(), "npm", name, version, func(context.Context) (*FetchResult, error) {
|
||||
h.fetches++
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
return entry
|
||||
}
|
||||
|
||||
func (h *idleHarness) exists(name, version string) bool {
|
||||
_, err := h.meta.GetPackage(context.Background(), "npm", name, version)
|
||||
return err == nil && h.store.has(fmt.Sprintf("npm/%s/%s", name, version))
|
||||
}
|
||||
|
||||
const (
|
||||
day = 24 * time.Hour
|
||||
artifactVer = "4.17.21"
|
||||
)
|
||||
|
||||
func TestIdleTTL_AccessedArtifactSurvivesDefaultTTL(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
|
||||
entry := h.get(t, "lodash", artifactVer)
|
||||
require.Nil(t, entry.Package.ExpiresAt, "an artifact is immutable: no age-based expiry")
|
||||
|
||||
h.clock.Advance(2 * day)
|
||||
h.get(t, "lodash", artifactVer) // touches last_accessed
|
||||
h.clock.Advance(2 * day) // 4 days after caching, past DefaultTTL; idle for only 2
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.True(t, h.exists("lodash", artifactVer))
|
||||
h.get(t, "lodash", artifactVer)
|
||||
require.Equal(t, 1, h.fetches, "served from cache, not re-fetched")
|
||||
}
|
||||
|
||||
func TestIdleTTL_IdleArtifactIsDeletedFromStorageAndMetadata(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.get(t, "left-pad", "1.3.0")
|
||||
h.clock.Advance(2 * day)
|
||||
h.get(t, "left-pad", "1.3.0") // keeps left-pad alive
|
||||
h.clock.Advance(2 * day) // lodash idle for 4 days
|
||||
|
||||
before := evictions(metrics.CacheEvictions.WithLabelValues("idle"))
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.False(t, h.exists("lodash", artifactVer))
|
||||
require.False(t, h.store.has("npm/lodash/"+artifactVer), "storage object removed")
|
||||
_, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
|
||||
require.Error(t, err, "metadata row removed")
|
||||
require.True(t, h.exists("left-pad", "1.3.0"))
|
||||
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("idle")))
|
||||
}
|
||||
|
||||
func TestIdleTTL_IdleMetadataEntryIsDeleted(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: 3 * day})
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.clock.Advance(4 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.False(t, h.exists("lodash", "metadata"))
|
||||
}
|
||||
|
||||
func TestIdleTTL_MetadataEntryPastFreshnessTTLIsRefetched(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 7 * day})
|
||||
entry := h.get(t, "lodash", "metadata")
|
||||
require.NotNil(t, entry.Package.ExpiresAt)
|
||||
require.Equal(t, h.clock.Now().Add(time.Hour), *entry.Package.ExpiresAt)
|
||||
|
||||
h.clock.Advance(30 * time.Minute)
|
||||
h.get(t, "lodash", "metadata")
|
||||
require.Equal(t, 1, h.fetches, "still fresh")
|
||||
|
||||
h.clock.Advance(2 * time.Hour) // recently requested, but stale
|
||||
before := evictions(metrics.CacheEvictions.WithLabelValues("ttl"))
|
||||
h.get(t, "lodash", "metadata")
|
||||
require.Equal(t, 2, h.fetches, "stale metadata is re-fetched")
|
||||
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("ttl")))
|
||||
}
|
||||
|
||||
func TestIdleTTL_CleanupRemovesExpiredMetadataOnly(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 30 * day})
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.clock.Advance(2 * time.Hour)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.False(t, h.exists("lodash", "metadata"), "past its freshness expiry")
|
||||
require.True(t, h.exists("lodash", artifactVer), "artifacts have no age-based expiry")
|
||||
}
|
||||
|
||||
func TestIdleTTL_ZeroDisablesIdleEviction(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 0})
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.clock.Advance(365 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.True(t, h.exists("lodash", artifactVer))
|
||||
require.Zero(t, h.meta.idleCalls, "no idle query when disabled")
|
||||
}
|
||||
|
||||
func TestIdleTTL_CleanupReadsBoundedBatches(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: day, IdleTTL: day})
|
||||
const total = 1250
|
||||
for i := 0; i < total; i++ {
|
||||
name := fmt.Sprintf("pkg-%d", i)
|
||||
h.get(t, name, "1.0.0")
|
||||
}
|
||||
h.clock.Advance(2 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Zero(t, h.meta.count(), "every idle item removed across batches")
|
||||
require.Positive(t, h.meta.maxLimit)
|
||||
require.LessOrEqual(t, h.meta.maxLimit, cleanupBatchSize, "never loads more than one batch")
|
||||
require.Zero(t, len(h.store.objects))
|
||||
}
|
||||
|
||||
func TestIdleTTL_ItemRequestedDuringCleanupSurvives(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: day})
|
||||
h.get(t, "lodash", artifactVer)
|
||||
h.clock.Advance(2 * day)
|
||||
h.meta.onList = func() {
|
||||
h.meta.onList = nil
|
||||
require.NoError(t, h.meta.UpdateDownloadCount(context.Background(), "npm", "lodash", artifactVer))
|
||||
}
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.True(t, h.exists("lodash", artifactVer), "a request between listing and deleting wins")
|
||||
}
|
||||
|
||||
func TestIdleTTL_StartupClearsLegacyArtifactExpiry(t *testing.T) {
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
h.meta = newMemMetadata(h.clock)
|
||||
past := h.clock.Now().Add(-day)
|
||||
require.NoError(t, h.meta.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: "lodash", Version: artifactVer, StorageKey: "npm/lodash/" + artifactVer,
|
||||
LastAccessed: h.clock.Now(), ExpiresAt: &past,
|
||||
}))
|
||||
require.NoError(t, h.store.Put(context.Background(), "npm/lodash/"+artifactVer, strings.NewReader("x"), nil))
|
||||
|
||||
h.start(t, Config{DefaultTTL: 7 * day, IdleTTL: 7 * day, Now: h.clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
|
||||
h.get(t, "lodash", artifactVer)
|
||||
require.Zero(t, h.fetches, "the legacy 7-day expiry no longer evicts a popular artifact")
|
||||
p, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, p.ExpiresAt)
|
||||
}
|
||||
@@ -133,11 +133,15 @@ type MySQLConfig struct {
|
||||
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
|
||||
}
|
||||
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
// CacheConfig contains cache management configuration
|
||||
type CacheConfig struct {
|
||||
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
|
||||
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
|
||||
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
|
||||
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
}
|
||||
@@ -353,6 +357,7 @@ func Default() *Config {
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: 7 * 24 * time.Hour,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
@@ -505,6 +510,9 @@ func (c *Config) Validate() error {
|
||||
if c.Cache.DefaultTTL < 0 {
|
||||
return fmt.Errorf("cache.default_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.IdleTTL < 0 {
|
||||
return fmt.Errorf("cache.idle_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.MaxSizeBytes < 0 {
|
||||
return fmt.Errorf("cache.max_size_bytes cannot be negative")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func loadCacheYAML(t *testing.T, cacheYAML string) (*Config, error) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(cacheYAML), 0600))
|
||||
return Load(path)
|
||||
}
|
||||
|
||||
func TestIdleTTLDefaultsToAWeek(t *testing.T) {
|
||||
require.Equal(t, 168*time.Hour, Default().Cache.IdleTTL)
|
||||
|
||||
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 168*time.Hour, cfg.Cache.IdleTTL, "an unset key keeps the default")
|
||||
}
|
||||
|
||||
func TestIdleTTLParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want time.Duration
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "duration string", yaml: "cache:\n idle_ttl: 72h\n", want: 72 * time.Hour},
|
||||
{name: "zero disables", yaml: "cache:\n idle_ttl: 0\n", want: 0},
|
||||
{name: "quoted zero disables", yaml: "cache:\n idle_ttl: \"0\"\n", want: 0},
|
||||
{name: "quoted duration", yaml: "cache:\n idle_ttl: \"168h\"\n", want: 168 * time.Hour},
|
||||
{name: "negative rejected", yaml: "cache:\n idle_ttl: -1h\n", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg, err := loadCacheYAML(t, tt.yaml)
|
||||
if tt.wantErr {
|
||||
require.ErrorContains(t, err, "cache.idle_ttl")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, cfg.Cache.IdleTTL)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -157,6 +158,63 @@ func (s *Store) ListPackages(ctx context.Context, opts *metadata.ListOptions) ([
|
||||
return packages, nil
|
||||
}
|
||||
|
||||
// filterPackages returns package records (not scan results) matching keep,
|
||||
// ordered by key ascending and capped at limit.
|
||||
func (s *Store) filterPackages(ctx context.Context, limit int, keep func(*metadata.Package) bool, key func(*metadata.Package) time.Time) ([]*metadata.Package, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []*metadata.Package
|
||||
for _, p := range all {
|
||||
if p.Registry != "" && p.Name != "" && keep(p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return key(out[i]).Before(key(out[j])) })
|
||||
if limit <= 0 {
|
||||
limit = metadata.DefaultBatchSize
|
||||
}
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListIdlePackages returns packages last accessed before idleBefore, oldest first.
|
||||
func (s *Store) ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.filterPackages(ctx, limit,
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
|
||||
func(p *metadata.Package) time.Time { return p.LastAccessed })
|
||||
}
|
||||
|
||||
// ListExpiredPackages returns packages whose ExpiresAt is before the given time, oldest first.
|
||||
func (s *Store) ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.filterPackages(ctx, limit,
|
||||
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(expiredBefore) },
|
||||
func(p *metadata.Package) time.Time { return *p.ExpiresAt })
|
||||
}
|
||||
|
||||
// ClearArtifactExpiry removes ExpiresAt from every non-metadata package.
|
||||
func (s *Store) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var cleared int64
|
||||
for _, p := range all {
|
||||
if p.Registry == "" || p.Name == "" || p.ExpiresAt == nil || metadata.IsMetadataEntry(p.Name, p.Version) {
|
||||
continue
|
||||
}
|
||||
p.ExpiresAt = nil
|
||||
if err := s.SavePackage(ctx, p); err != nil {
|
||||
return cleared, err
|
||||
}
|
||||
cleared++
|
||||
}
|
||||
return cleared, nil
|
||||
}
|
||||
|
||||
// DeletePackage deletes package metadata
|
||||
func (s *Store) DeletePackage(ctx context.Context, registry, name, version string) error {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestListIdlePackages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, _ := newStore(t)
|
||||
now := time.Now()
|
||||
for i, p := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
}{{"old-a", 10 * 24 * time.Hour}, {"old-b", 9 * 24 * time.Hour}, {"fresh", time.Hour}} {
|
||||
require.NoError(t, s.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: p.name, Version: "1", LastAccessed: now.Add(-p.age), Size: int64(i),
|
||||
}))
|
||||
}
|
||||
require.NoError(t, s.SaveScanResult(ctx, &metadata.ScanResult{Registry: "npm", PackageName: "old-a", PackageVersion: "1"}))
|
||||
|
||||
got, err := s.ListIdlePackages(ctx, now.Add(-7*24*time.Hour), 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
require.Equal(t, "old-a", got[0].Name, "oldest first, scan results are not packages")
|
||||
|
||||
got, err = s.ListIdlePackages(ctx, now.Add(-7*24*time.Hour), 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
}
|
||||
|
||||
func TestListExpiredPackagesAndClearArtifactExpiry(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, _ := newStore(t)
|
||||
past := time.Now().Add(-time.Hour)
|
||||
for _, v := range []string{"list", "1.0.0"} {
|
||||
require.NoError(t, s.SavePackage(ctx, &metadata.Package{Registry: "npm", Name: "x", Version: v, ExpiresAt: &past}))
|
||||
}
|
||||
|
||||
cleared, err := s.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), cleared)
|
||||
|
||||
got, err := s.ListExpiredPackages(ctx, time.Now(), 10)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
require.Equal(t, "list", got[0].Version)
|
||||
}
|
||||
@@ -490,7 +490,11 @@ func (s *GORMStoreV2) ListPackages(ctx context.Context, opts *metadata.ListOptio
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
|
||||
}
|
||||
|
||||
// Convert to metadata.Package
|
||||
return s.modelsToPackages(models), nil
|
||||
}
|
||||
|
||||
// modelsToPackages converts rows to metadata packages, resolving registry names once.
|
||||
func (s *GORMStoreV2) modelsToPackages(models []PackageModel) []*metadata.Package {
|
||||
packages := make([]*metadata.Package, len(models))
|
||||
// Snapshot id->name mapping under read lock once to avoid repeated locking
|
||||
s.registryCacheMu.RLock()
|
||||
@@ -502,8 +506,48 @@ func (s *GORMStoreV2) ListPackages(ctx context.Context, opts *metadata.ListOptio
|
||||
for i, model := range models {
|
||||
packages[i] = s.modelToPackage(&model, idToName[model.RegistryID])
|
||||
}
|
||||
return packages
|
||||
}
|
||||
|
||||
return packages, nil
|
||||
// listBatch runs a bounded, index-ordered query over live packages.
|
||||
func (s *GORMStoreV2) listBatch(ctx context.Context, where, order string, arg time.Time, limit int) ([]*metadata.Package, error) {
|
||||
if limit <= 0 {
|
||||
limit = metadata.DefaultBatchSize
|
||||
}
|
||||
var models []PackageModel
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where(where, arg).
|
||||
Order(order).
|
||||
Limit(limit).
|
||||
Find(&models).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
|
||||
}
|
||||
return s.modelsToPackages(models), nil
|
||||
}
|
||||
|
||||
// ListIdlePackages returns live packages last accessed before idleBefore, oldest first.
|
||||
func (s *GORMStoreV2) ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.listBatch(ctx, "last_accessed < ?", "last_accessed ASC", idleBefore, limit)
|
||||
}
|
||||
|
||||
// ListExpiredPackages returns live packages whose expires_at is before the given time, oldest first.
|
||||
func (s *GORMStoreV2) ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*metadata.Package, error) {
|
||||
return s.listBatch(ctx, "expires_at < ?", "expires_at ASC", expiredBefore, limit)
|
||||
}
|
||||
|
||||
// ClearArtifactExpiry nulls expires_at on every row that is not a metadata entry.
|
||||
func (s *GORMStoreV2) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
query := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Where("expires_at IS NOT NULL").
|
||||
Where("version NOT IN ?", metadata.MetadataVersions)
|
||||
for _, suffix := range metadata.MetadataNameSuffixes {
|
||||
query = query.Where("name NOT LIKE ?", "%"+suffix)
|
||||
}
|
||||
result := query.UpdateColumn("expires_at", nil)
|
||||
if result.Error != nil {
|
||||
return 0, errors.Wrap(result.Error, errors.ErrCodeStorageFailure, "failed to clear artifact expiry")
|
||||
}
|
||||
return result.RowsAffected, nil
|
||||
}
|
||||
|
||||
// UpdateDownloadCount increments download count and records event
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresIdleEviction(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.db.Exec(
|
||||
"TRUNCATE packages, download_events, download_stats_hourly, download_stats_daily RESTART IDENTITY CASCADE").Error)
|
||||
}
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"list idle": checkListIdlePackages,
|
||||
"list expired": checkListExpiredPackages,
|
||||
"clear artifact expiry": checkClearArtifactExpiry,
|
||||
"delete keeps history": checkDeleteKeepsDownloadHistory,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
reset(t)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresHistoryTablesHaveNoPackageForeignKey(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
var referencing []string
|
||||
require.NoError(t, store.db.Raw(
|
||||
"SELECT conrelid::regclass::text FROM pg_constraint WHERE contype = 'f' AND confrelid = 'packages'::regclass",
|
||||
).Scan(&referencing).Error)
|
||||
for _, table := range []string{"download_events", "download_stats_hourly", "download_stats_daily"} {
|
||||
require.NotContains(t, referencing, table, "%s must not reference packages: a package delete would restrict or cascade over history", table)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func savePkg(t *testing.T, store *GORMStoreV2, name, version string, lastAccessed time.Time, expiresAt *time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version,
|
||||
StorageKey: fmt.Sprintf("npm/%s/%s", name, version),
|
||||
Size: 100, CachedAt: lastAccessed, LastAccessed: lastAccessed, ExpiresAt: expiresAt,
|
||||
}))
|
||||
}
|
||||
|
||||
func names(pkgs []*metadata.Package) []string {
|
||||
out := make([]string, len(pkgs))
|
||||
for i, p := range pkgs {
|
||||
out[i] = p.Name
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func checkListIdlePackages(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
savePkg(t, store, "idle-oldest", "1.0.0", now.Add(-10*24*time.Hour), nil)
|
||||
savePkg(t, store, "idle-middle", "1.0.0", now.Add(-9*24*time.Hour), nil)
|
||||
savePkg(t, store, "idle-newest", "1.0.0", now.Add(-8*24*time.Hour), nil)
|
||||
savePkg(t, store, "recent", "1.0.0", now.Add(-24*time.Hour), nil)
|
||||
savePkg(t, store, "touched", "1.0.0", now.Add(-12*24*time.Hour), nil)
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "touched", "1.0.0"))
|
||||
|
||||
cutoff := now.Add(-7 * 24 * time.Hour)
|
||||
|
||||
batch, err := store.ListIdlePackages(ctx, cutoff, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"idle-oldest", "idle-middle"}, names(batch), "oldest first, capped at the limit")
|
||||
require.Equal(t, "npm", batch[0].Registry)
|
||||
require.Equal(t, "npm/idle-oldest/1.0.0", batch[0].StorageKey)
|
||||
require.Equal(t, int64(100), batch[0].Size)
|
||||
|
||||
for _, p := range batch {
|
||||
require.NoError(t, store.DeletePackage(ctx, p.Registry, p.Name, p.Version))
|
||||
}
|
||||
batch, err = store.ListIdlePackages(ctx, cutoff, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"idle-newest"}, names(batch), "deleted rows leave the result; a touched row is not idle")
|
||||
|
||||
batch, err = store.ListIdlePackages(ctx, cutoff, 0)
|
||||
require.NoError(t, err, "a non-positive limit falls back to the default batch size")
|
||||
require.Equal(t, []string{"idle-newest"}, names(batch))
|
||||
}
|
||||
|
||||
func checkListExpiredPackages(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
past, future := now.Add(-time.Hour), now.Add(time.Hour)
|
||||
savePkg(t, store, "stale-meta", "list", now, &past)
|
||||
savePkg(t, store, "fresh-meta", "list", now, &future)
|
||||
savePkg(t, store, "no-expiry", "1.0.0", now, nil)
|
||||
|
||||
got, err := store.ListExpiredPackages(ctx, now, 10)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"stale-meta"}, names(got))
|
||||
}
|
||||
|
||||
func checkClearArtifactExpiry(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
exp := now.Add(24 * time.Hour)
|
||||
savePkg(t, store, "lodash", "4.17.21", now, &exp)
|
||||
savePkg(t, store, "left-pad", "1.3.0", now, &exp)
|
||||
savePkg(t, store, "lodash", "list", now, &exp)
|
||||
savePkg(t, store, "lodash", "page", now, &exp)
|
||||
savePkg(t, store, "lodash", "latest", now, &exp)
|
||||
savePkg(t, store, "lodash", "metadata", now, &exp)
|
||||
savePkg(t, store, "golang.org/x/text/@v/v0.3.0.mod", "v0.3.0", now, &exp)
|
||||
savePkg(t, store, "golang.org/x/text/@v/v0.3.0.info", "v0.3.0", now, &exp)
|
||||
|
||||
cleared, err := store.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(2), cleared, "only the two artifacts lose their expiry")
|
||||
|
||||
for _, a := range [][2]string{{"lodash", "4.17.21"}, {"left-pad", "1.3.0"}} {
|
||||
p, getErr := store.GetPackage(ctx, "npm", a[0], a[1])
|
||||
require.NoError(t, getErr)
|
||||
require.Nil(t, p.ExpiresAt, a[0])
|
||||
}
|
||||
for _, m := range [][2]string{
|
||||
{"lodash", "list"}, {"lodash", "page"}, {"lodash", "latest"}, {"lodash", "metadata"},
|
||||
{"golang.org/x/text/@v/v0.3.0.mod", "v0.3.0"}, {"golang.org/x/text/@v/v0.3.0.info", "v0.3.0"},
|
||||
} {
|
||||
p, getErr := store.GetPackage(ctx, "npm", m[0], m[1])
|
||||
require.NoError(t, getErr)
|
||||
require.NotNil(t, p.ExpiresAt, "metadata entry %s@%s keeps its freshness expiry", m[0], m[1])
|
||||
}
|
||||
|
||||
again, err := store.ClearArtifactExpiry(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, again, "idempotent")
|
||||
}
|
||||
|
||||
// A deleted package must not change the download totals: history rows carry
|
||||
// package_id with no foreign key, and the soft delete keeps the package row.
|
||||
func checkDeleteKeepsDownloadHistory(t *testing.T, store *GORMStoreV2) {
|
||||
ctx := context.Background()
|
||||
recordDownloads(t, store, 3)
|
||||
// Two of the three downloads sit in a completed hour, ready to aggregate.
|
||||
require.NoError(t, store.db.Exec(
|
||||
"UPDATE download_events SET downloaded_at = ? WHERE id IN (SELECT id FROM (SELECT id FROM download_events ORDER BY id LIMIT 2) AS first_two)",
|
||||
time.Now().UTC().Add(-3*time.Hour)).Error)
|
||||
|
||||
total := func(label string) {
|
||||
t.Helper()
|
||||
for _, period := range []string{"1day", "7day", "30day"} {
|
||||
ts, err := store.GetTimeSeriesStats(ctx, period, "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(3), sumPoints(ts), "%s (%s)", label, period)
|
||||
}
|
||||
}
|
||||
total("before delete")
|
||||
|
||||
require.NoError(t, store.DeletePackage(ctx, "npm", "left-pad", "1.3.0"))
|
||||
total("after delete")
|
||||
|
||||
// Re-caching the key hard-deletes the stale soft-deleted row.
|
||||
now := time.Now()
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
Size: 10, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
total("after re-cache")
|
||||
|
||||
// Aggregation writes package_id rows for a package that is gone again.
|
||||
require.NoError(t, store.DeletePackage(ctx, "npm", "left-pad", "1.3.0"))
|
||||
require.NoError(t, store.AggregateDownloadData(ctx))
|
||||
total("after delete and aggregation")
|
||||
}
|
||||
|
||||
func TestListIdlePackages(t *testing.T) { checkListIdlePackages(t, newTimeSeriesStore(t)) }
|
||||
func TestListExpiredPackages(t *testing.T) { checkListExpiredPackages(t, newTimeSeriesStore(t)) }
|
||||
func TestClearArtifactExpiry(t *testing.T) { checkClearArtifactExpiry(t, newTimeSeriesStore(t)) }
|
||||
func TestDeletePackageKeepsDownloadHistory(t *testing.T) {
|
||||
checkDeleteKeepsDownloadHistory(t, newTimeSeriesStore(t))
|
||||
}
|
||||
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListIdlePackages() { checkListIdlePackages(s.T(), s.store) }
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListExpiredPackages() {
|
||||
checkListExpiredPackages(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ClearArtifactExpiry() {
|
||||
checkClearArtifactExpiry(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_DeleteKeepsDownloadHistory() {
|
||||
checkDeleteKeepsDownloadHistory(s.T(), s.store)
|
||||
}
|
||||
@@ -14,6 +14,31 @@ import (
|
||||
// Callers should treat it as a non-fatal capability check.
|
||||
var ErrNotImplemented = errors.New("metadata: operation not implemented by this backend")
|
||||
|
||||
// DefaultBatchSize bounds the rows a list query returns when the caller passes no limit.
|
||||
const DefaultBatchSize = 500
|
||||
|
||||
// MetadataVersions are the cache-key versions of metadata pages (index, list, latest).
|
||||
var MetadataVersions = []string{"list", "page", "latest", "metadata"}
|
||||
|
||||
// MetadataNameSuffixes mark Go module metadata files (.mod, .info).
|
||||
var MetadataNameSuffixes = []string{".mod", ".info"}
|
||||
|
||||
// IsMetadataEntry reports whether a cache entry is a metadata page that must
|
||||
// refresh, as opposed to an immutable artifact.
|
||||
func IsMetadataEntry(name, version string) bool {
|
||||
for _, v := range MetadataVersions {
|
||||
if version == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, suffix := range MetadataNameSuffixes {
|
||||
if strings.HasSuffix(name, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Store is an alias for MetadataStore for convenience
|
||||
type Store = MetadataStore
|
||||
|
||||
@@ -31,9 +56,21 @@ type MetadataStore interface {
|
||||
// ListPackages lists packages with optional filtering
|
||||
ListPackages(ctx context.Context, opts *ListOptions) ([]*Package, error)
|
||||
|
||||
// UpdateDownloadCount increments download counter
|
||||
// UpdateDownloadCount increments download counter and stamps last_accessed
|
||||
UpdateDownloadCount(ctx context.Context, registry, name, version string) error
|
||||
|
||||
// ListIdlePackages returns up to limit packages last accessed before
|
||||
// idleBefore, oldest first. A limit <= 0 means DefaultBatchSize.
|
||||
ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*Package, error)
|
||||
|
||||
// ListExpiredPackages returns up to limit packages whose ExpiresAt is before
|
||||
// the given time, oldest first. A limit <= 0 means DefaultBatchSize.
|
||||
ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*Package, error)
|
||||
|
||||
// ClearArtifactExpiry removes ExpiresAt from every non-metadata entry and
|
||||
// returns the number of rows changed. It is idempotent.
|
||||
ClearArtifactExpiry(ctx context.Context) (int64, error)
|
||||
|
||||
// GetStats returns statistics
|
||||
GetStats(ctx context.Context, registry string) (*Stats, error)
|
||||
|
||||
|
||||
@@ -118,6 +118,13 @@ func (m *stubMetadataStore) GetTimeSeriesStats(context.Context, string, string)
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) AggregateDownloadData(context.Context) error { return nil }
|
||||
func (m *stubMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
func (m *stubMetadataStore) SaveAPIKey(context.Context, *metadata.APIKey) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user