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
+12 -6
View File
@@ -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
View File
@@ -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,
+77
View File
@@ -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))
}
+130
View File
@@ -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)
}
}
}