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 .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ jobs:
env:
GOOS: wasip1
GOARCH: wasm
run: go build ./internal/metadata/... ./internal/config ./internal/denylist ./internal/packageurl ./internal/storage ./internal/database ./internal/handler ./internal/mirror
run: go build ./internal/metadata/... ./internal/config ./internal/denylist ./internal/packageurl ./internal/storage ./internal/database ./internal/handler ./internal/mirror ./internal/maintenance

helm:
name: Helm chart
Expand Down
9 changes: 9 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -364,13 +364,22 @@ Local bare clones of upstream Git repositories, outside the artifact cache and t
HTTP server setup, web UI, and API handlers.

- Creates and wires together all components
- Schedules the background work in `internal/maintenance`
- Mounts protocol handlers at ecosystem-specific paths
- Middleware: request ID, real IP, logging, panic recovery, active request tracking
- Web UI under `/ui`: dashboard, package browser, source browser, version comparison
- Templates are embedded in the binary via `//go:embed`
- Enrichment API for package metadata, vulnerability scanning, and outdated detection
- Health, stats, and Prometheus metrics endpoints. `/health` runs an active write → size-check → read → verify → delete probe against the storage backend and returns a structured JSON response (`HealthResponse`) with `"ok"` / `"error"` status per subsystem. Probe results are cached (default 30 s, configurable via `health.storage_probe_interval`) to avoid overwhelming remote backends. The response also carries a `circuit_breakers` map reporting each upstream's artifact-fetch breaker as `"open"` or `"closed"`, keyed by the host fetched from (or an opaque placeholder where the fetch URL has no host to read); the same state is published as the `proxy_circuit_breaker_state` gauge on each `/metrics` scrape. An open breaker leaves the overall status `"ok"` — it describes an upstream, not this proxy.

### `internal/maintenance`

The background work: the retention sweep, eviction against `max_size`, reclaiming storage, the metadata backfill, and pruning image records, projects, APK snapshots and the Gradle build cache.

- Each function does one bounded pass and returns. It is handed the time it works at and the limits of the pass (batch sizes, a cap on clears, a time budget)
- It starts no goroutine and no timer and takes no lock. `internal/server` runs the passes on tickers and takes the lock that keeps a pass to one of the instances sharing a database
- Builds for `wasip1`, so another runtime can invoke the same passes in small batches on its own schedule (#501)

### `internal/memlimit`

Sets Go's soft memory limit to 80% of the cgroup memory limit at startup on Linux, unless `GOMEMLIMIT` is set. See "Memory limit" in the configuration docs.
Expand Down
11 changes: 11 additions & 0 deletions internal/maintenance/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Package maintenance holds the proxy's background work: the retention
// sweep, eviction against the size limit, reclaiming storage, and pruning
// records nothing needs any more.
//
// Each function does one bounded pass and returns. It is handed the time it
// works at and the limits of the pass, and it starts no goroutine and no
// timer and takes no lock. When a pass runs, how often, and on which of the
// instances sharing a database is the caller's business: internal/server
// runs them on tickers, and another runtime can invoke them in small batches
// on its own schedule (#501).
package maintenance
4 changes: 4 additions & 0 deletions internal/maintenance/drivers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package maintenance

// The tests open a SQLite database.
import _ "github.com/git-pkgs/proxy/internal/database/drivers"
156 changes: 156 additions & 0 deletions internal/maintenance/eviction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package maintenance

import (
"context"
"log/slog"

"github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/metrics"
"github.com/git-pkgs/proxy/internal/storage"
)

// DefaultEvictionBatch is how many of the least recently used entries the
// server reads at a time.
const DefaultEvictionBatch = 50

// EvictLRU removes the least recently used cached artifacts and metadata
// documents until what max_size counts falls to maxSize, reading them batch
// entries at a time.
func EvictLRU(ctx context.Context, db *database.DB, store storage.Storage, logger *slog.Logger, maxSize int64, batch int) {
totalSize, err := db.GetEvictableCacheSize()
if err != nil {
logger.Warn("eviction: failed to get cache size", "error", err)
return
}

if totalSize <= maxSize {
return
}

logger.Info("eviction: cache size exceeds limit, evicting",
"current_size", totalSize, "max_size", maxSize)

evicted := 0
freedBytes := int64(0)

for totalSize-freedBytes > maxSize {
if ctx.Err() != nil {
break
}

entries, err := db.GetLeastRecentlyUsedCacheEntries(batch)
if err != nil {
logger.Warn("eviction: failed to get LRU entries", "error", err)
break
}
if len(entries) == 0 {
break
}

cleared, freed := evictBatch(ctx, db, store, logger, entries, maxSize, totalSize-freedBytes)
evicted += cleared
freedBytes += freed

if ctx.Err() != nil {
break
}

// A batch that clears nothing returns the same records next time, so
// stop rather than retry them without end. The next pass retries.
if cleared == 0 {
logger.Warn("eviction: no entry in this batch could be evicted, ending the pass",
"batch", len(entries))
break
}
}

if evicted > 0 {
logger.Info("eviction: completed",
"evicted", evicted, "freed_bytes", freedBytes)
}
}

// evictBatch evicts from entries until the size still in use falls to
// maxSize, reporting how many records it cleared and how many bytes that
// freed. Progress is reported in records as well as bytes because a cached
// record can have no size recorded, and clearing one is still progress.
func evictBatch(ctx context.Context, db *database.DB, store storage.Storage, logger *slog.Logger,
entries []database.CacheEntry, maxSize, inUse int64) (int, int64) {
cleared := 0
freed := int64(0)

for _, entry := range entries {
if inUse-freed <= maxSize {
break
}
if ctx.Err() != nil {
break
}
if !entry.StoragePath.Valid {
continue
}

path := entry.StoragePath.String

// Clear before deleting: a record a newer fetch moved has left this
// path queued, and a request may still open it within the grace period.
// The clear queues the path too, so it is never left unrecorded.
recordCleared, err := clearEntry(db, logger, entry)
if err != nil {
logger.Warn("eviction: failed to clear record",
"kind", entry.Kind, "key", entry.Key, "name", entry.Name, "error", err)
continue
}
if !recordCleared {
continue
}
if path == "" {
// Bodiless metadata, such as a HEAD tag resolution, has no
// storage object to delete.
cleared++
continue
}

// Metadata goes now too: readers hold the whole document in memory,
// and a row refetched meanwhile refetches again on a missing blob.
if err := store.Delete(ctx, path); err != nil {
logger.Warn("eviction: failed to delete from storage, leaving it queued", "path", path, "error", err)
} else if err := db.RemovePendingDelete(path); err != nil {
logger.Warn("eviction: failed to dequeue deleted object", "path", path, "error", err)
}

if entry.Size.Valid {
freed += entry.Size.Int64
}
cleared++
}

return cleared, freed
}

// clearEntry drops the record of entry if it still points at the path read
// for it, and counts the eviction.
func clearEntry(db *database.DB, logger *slog.Logger, entry database.CacheEntry) (bool, error) {
if entry.Kind == database.CacheEntryMetadata {
cleared, err := db.EvictMetadataCache(entry.Key, entry.Name, entry.StoragePath.String, entry.LastAccessedAt)
if cleared {
metrics.RecordMetadataEvicted(entry.Key)
}
return cleared, err
}
cleared, err := db.ClearArtifactCache(entry.Key, entry.Name, entry.StoragePath.String)
if cleared {
recordLRUEviction(db, logger, entry.Key)
}
return cleared, err
}

// recordLRUEviction counts an artifact the size limit evicted under the
// ecosystem of its package record.
func recordLRUEviction(db *database.DB, logger *slog.Logger, versionPURL string) {
ecosystem, err := db.GetArtifactEcosystem(versionPURL)
if err != nil {
logger.Debug("eviction: failed to look up ecosystem for metrics", "version_purl", versionPURL, "error", err)
}
metrics.RecordArtifactEvicted("lru", ecosystem)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package server
package maintenance

import (
"context"
Expand Down Expand Up @@ -52,7 +52,7 @@ func TestEvictLRU_CountsAndEvictsMetadata(t *testing.T) {
// Artifacts alone are within the limit; with metadata the cache is
// 1500 bytes, so the least recently used entry has to go, and that is
// the old metadata document.
evictLRU(ctx, db, store, logger, 1100)
EvictLRU(ctx, db, store, logger, 1100, DefaultEvictionBatch)

if entry, _ := db.GetMetadataCache("golang", "tile-old"); entry != nil {
t.Error("least recently used metadata row was kept")
Expand Down Expand Up @@ -81,7 +81,7 @@ func TestEvictLRU_EvictsArtifactBeforeNewerMetadata(t *testing.T) {
seedArtifact(t, ctx, db, store, "old-pkg", 500, now.Add(-3*time.Hour))
seedMetadata(t, ctx, db, store, "tile", now)

evictLRU(ctx, db, store, logger, 600)
EvictLRU(ctx, db, store, logger, 600, DefaultEvictionBatch)

art, err := db.GetArtifact("pkg:npm/old-pkg@1.0.0", "old-pkg-1.0.0.tgz")
if err != nil || art == nil || art.StoragePath.Valid {
Expand All @@ -101,7 +101,7 @@ func TestEvictBatch_KeepsMetadataUsedSinceRead(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
path := seedMetadata(t, ctx, db, store, "tile", time.Now().Add(-time.Hour))

stale, err := db.GetLeastRecentlyUsedCacheEntries(evictionBatch)
stale, err := db.GetLeastRecentlyUsedCacheEntries(DefaultEvictionBatch)
if err != nil || len(stale) != 1 {
t.Fatalf("reading LRU rows: %v, %v", stale, err)
}
Expand Down Expand Up @@ -129,7 +129,7 @@ func TestEvictLRU_MetadataLeavesNothingQueued(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
path := seedMetadata(t, ctx, db, store, "tile", time.Now().Add(-time.Hour))

evictLRU(ctx, db, store, logger, 0)
EvictLRU(ctx, db, store, logger, 0, DefaultEvictionBatch)

if ok, _ := store.Exists(ctx, path); ok {
t.Error("metadata blob kept")
Expand All @@ -148,7 +148,7 @@ func TestEvictMetadata_InterruptedBeforeDeleteIsReclaimed(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
path := seedMetadata(t, ctx, db, store, "tile", time.Now().Add(-time.Hour))

entries, err := db.GetLeastRecentlyUsedCacheEntries(evictionBatch)
entries, err := db.GetLeastRecentlyUsedCacheEntries(DefaultEvictionBatch)
if err != nil || len(entries) != 1 {
t.Fatalf("reading LRU rows: %v, %v", entries, err)
}
Expand All @@ -161,10 +161,10 @@ func TestEvictMetadata_InterruptedBeforeDeleteIsReclaimed(t *testing.T) {
}

// Nothing left for a restarted eviction pass to retry; reclaim takes it.
if again, _ := db.GetLeastRecentlyUsedCacheEntries(evictionBatch); len(again) != 0 {
if again, _ := db.GetLeastRecentlyUsedCacheEntries(DefaultEvictionBatch); len(again) != 0 {
t.Errorf("LRU after interruption = %+v, want nothing", again)
}
reclaimDue(ctx, db, store, logger, time.Now().Add(time.Hour), time.Minute)
Reclaim(ctx, db, store, logger, time.Now().Add(time.Hour), ReclaimLimits{Batch: reclaimBatch, Budget: time.Minute}, time.Now)
if objectExists(t, store, path) {
t.Error("blob still stored after reclaim")
}
Expand All @@ -175,14 +175,19 @@ func TestEvictMetadata_InterruptedBeforeDeleteIsReclaimed(t *testing.T) {

func TestBackfillMetadataAccessDrainsInBatches(t *testing.T) {
db, _ := setupEvictionTest(t)
for _, name := range []string{"a", "b", "c", "d", "e"} {
names := []string{"a", "b", "c", "d", "e"}
inserted := len(names)
for _, name := range names {
query := db.Rebind(`INSERT INTO metadata_cache (ecosystem, name, storage_path, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`)
if _, err := db.Exec(query, "npm", name, "_metadata/npm/"+name+"/metadata", 1, time.Now(), time.Now()); err != nil {
t.Fatalf("inserting: %v", err)
}
}

backfillMetadataAccess(context.Background(), db, slog.New(slog.NewTextHandler(io.Discard, nil)), 2)
rows, err := BackfillMetadataAccess(context.Background(), db, 2)
if err != nil || rows != inserted {
t.Fatalf("BackfillMetadataAccess = %d, %v; want 5 rows", rows, err)
}

var left int
if err := db.Get(&left, `SELECT COUNT(*) FROM metadata_cache WHERE last_accessed_at IS NULL`); err != nil {
Expand Down
Loading
Loading