feat(stats): record daily snapshots and serve a trend API

The aggregation worker now writes one row per UTC day to
stats_snapshots. The row holds package count, total size, vulnerable
package count, the four severity counts and the blocked count. The
write is an idempotent upsert per day.

A migration backfills package counts from cached_at and deleted_at as
the number of packages alive at the end of each day. Vulnerability
fields backfill from scan_results timestamps and stay empty before the
first scan. GET /api/stats/trend returns daily points for 30day, 90day
or 1year with a constant number of queries.

The Stats page shows a chart of cached and vulnerable packages with a
period selector and severity toggles. The Dashboard shows a compact
version. The Lean model gains theorems for the backfill and upsert.
This commit is contained in:
2026-11-23 14:55:19 +00:00
parent bd9d686383
commit 1512230ab3
26 changed files with 1660 additions and 51 deletions
+10
View File
@@ -195,6 +195,16 @@ func (s *Store) ListExpiredPackages(ctx context.Context, expiredBefore time.Time
func(p *metadata.Package) time.Time { return *p.ExpiresAt })
}
// PurgeDeletedPackages is a no-op: the file store deletes packages outright.
func (s *Store) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
return 0, nil
}
// GetStatsTrend returns no history: the file store keeps no daily snapshots.
func (s *Store) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
return nil, nil
}
// ClearArtifactExpiry removes ExpiresAt from every non-metadata package.
func (s *Store) ClearArtifactExpiry(ctx context.Context) (int64, error) {
all, err := s.ListPackages(ctx, nil)
+13 -1
View File
@@ -1,6 +1,7 @@
package gormstore
import (
"context"
"sync"
"time"
@@ -18,8 +19,10 @@ type AggregationWorker struct {
stopChan chan struct{}
ticker *time.Ticker
now func() time.Time // nil means time.Now
blocked func(context.Context) (int64, error)
wg sync.WaitGroup
stopOnce sync.Once
mu sync.Mutex // guards blocked
}
// NewAggregationWorker creates a new aggregation worker
@@ -289,7 +292,7 @@ func (w *AggregationWorker) AggregateDaily() error {
dayEnd := w.clock().UTC().Truncate(24 * time.Hour)
firstDay := dayEnd.Add(-rollupDays * 24 * time.Hour)
return w.db.Transaction(func(tx *gorm.DB) error {
err := w.db.Transaction(func(tx *gorm.DB) error {
var aggregateSQL string
switch dialectName {
@@ -384,6 +387,15 @@ func (w *AggregationWorker) AggregateDaily() error {
return nil
})
if err != nil {
return err
}
// The snapshot is not part of the rollup: a failure here must not undo it.
if err := w.SnapshotStats(context.Background()); err != nil {
log.Error().Err(err).Msg("Failed to record stats snapshot")
}
return nil
}
// UpdatePackageAccessCounts synchronizes package access_count from download stats
+7
View File
@@ -125,6 +125,13 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
}
}
// History must exist before the worker writes today's snapshot.
if days, err := BackfillStatsSnapshots(context.Background(), db, time.Now()); err != nil {
log.Warn().Err(err).Msg("Failed to backfill stats snapshots")
} else if days > 0 {
log.Info().Int("days", days).Msg("Backfilled stats snapshots")
}
// Start aggregation worker (skip for in-memory databases used in tests)
if !strings.Contains(cfg.DSN, ":memory:") {
store.aggregationWorker = NewAggregationWorker(db)
+16
View File
@@ -1,6 +1,7 @@
package gormstore
import (
"context"
"fmt"
"time"
@@ -98,6 +99,20 @@ func GetMigrations() []*gormigrate.Migration {
return tx.Migrator().DropIndex(&ScanResultModel{}, scanPackageScannedAtIndex)
},
},
{
// Daily stats snapshots for the trend chart, seeded from package and scan history.
ID: "202611250001",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&StatsSnapshotModel{}); err != nil {
return err
}
_, err := BackfillStatsSnapshots(context.Background(), tx, time.Now())
return err
},
Rollback: func(tx *gorm.DB) error {
return tx.Migrator().DropTable(&StatsSnapshotModel{})
},
},
}
}
@@ -292,6 +307,7 @@ func createMySQLOptimizations(tx *gorm.DB) error {
func rollbackFromV2(tx *gorm.DB) error {
// Drop in reverse order to respect foreign keys
tables := []string{
"stats_snapshots",
"api_keys",
"audit_log",
"download_stats_daily",
+22
View File
@@ -351,6 +351,27 @@ func (a *PostgresArray) Scan(value interface{}) error {
return json.Unmarshal(bytes, a)
}
// StatsSnapshotModel is the cache state at the end of one UTC day. It has no
// foreign key to packages, so purging package rows never touches history. A nil
// count is unknown, not zero.
type StatsSnapshotModel struct {
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
VulnerablePackages *int64
Critical *int64 // packages whose highest severity is critical
High *int64
Moderate *int64
Low *int64
Blocked *int64
Day string `gorm:"primaryKey;size:10"` // YYYY-MM-DD, UTC
TotalPackages int64 `gorm:"not null;default:0"`
TotalSize int64 `gorm:"not null;default:0"`
}
func (StatsSnapshotModel) TableName() string {
return "stats_snapshots"
}
// GetAllModels returns all models for GORM auto-migration
func GetAllModels() []interface{} {
return []interface{}{
@@ -366,5 +387,6 @@ func GetAllModels() []interface{} {
&DownloadStatsDailyModel{},
&AuditLogModel{},
&APIKeyModel{},
&StatsSnapshotModel{},
}
}
+382
View File
@@ -0,0 +1,382 @@
package gormstore
import (
"context"
"sort"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const (
day = 24 * time.Hour
snapshotBatch = 500
)
// artifactPackages limits a query on packages to cache artifacts: no metadata
// pages and no Go .mod/.info files, as GetStats counts them.
func artifactPackages(db *gorm.DB) *gorm.DB {
return db.Where("version NOT IN ?", metadata.MetadataVersions).
Where("name NOT LIKE ?", "%.mod").Where("name NOT LIKE ?", "%.info")
}
func dayString(t time.Time) string { return t.UTC().Format(metadata.StatsSnapshotDateLayout) }
func ptr(v int64) *int64 { return &v }
// liveSnapshot reads the current cache state in one statement. blocked may be nil.
func liveSnapshot(ctx context.Context, db *gorm.DB, at time.Time, blocked *int64) (*StatsSnapshotModel, error) {
var r struct {
Total int64
Size int64
Vulnerable int64
Critical int64
High int64
Moderate int64
Low int64
}
err := artifactPackages(db.WithContext(ctx).Model(&PackageModel{})).Select(`
COUNT(*) AS total,
COALESCE(SUM(size), 0) AS size,
COALESCE(SUM(CASE WHEN vulnerability_count > 0 THEN 1 ELSE 0 END), 0) AS vulnerable,
COALESCE(SUM(CASE WHEN highest_severity = 'critical' THEN 1 ELSE 0 END), 0) AS critical,
COALESCE(SUM(CASE WHEN highest_severity = 'high' THEN 1 ELSE 0 END), 0) AS high,
COALESCE(SUM(CASE WHEN highest_severity = 'medium' THEN 1 ELSE 0 END), 0) AS moderate,
COALESCE(SUM(CASE WHEN highest_severity = 'low' THEN 1 ELSE 0 END), 0) AS low`).
Scan(&r).Error
if err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats for snapshot")
}
return &StatsSnapshotModel{
Day: dayString(at),
TotalPackages: r.Total,
TotalSize: r.Size,
VulnerablePackages: ptr(r.Vulnerable),
Critical: ptr(r.Critical),
High: ptr(r.High),
Moderate: ptr(r.Moderate),
Low: ptr(r.Low),
Blocked: blocked,
}, nil
}
// snapshotColumns are overwritten when a day's snapshot is written again.
var snapshotColumns = []string{
"total_packages", "total_size", "vulnerable_packages", "critical", "high", "moderate", "low", "blocked", "updated_at",
}
// upsertSnapshot writes the day's row, replacing an earlier write of the same day.
// A nil blocked keeps the stored value so a run without a blocking policy never erases it.
func upsertSnapshot(ctx context.Context, db *gorm.DB, snap *StatsSnapshotModel) error {
cols := snapshotColumns
if snap.Blocked == nil {
cols = make([]string, 0, len(snapshotColumns))
for _, c := range snapshotColumns {
if c != "blocked" {
cols = append(cols, c)
}
}
}
err := db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "day"}},
DoUpdates: clause.AssignmentColumns(cols),
}).Create(snap).Error
if err != nil {
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to save stats snapshot")
}
return nil
}
// SnapshotStats records today's (UTC) cache state. Running it again the same
// day overwrites that day's row, so the last run of a day is its closing state.
func (w *AggregationWorker) SnapshotStats(ctx context.Context) error {
now := w.clock()
var blocked *int64
if count := w.blockedCounter(); count != nil {
n, err := count(ctx)
if err != nil {
log.Warn().Err(err).Msg("Failed to count blocked packages for the stats snapshot")
} else {
blocked = ptr(n)
}
}
snap, err := liveSnapshot(ctx, w.db, now, blocked)
if err != nil {
return err
}
if err := upsertSnapshot(ctx, w.db, snap); err != nil {
return err
}
log.Info().Str("day", snap.Day).Int64("packages", snap.TotalPackages).Msg("Recorded stats snapshot")
return nil
}
// SetBlockedCounter sets how the snapshot counts blocked packages, which needs the scan policy the store lacks.
func (w *AggregationWorker) SetBlockedCounter(count func(context.Context) (int64, error)) {
w.mu.Lock()
w.blocked = count
w.mu.Unlock()
}
func (w *AggregationWorker) blockedCounter() func(context.Context) (int64, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.blocked
}
// SetBlockedCounter sets how daily snapshots count blocked packages.
func (s *GORMStoreV2) SetBlockedCounter(count func(context.Context) (int64, error)) {
if s.aggregationWorker != nil {
s.aggregationWorker.SetBlockedCounter(count)
}
}
// GetStatsTrend returns the daily snapshots from the UTC day of since, oldest first, in one statement.
func (s *GORMStoreV2) GetStatsTrend(ctx context.Context, since time.Time) ([]*metadata.StatsSnapshot, error) {
var rows []StatsSnapshotModel
if err := s.db.WithContext(ctx).Where("day >= ?", dayString(since)).Order("day").Find(&rows).Error; err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats snapshots")
}
out := make([]*metadata.StatsSnapshot, len(rows))
for i, r := range rows {
out[i] = &metadata.StatsSnapshot{
Date: r.Day,
TotalPackages: r.TotalPackages,
TotalSize: r.TotalSize,
VulnerablePackages: r.VulnerablePackages,
Critical: r.Critical,
High: r.High,
Moderate: r.Moderate,
Low: r.Low,
Blocked: r.Blocked,
}
}
return out, nil
}
// dayState is one package's contribution to a day's totals.
type dayState struct {
size, vulnerable, critical, high, moderate, low int64
alive int64
}
func (a dayState) minus(b dayState) dayState {
return dayState{
alive: a.alive - b.alive, size: a.size - b.size, vulnerable: a.vulnerable - b.vulnerable,
critical: a.critical - b.critical, high: a.high - b.high, moderate: a.moderate - b.moderate, low: a.low - b.low,
}
}
func (a *dayState) add(b dayState) {
a.alive += b.alive
a.size += b.size
a.vulnerable += b.vulnerable
a.critical += b.critical
a.high += b.high
a.moderate += b.moderate
a.low += b.low
}
// backfillScan is one scan result reduced to what the history needs.
type backfillScan struct {
at time.Time
vulns, critical, high, moderate, lowCounts int
id int64
}
// backfillPackage is one package's lifetime: alive from cachedAt up to deletedAt.
type backfillPackage struct {
cachedAt time.Time
deletedAt *time.Time
size int64
}
// stateAtDayEnd is the package's contribution at the end of the UTC day whose
// midnight-after is end. withScans is false for days before any scan exists.
func (p backfillPackage) stateAtDayEnd(end time.Time, scans []backfillScan, withScans bool) dayState {
if !p.cachedAt.Before(end) || (p.deletedAt != nil && p.deletedAt.Before(end)) {
return dayState{}
}
st := dayState{alive: 1, size: p.size}
if !withScans {
return st
}
// scans is sorted by (at, id); the last one before end is the latest.
i := sort.Search(len(scans), func(i int) bool { return !scans[i].at.Before(end) })
if i == 0 {
return st
}
sc := scans[i-1]
if sc.vulns > 0 {
st.vulnerable = 1
}
switch {
case sc.critical > 0:
st.critical = 1
case sc.high > 0:
st.high = 1
case sc.moderate > 0:
st.moderate = 1
case sc.lowCounts > 0:
st.low = 1
}
return st
}
// BackfillStatsSnapshots writes one snapshot per past UTC day, from the first
// package to the day before today, when no snapshot of a past day exists yet. Package counts
// come from cached_at and deleted_at. Vulnerability counts come from the
// append-only scan results and start at the first scan; earlier days leave
// them nil, as blocked is always nil (the policy at the time is not stored).
// It returns the number of days written.
func BackfillStatsSnapshots(ctx context.Context, db *gorm.DB, now time.Time) (int, error) {
today := now.UTC().Truncate(day)
var existing int64
if err := db.WithContext(ctx).Model(&StatsSnapshotModel{}).Where("day < ?", dayString(today)).Count(&existing).Error; err != nil {
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to count stats snapshots")
}
if existing > 0 {
return 0, nil
}
pkgs, err := loadBackfillPackages(ctx, db)
if err != nil {
return 0, err
}
if len(pkgs) == 0 {
return 0, nil
}
scans, firstScan, err := loadBackfillScans(ctx, db, pkgs)
if err != nil {
return 0, err
}
deltas := map[int64]dayState{}
first := today
for id, p := range pkgs {
if d := p.cachedAt.UTC().Truncate(day); d.Before(first) {
first = d
}
prev := dayState{}
for _, d := range candidateDays(p, scans[id], today) {
cur := p.stateAtDayEnd(d.Add(day), scans[id], !firstScan.IsZero() && !d.Before(firstScan))
if delta := cur.minus(prev); delta != (dayState{}) {
acc := deltas[d.Unix()]
acc.add(delta)
deltas[d.Unix()] = acc
}
prev = cur
}
}
var rows []StatsSnapshotModel
var total dayState
for d := first; d.Before(today); d = d.Add(day) {
total.add(deltas[d.Unix()])
row := StatsSnapshotModel{Day: dayString(d), TotalPackages: total.alive, TotalSize: total.size}
if !firstScan.IsZero() && !d.Before(firstScan) {
row.VulnerablePackages, row.Critical, row.High = ptr(total.vulnerable), ptr(total.critical), ptr(total.high)
row.Moderate, row.Low = ptr(total.moderate), ptr(total.low)
}
rows = append(rows, row)
}
if len(rows) == 0 {
return 0, nil
}
err = db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(rows, snapshotBatch).Error
if err != nil {
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to backfill stats snapshots")
}
return len(rows), nil
}
// candidateDays lists, sorted, the days before today on which a package's
// end-of-day state can change: when it was cached, deleted or scanned.
func candidateDays(p backfillPackage, scans []backfillScan, today time.Time) []time.Time {
set := map[int64]struct{}{}
mark := func(t time.Time) {
if d := t.UTC().Truncate(day); d.Before(today) {
set[d.Unix()] = struct{}{}
}
}
mark(p.cachedAt)
if p.deletedAt != nil {
mark(*p.deletedAt)
}
for _, s := range scans {
mark(s.at)
}
days := make([]time.Time, 0, len(set))
for unix := range set {
days = append(days, time.Unix(unix, 0).UTC())
}
sort.Slice(days, func(i, j int) bool { return days[i].Before(days[j]) })
return days
}
func loadBackfillPackages(ctx context.Context, db *gorm.DB) (map[int64]backfillPackage, error) {
var rows []struct {
CachedAt time.Time
DeletedAt *time.Time
ID int64
Size int64
}
err := artifactPackages(db.WithContext(ctx).Unscoped().Model(&PackageModel{})).
Select("id, cached_at, deleted_at, size").Scan(&rows).Error
if err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read packages for backfill")
}
pkgs := make(map[int64]backfillPackage, len(rows))
for _, r := range rows {
pkgs[r.ID] = backfillPackage{cachedAt: r.CachedAt, deletedAt: r.DeletedAt, size: r.Size}
}
return pkgs, nil
}
// loadBackfillScans groups the scan results of the given packages and returns
// the UTC day of the first scan (zero when there is none).
func loadBackfillScans(ctx context.Context, db *gorm.DB, pkgs map[int64]backfillPackage) (map[int64][]backfillScan, time.Time, error) {
var rows []struct {
ScannedAt time.Time
ID int64
PackageID int64
VulnCount int
CriticalCount int
HighCount int
MediumCount int
LowCount int
}
err := db.WithContext(ctx).Model(&ScanResultModel{}).
Select("id, package_id, scanned_at, vuln_count, critical_count, high_count, medium_count, low_count").
Scan(&rows).Error
if err != nil {
return nil, time.Time{}, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read scans for backfill")
}
scans := map[int64][]backfillScan{}
var firstScan time.Time
for _, r := range rows {
if _, ok := pkgs[r.PackageID]; !ok {
continue
}
scans[r.PackageID] = append(scans[r.PackageID], backfillScan{
id: r.ID, at: r.ScannedAt, vulns: r.VulnCount,
critical: r.CriticalCount, high: r.HighCount, moderate: r.MediumCount, lowCounts: r.LowCount,
})
if d := r.ScannedAt.UTC().Truncate(day); firstScan.IsZero() || d.Before(firstScan) {
firstScan = d
}
}
for _, list := range scans {
sort.Slice(list, func(i, j int) bool {
if list[i].at.Equal(list[j].at) {
return list[i].id < list[j].id
}
return list[i].at.Before(list[j].at)
})
}
return scans, firstScan, nil
}
@@ -0,0 +1,43 @@
//go:build pgintegration
package gormstore
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPostgresTrendSeverityAndPurge(t *testing.T) {
store, _ := newPostgresStore(t)
reset := func(t *testing.T) {
t.Helper()
require.NoError(t, store.db.Exec(
"TRUNCATE packages, stats_snapshots, download_stats_daily RESTART IDENTITY CASCADE").Error)
}
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
"backfill": checkBackfillStatsSnapshots,
"backfill without scans": checkBackfillWithoutScans,
"snapshot": checkSnapshotStats,
"trend window": checkTrendWindow,
"trend statements constant": checkTrendStatementsAreConstant,
"severity filter": checkSeverityFilter,
"severity statements constant": checkSeverityFilterStatementsAreConstant,
} {
t.Run(name, func(t *testing.T) {
reset(t)
check(t, store)
})
}
}
func TestPostgresStatsSnapshotsHaveNoPackageForeignKey(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)
require.NotContains(t, referencing, "stats_snapshots", "a package purge must not cascade over history")
}
+256
View File
@@ -0,0 +1,256 @@
package gormstore
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
func today() time.Time { return time.Now().UTC().Truncate(day) }
// daysAgo is noon UTC, n days before today.
func daysAgo(n int) time.Time { return today().AddDate(0, 0, -n).Add(12 * time.Hour) }
func seedAt(t *testing.T, store *GORMStoreV2, name, version string, size int64, cachedAt 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: size, CachedAt: cachedAt, LastAccessed: cachedAt,
}))
}
func scanAt(t *testing.T, store *GORMStoreV2, name, version string, at time.Time, severities ...string) {
t.Helper()
res := &metadata.ScanResult{
Registry: "npm", PackageName: name, PackageVersion: version, Scanner: "test", ScannedAt: at,
Status: metadata.ScanStatusClean,
}
for i, sev := range severities {
res.Status = metadata.ScanStatusVulnerable
res.Vulnerabilities = append(res.Vulnerabilities, metadata.Vulnerability{ID: fmt.Sprintf("CVE-%d", i), Severity: sev})
}
res.VulnerabilityCount = len(severities)
require.NoError(t, store.SaveScanResult(context.Background(), res))
}
// softDeleteAt deletes the package and backdates the deletion.
func softDeleteAt(t *testing.T, store *GORMStoreV2, name, version string, at time.Time) {
t.Helper()
require.NoError(t, store.DeletePackage(context.Background(), "npm", name, version))
require.NoError(t, store.db.Unscoped().Model(&PackageModel{}).
Where("name = ? AND version = ?", name, version).Update("deleted_at", at).Error)
}
func trendByDay(t *testing.T, store *GORMStoreV2, since time.Time) map[string]*metadata.StatsSnapshot {
t.Helper()
pts, err := store.GetStatsTrend(context.Background(), since)
require.NoError(t, err)
out := map[string]*metadata.StatsSnapshot{}
for _, p := range pts {
out[p.Date] = p
}
return out
}
func vulns(p *metadata.StatsSnapshot) [5]int64 {
get := func(v *int64) int64 {
if v == nil {
return -1
}
return *v
}
return [5]int64{get(p.VulnerablePackages), get(p.Critical), get(p.High), get(p.Moderate), get(p.Low)}
}
// checkBackfillStatsSnapshots seeds a five-day history and proves the reconstruction day by day.
func checkBackfillStatsSnapshots(t *testing.T, store *GORMStoreV2) {
t.Helper()
ctx := context.Background()
seedAt(t, store, "a", "1.0.0", 10, daysAgo(5))
seedAt(t, store, "b", "1.0.0", 20, daysAgo(4))
seedAt(t, store, "a", "list", 5, daysAgo(5)) // metadata page: never counted
seedAt(t, store, "mod/@v/v1.mod", "v1", 7, daysAgo(5)) // Go .mod file: never counted
seedAt(t, store, "early", "1.0.0", 40, daysAgo(2)) // cached and deleted the same day
scanAt(t, store, "b", "1.0.0", daysAgo(4), "high") // first scan: vulnerability history starts here
scanAt(t, store, "a", "1.0.0", daysAgo(3), "critical", "low") // critical wins over low
scanAt(t, store, "a", "1.0.0", daysAgo(1)) // clean rescan
softDeleteAt(t, store, "b", "1.0.0", daysAgo(2))
softDeleteAt(t, store, "early", "1.0.0", daysAgo(2).Add(time.Hour))
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
require.NoError(t, err)
require.Equal(t, 5, days, "day -5 to day -1; today belongs to the live snapshot")
got := trendByDay(t, store, daysAgo(10))
require.Len(t, got, 5)
day := func(n int) *metadata.StatsSnapshot {
p, ok := got[dayString(daysAgo(n))]
require.True(t, ok, "day -%d", n)
return p
}
require.EqualValues(t, 1, day(5).TotalPackages)
require.EqualValues(t, 10, day(5).TotalSize)
require.Equal(t, [5]int64{-1, -1, -1, -1, -1}, vulns(day(5)), "no scan existed yet: unknown, not zero")
require.EqualValues(t, 2, day(4).TotalPackages)
require.EqualValues(t, 30, day(4).TotalSize)
require.Equal(t, [5]int64{1, 0, 1, 0, 0}, vulns(day(4)))
require.EqualValues(t, 2, day(3).TotalPackages)
require.Equal(t, [5]int64{2, 1, 1, 0, 0}, vulns(day(3)))
require.EqualValues(t, 1, day(2).TotalPackages, "b was deleted on day -2; early lived and died within it")
require.EqualValues(t, 10, day(2).TotalSize)
require.Equal(t, [5]int64{1, 1, 0, 0, 0}, vulns(day(2)))
require.EqualValues(t, 1, day(1).TotalPackages)
require.Equal(t, [5]int64{0, 0, 0, 0, 0}, vulns(day(1)), "the clean rescan clears the vulnerability")
require.Nil(t, day(1).Blocked, "the policy of a past day is not reconstructable")
again, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
require.NoError(t, err)
require.Zero(t, again, "a second run is a no-op")
require.Len(t, trendByDay(t, store, daysAgo(10)), 5)
}
// checkBackfillWithoutScans proves that without scan history only package counts are written.
func checkBackfillWithoutScans(t *testing.T, store *GORMStoreV2) {
t.Helper()
ctx := context.Background()
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
require.NoError(t, err)
require.Zero(t, days, "no packages, no history")
seedAt(t, store, "a", "1.0.0", 10, daysAgo(2))
days, err = BackfillStatsSnapshots(ctx, store.db, time.Now())
require.NoError(t, err)
require.Equal(t, 2, days)
for _, p := range trendByDay(t, store, daysAgo(10)) {
require.EqualValues(t, 1, p.TotalPackages)
require.Equal(t, [5]int64{-1, -1, -1, -1, -1}, vulns(p))
}
}
func checkSnapshotStats(t *testing.T, store *GORMStoreV2) {
t.Helper()
ctx := context.Background()
seedAt(t, store, "a", "1.0.0", 10, daysAgo(1))
seedAt(t, store, "b", "1.0.0", 20, daysAgo(1))
seedAt(t, store, "c", "1.0.0", 30, daysAgo(1))
scanAt(t, store, "a", "1.0.0", daysAgo(1), "critical")
scanAt(t, store, "b", "1.0.0", daysAgo(1), "moderate")
// An in-memory database has no running worker; this one is the test's own.
worker := store.aggregationWorker
store.SetBlockedCounter(func(context.Context) (int64, error) { return 1, nil })
require.NoError(t, worker.SnapshotStats(ctx))
require.NoError(t, worker.SnapshotStats(ctx), "the same day twice writes one row")
rows := trendByDay(t, store, today())
require.Len(t, rows, 1)
snap := rows[dayString(time.Now())]
require.NotNil(t, snap)
require.EqualValues(t, 3, snap.TotalPackages)
require.EqualValues(t, 60, snap.TotalSize)
require.Equal(t, [5]int64{2, 1, 0, 1, 0}, vulns(snap))
require.EqualValues(t, 1, *snap.Blocked)
// The next run of the day replaces the counts.
scanAt(t, store, "a", "1.0.0", daysAgo(0).Add(-time.Hour), "high")
store.SetBlockedCounter(nil)
require.NoError(t, worker.SnapshotStats(ctx))
snap = trendByDay(t, store, today())[dayString(time.Now())]
require.Equal(t, [5]int64{2, 0, 1, 1, 0}, vulns(snap))
require.EqualValues(t, 1, *snap.Blocked, "a run without a blocking policy keeps the earlier count")
store.SetBlockedCounter(func(context.Context) (int64, error) { return 0, errors.New("scanner down") })
require.NoError(t, worker.SnapshotStats(ctx), "a failed blocked count must not lose the snapshot")
}
func checkTrendWindow(t *testing.T, store *GORMStoreV2) {
t.Helper()
for i := 0; i < 5; i++ {
require.NoError(t, store.db.Create(&StatsSnapshotModel{Day: dayString(daysAgo(i)), TotalPackages: int64(i)}).Error)
}
pts, err := store.GetStatsTrend(context.Background(), daysAgo(2))
require.NoError(t, err)
require.Len(t, pts, 3)
require.Equal(t, dayString(daysAgo(2)), pts[0].Date, "oldest first, from the since day inclusive")
require.Equal(t, dayString(daysAgo(0)), pts[2].Date)
require.Nil(t, pts[0].VulnerablePackages)
none, err := store.GetStatsTrend(context.Background(), today().AddDate(0, 0, 1))
require.NoError(t, err)
require.Empty(t, none)
}
// attachCounter counts the statements of the store and of its worker, which holds its own handle.
func attachCounter(store *GORMStoreV2) *dbcount.Counter {
var counter *dbcount.Counter
store.WrapDB(func(db *gorm.DB) *gorm.DB {
counted, c := dbcount.Attach(db)
counter = c
return counted
})
store.aggregationWorker.db = store.db
return counter
}
func checkTrendStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
t.Helper()
ctx := context.Background()
counter := attachCounter(store)
measure := func() map[string]int {
out := map[string]int{}
counter.Reset()
_, err := store.GetStatsTrend(ctx, daysAgo(365))
require.NoError(t, err)
out["trend"] = counter.Count()
counter.Reset()
require.NoError(t, store.aggregationWorker.SnapshotStats(ctx))
out["snapshot"] = counter.Count()
require.NoError(t, store.db.Exec("DELETE FROM stats_snapshots").Error)
counter.Reset()
_, err = BackfillStatsSnapshots(ctx, store.db, time.Now().AddDate(0, 0, 400))
require.NoError(t, err)
out["backfill"] = counter.Count()
return out
}
seedScanned(t, store, 0, 10)
small := measure()
seedScanned(t, store, 10, 90)
large := measure()
t.Logf("statements for 10 packages %v, for 100 packages %v", small, large)
require.Equal(t, small, large)
require.Equal(t, 1, large["trend"])
require.Equal(t, 2, large["snapshot"], "one aggregate read, one upsert")
require.LessOrEqual(t, large["backfill"], 4, "count, packages, scans, one insert batch")
require.Positive(t, large["backfill"])
}
func TestStatsSnapshotMigration(t *testing.T) {
store := newTimeSeriesStore(t)
seedAt(t, store, "a", "1.0.0", 10, daysAgo(2))
require.NoError(t, store.db.Migrator().DropTable(&StatsSnapshotModel{}))
for _, migration := range GetMigrations() {
if migration.ID != "202611250001" {
continue
}
require.NoError(t, migration.Migrate(store.db))
require.NoError(t, migration.Migrate(store.db), "rerun must be a no-op")
require.Len(t, trendByDay(t, store, daysAgo(10)), 2, "the migration seeds the history")
return
}
t.Fatal("migration 202611250001 is not registered")
}
+21
View File
@@ -86,6 +86,10 @@ type MetadataStore interface {
// the given time, oldest first. A limit <= 0 means DefaultBatchSize.
ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*Package, error)
// GetStatsTrend returns the daily stats snapshots from the UTC day of since
// on, oldest first. Backends without history return none.
GetStatsTrend(ctx context.Context, since time.Time) ([]*StatsSnapshot, 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)
@@ -351,6 +355,23 @@ const (
// Severities lists the severity filter values, most severe first.
var Severities = []string{SeverityCritical, SeverityHigh, SeverityModerate, SeverityLow}
// StatsSnapshot is the cache state at the end of one UTC day. The pointer
// fields are nil for days whose value cannot be reconstructed.
type StatsSnapshot struct {
VulnerablePackages *int64 `json:"vulnerable_packages"`
Critical *int64 `json:"critical"`
High *int64 `json:"high"`
Moderate *int64 `json:"moderate"`
Low *int64 `json:"low"`
Blocked *int64 `json:"blocked"`
Date string `json:"date"` // YYYY-MM-DD, UTC
TotalPackages int64 `json:"total_packages"`
TotalSize int64 `json:"total_size"`
}
// StatsSnapshotDateLayout is the layout of StatsSnapshot.Date.
const StatsSnapshotDateLayout = "2006-01-02"
// GroupPage is one page of groups, flattened to rows.
type GroupPage struct {
// Packages holds every version row of each group on the page, in group