mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
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:
+12
-6
@@ -215,6 +215,10 @@ func (a *App) initializeComponents() error {
|
||||
return fmt.Errorf("failed to initialize scanner: %w", err)
|
||||
}
|
||||
|
||||
if setter, ok := a.metadata.(blockedCounterSetter); ok {
|
||||
setter.SetBlockedCounter(a.countBlocked)
|
||||
}
|
||||
|
||||
// Initialize analytics engine first (needed by cache)
|
||||
log.Info().Msg("Initializing analytics engine")
|
||||
a.analyticsEngine = analytics.NewEngine(analytics.Config{
|
||||
@@ -231,12 +235,12 @@ func (a *App) initializeComponents() error {
|
||||
cleanupInterval = 5 * time.Minute
|
||||
}
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize cache: %w", err)
|
||||
@@ -446,6 +450,7 @@ func (a *App) setupServer() error {
|
||||
a.app.All("/api/packages/*", mwAuth, a.handlePackages) // OPTIONS, preflight, vulnerabilities
|
||||
a.app.Get("/api/stats", mwAuth, a.handleStats)
|
||||
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
|
||||
a.app.Get("/api/info", mwAuth, a.handleInfo)
|
||||
|
||||
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
|
||||
@@ -460,6 +465,7 @@ func (a *App) setupServer() error {
|
||||
a.app.All("/api/packages/*", a.handlePackages)
|
||||
a.app.Get("/api/stats", a.handleStats)
|
||||
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", a.handleStatsTrend)
|
||||
a.app.Get("/api/info", a.handleInfo)
|
||||
|
||||
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
|
||||
|
||||
+3
-12
@@ -391,20 +391,11 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
blockedCount := int64(0)
|
||||
if a.config.Security.Enabled && a.scanManager != nil {
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blockedCount++
|
||||
}
|
||||
}
|
||||
blockedCount, err := a.countBlocked(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
|
||||
|
||||
// Combine statistics using database stats for accuracy
|
||||
stats := map[string]interface{}{
|
||||
"total_packages": cacheStats.TotalPackages,
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// trendPeriods maps the period query value of /api/stats/trend to days of history.
|
||||
var trendPeriods = map[string]int{"30day": 30, "90day": 90, "1year": 365}
|
||||
|
||||
const defaultTrendPeriod = "30day"
|
||||
|
||||
// handleStatsTrend returns one snapshot per day for the period, oldest first.
|
||||
// Vulnerability fields are null for days before vulnerability history starts.
|
||||
func (a *App) handleStatsTrend(c fiber.Ctx) error {
|
||||
period := c.Query("period", defaultTrendPeriod)
|
||||
days, ok := trendPeriods[period]
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"error": "invalid period, must be one of: 30day, 90day, 1year",
|
||||
})
|
||||
}
|
||||
|
||||
today := time.Now().UTC().Truncate(24 * time.Hour)
|
||||
from := today.AddDate(0, 0, -(days - 1))
|
||||
points, err := a.metadata.GetStatsTrend(c.Context(), from)
|
||||
if err != nil && !errors.Is(err, metadata.ErrNotImplemented) {
|
||||
log.Error().Err(err).Str("period", period).Msg("Failed to get stats trend")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get stats trend"})
|
||||
}
|
||||
if points == nil {
|
||||
points = []*metadata.StatsSnapshot{}
|
||||
}
|
||||
|
||||
var vulnStart *string
|
||||
for _, p := range points {
|
||||
if p.VulnerablePackages != nil {
|
||||
vulnStart = &p.Date
|
||||
break
|
||||
}
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"period": period,
|
||||
"from": from.Format(metadata.StatsSnapshotDateLayout),
|
||||
"to": today.Format(metadata.StatsSnapshotDateLayout),
|
||||
"vulnerability_history_start": vulnStart,
|
||||
"points": points,
|
||||
})
|
||||
}
|
||||
|
||||
// countBlocked counts scanned artifacts the blocking policy refuses.
|
||||
func (a *App) countBlocked(ctx context.Context) (int64, error) {
|
||||
if !a.config.Security.Enabled || a.scanManager == nil {
|
||||
return 0, nil
|
||||
}
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var blocked int64
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blocked++
|
||||
}
|
||||
}
|
||||
return blocked, nil
|
||||
}
|
||||
|
||||
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
|
||||
type blockedCounterSetter interface {
|
||||
SetBlockedCounter(func(context.Context) (int64, error))
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
)
|
||||
|
||||
type trendResponse struct {
|
||||
VulnerabilityHistoryStart *string `json:"vulnerability_history_start"`
|
||||
Period string `json:"period"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Points []struct {
|
||||
VulnerablePackages *int64 `json:"vulnerable_packages"`
|
||||
Blocked *int64 `json:"blocked"`
|
||||
Date string `json:"date"`
|
||||
TotalPackages int64 `json:"total_packages"`
|
||||
} `json:"points"`
|
||||
}
|
||||
|
||||
func trendDay(daysAgo int) string {
|
||||
return time.Now().UTC().AddDate(0, 0, -daysAgo).Format("2006-01-02")
|
||||
}
|
||||
|
||||
func getTrend(t *testing.T, a *App, target string) trendResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out trendResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeverityAndTrendQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{
|
||||
"/api/packages?severity=critical,high",
|
||||
"/api/packages?severity=low&page=1&page_size=25",
|
||||
"/api/stats/trend?period=90day",
|
||||
}
|
||||
seedScanned(t, a, 0, 20)
|
||||
small := map[string]int{}
|
||||
for _, target := range targets {
|
||||
small[target] = queriesFor(t, a, counter, target)
|
||||
}
|
||||
seedScanned(t, a, 20, 100)
|
||||
for _, target := range targets {
|
||||
large := queriesFor(t, a, counter, target)
|
||||
t.Logf("%-50s 20 rows: %2d queries, 120 rows: %2d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
if n := small["/api/stats/trend?period=90day"]; n != 1 {
|
||||
t.Errorf("trend costs %d statements, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendEndpoint(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
empty := getTrend(t, a, "/api/stats/trend")
|
||||
if empty.Period != "30day" || empty.Points == nil || len(empty.Points) != 0 || empty.VulnerabilityHistoryStart != nil {
|
||||
t.Fatalf("empty trend = %+v, want the default period, no points and no vulnerability start", empty)
|
||||
}
|
||||
|
||||
store := a.metadata.(*gormstore.GORMStoreV2)
|
||||
one, two := int64(1), int64(2)
|
||||
for _, row := range []gormstore.StatsSnapshotModel{
|
||||
{Day: trendDay(100), TotalPackages: 5},
|
||||
{Day: trendDay(40), TotalPackages: 6},
|
||||
{Day: trendDay(2), TotalPackages: 7},
|
||||
{Day: trendDay(1), TotalPackages: 8, VulnerablePackages: &two, Blocked: &one},
|
||||
} {
|
||||
if err := store.DB().Create(&row).Error; err != nil {
|
||||
t.Fatalf("seed snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
target string
|
||||
period string
|
||||
points int
|
||||
}{
|
||||
{"/api/stats/trend", "30day", 2},
|
||||
{"/api/stats/trend?period=30day", "30day", 2},
|
||||
{"/api/stats/trend?period=90day", "90day", 3},
|
||||
{"/api/stats/trend?period=1year", "1year", 4},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := getTrend(t, a, c.target)
|
||||
if got.Period != c.period || len(got.Points) != c.points {
|
||||
t.Errorf("%s = period %q, %d points; want %q, %d", c.target, got.Period, len(got.Points), c.period, c.points)
|
||||
}
|
||||
}
|
||||
|
||||
got := getTrend(t, a, "/api/stats/trend")
|
||||
if got.To != trendDay(0) || got.From != trendDay(29) {
|
||||
t.Errorf("window = %s..%s, want %s..%s", got.From, got.To, trendDay(29), trendDay(0))
|
||||
}
|
||||
if got.Points[0].Date != trendDay(2) || got.Points[1].Date != trendDay(1) {
|
||||
t.Errorf("points not oldest first: %+v", got.Points)
|
||||
}
|
||||
if got.Points[0].VulnerablePackages != nil || got.Points[0].Blocked != nil {
|
||||
t.Errorf("a day without vulnerability data must carry null, got %+v", got.Points[0])
|
||||
}
|
||||
if v := got.Points[1].VulnerablePackages; v == nil || *v != 2 {
|
||||
t.Errorf("vulnerable_packages = %v, want 2", v)
|
||||
}
|
||||
if got.VulnerabilityHistoryStart == nil || *got.VulnerabilityHistoryStart != trendDay(1) {
|
||||
t.Errorf("vulnerability_history_start = %v, want %s", got.VulnerabilityHistoryStart, trendDay(1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendRejectsUnknownPeriod(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, p := range []string{"7day", "1day", "bogus", "1YEAR"} {
|
||||
if code, _, body := doRequest(t, a, "/api/stats/trend?period="+p, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("period=%s = %d %s, want 400", p, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,12 @@ func (f *fakeStore) ListExpiredPackages(context.Context, time.Time, int) ([]*met
|
||||
func (f *fakeStore) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
|
||||
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
|
||||
|
||||
Vendored
+8
@@ -265,6 +265,14 @@ func (m *MockMetadataStore) ListExpiredPackages(context.Context, time.Time, int)
|
||||
|
||||
func (m *MockMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
|
||||
func (m *MockMetadataStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, 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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -134,6 +134,12 @@ func (m *stubMetadataStore) ListExpiredPackages(context.Context, time.Time, int)
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
func (m *stubMetadataStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
func (m *stubMetadataStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) SaveAPIKey(context.Context, *metadata.APIKey) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user