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
+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