mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
feat(cache): purge soft-deleted package rows after a retention period
The cleanup worker now hard-deletes package rows whose deleted_at is older than cache.deleted_retention. The default is 30 days. A value of 0 keeps the rows. The purge runs in bounded batches, with at most 100 batches per cleanup pass, and removes child rows with the package. History tables have no foreign key to packages, and stats_snapshots holds its own counts, so the purge leaves both untouched. The cleanup log line now reports purged_deleted and deleted_retention.
This commit is contained in:
Vendored
+30
@@ -85,6 +85,7 @@ type Config struct {
|
||||
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)
|
||||
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
|
||||
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)
|
||||
@@ -97,6 +98,9 @@ const defaultScanWaitTimeout = 30 * time.Second
|
||||
// cleanupBatchSize bounds how many rows one cleanup query reads.
|
||||
const cleanupBatchSize = metadata.DefaultBatchSize
|
||||
|
||||
// maxPurgeBatches bounds the soft-delete purge of one cleanup pass; the next pass continues.
|
||||
const maxPurgeBatches = 100
|
||||
|
||||
// getAttempts bounds how often Get re-resolves an entry whose blob vanished.
|
||||
const getAttempts = 2
|
||||
|
||||
@@ -917,14 +921,40 @@ func (m *Manager) cleanup(ctx context.Context) {
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
|
||||
}
|
||||
|
||||
purged := m.purgeDeleted(ctx, start)
|
||||
|
||||
log.Info().
|
||||
Int("expired", expired.count).
|
||||
Int("idle", idle.count).
|
||||
Int64("bytes_freed", expired.bytes+idle.bytes).
|
||||
Dur("idle_ttl", m.config.IdleTTL).
|
||||
Int64("purged_deleted", purged).
|
||||
Dur("deleted_retention", m.config.DeletedRetention).
|
||||
Msg("Cleanup completed")
|
||||
}
|
||||
|
||||
// purgeDeleted hard-deletes soft-deleted rows past DeletedRetention in bounded
|
||||
// batches and returns how many it removed.
|
||||
func (m *Manager) purgeDeleted(ctx context.Context, now time.Time) int64 {
|
||||
if m.config.DeletedRetention <= 0 {
|
||||
return 0
|
||||
}
|
||||
cutoff := now.Add(-m.config.DeletedRetention)
|
||||
var total int64
|
||||
for i := 0; i < maxPurgeBatches && ctx.Err() == nil; i++ {
|
||||
n, err := m.metadata.PurgeDeletedPackages(ctx, cutoff, cleanupBatchSize)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to purge soft-deleted packages")
|
||||
break
|
||||
}
|
||||
total += n
|
||||
if n < cleanupBatchSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// generateStorageKey generates a storage key for a package
|
||||
func (m *Manager) generateStorageKey(registry, name, version string) string {
|
||||
return fmt.Sprintf("%s/%s/%s", registry, name, version)
|
||||
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// purgeRecorder plays a store holding `pending` soft-deleted rows.
|
||||
type purgeRecorder struct {
|
||||
*memMetadata
|
||||
err error
|
||||
cutoffs []time.Time
|
||||
limits []int
|
||||
pending int64
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (p *purgeRecorder) PurgeDeletedPackages(_ context.Context, before time.Time, limit int) (int64, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.cutoffs = append(p.cutoffs, before)
|
||||
p.limits = append(p.limits, limit)
|
||||
if p.err != nil {
|
||||
return 0, p.err
|
||||
}
|
||||
n := min(p.pending, int64(limit))
|
||||
p.pending -= n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newPurgeHarness(t *testing.T, retention time.Duration, pending int64) (*idleHarness, *purgeRecorder) {
|
||||
t.Helper()
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
rec := &purgeRecorder{memMetadata: newMemMetadata(h.clock), pending: pending}
|
||||
h.meta = rec.memMetadata
|
||||
mgr, err := New(h.store, rec, nil, nil, Config{Now: h.clock.Now, CleanupInterval: 24 * time.Hour, DeletedRetention: retention})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
h.mgr = mgr
|
||||
return h, rec
|
||||
}
|
||||
|
||||
func TestCleanupPurgesDeletedRowsPastRetention(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 3*int64(cleanupBatchSize)+7)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Zero(t, rec.pending, "batches continue until the store runs dry")
|
||||
require.Len(t, rec.limits, 4, "three full batches and a short one")
|
||||
for _, limit := range rec.limits {
|
||||
require.Equal(t, cleanupBatchSize, limit, "every batch is bounded")
|
||||
}
|
||||
require.Equal(t, h.clock.Now().Add(-30*day), rec.cutoffs[0], "the cutoff is now minus the retention")
|
||||
}
|
||||
|
||||
func TestCleanupPurgeIsBoundedPerPass(t *testing.T) {
|
||||
_, rec := newPurgeHarness(t, 30*day, int64(maxPurgeBatches+50)*int64(cleanupBatchSize))
|
||||
h := &Manager{config: Config{DeletedRetention: day, Now: time.Now}, metadata: rec}
|
||||
|
||||
got := h.purgeDeleted(context.Background(), time.Now())
|
||||
|
||||
require.EqualValues(t, maxPurgeBatches*cleanupBatchSize, got)
|
||||
require.EqualValues(t, 50*cleanupBatchSize, rec.pending, "the next pass continues where this one stopped")
|
||||
}
|
||||
|
||||
func TestCleanupSkipsPurgeWhenRetentionIsZero(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 0, 10)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Empty(t, rec.limits, "zero keeps every row")
|
||||
require.EqualValues(t, 10, rec.pending)
|
||||
}
|
||||
|
||||
func TestCleanupPurgeFailureDoesNotStopCleanup(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 10)
|
||||
rec.err = errors.New("db down")
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.clock.Advance(2 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Len(t, rec.limits, 1, "one failed attempt, no retry loop")
|
||||
require.False(t, h.exists("lodash", "metadata"), "expired metadata is still removed")
|
||||
}
|
||||
Reference in New Issue
Block a user