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
+7 -2
View File
@@ -1,12 +1,17 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { mount as mountWith } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import Dashboard from './Dashboard.vue'
import { usePackageStore } from '../stores/packages'
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
import { createTestRouter } from '@/test/router'
describe('Dashboard.vue', () => {
beforeEach(() => {
let router: Awaited<ReturnType<typeof createTestRouter>>
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
beforeEach(async () => {
router = await createTestRouter('/')
setActivePinia(createPinia())
__resetRealtimeSingleton()
// Mock the fetch functions to prevent actual API calls
+33 -29
View File
@@ -39,35 +39,38 @@
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle as="h2">Download activity</CardTitle>
<CardAction>
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
</CardAction>
</CardHeader>
<CardContent>
<LoadingState
v-if="chartLoading && chartData.length === 0"
layout="inline"
label="Loading chart data..."
/>
<ErrorState
v-else-if="chartError"
variant="inline"
title="Could not load download activity"
:message="chartError"
@retry="fetchTimeSeriesData"
/>
<BarChart
v-else
:labels="chartLabels"
:series="[{ name: 'Downloads', data: chartData }]"
label="Downloads over the selected period"
empty-text="No download activity in this period"
/>
</CardContent>
</Card>
<div class="grid gap-6 lg:grid-cols-2">
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Download activity</CardTitle>
<CardAction>
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
</CardAction>
</CardHeader>
<CardContent>
<LoadingState
v-if="chartLoading && chartData.length === 0"
layout="inline"
label="Loading chart data..."
/>
<ErrorState
v-else-if="chartError"
variant="inline"
title="Could not load download activity"
:message="chartError"
@retry="fetchTimeSeriesData"
/>
<BarChart
v-else
:labels="chartLabels"
:series="[{ name: 'Downloads', data: chartData }]"
label="Downloads over the selected period"
empty-text="No download activity in this period"
/>
</CardContent>
</Card>
<TrendChart compact class="min-w-0" />
</div>
<Card>
<CardHeader>
@@ -124,6 +127,7 @@ import {
type DataTableColumn,
} from '@perfect-design/ui'
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
import TrendChart from './TrendChart.vue'
import { usePackageStore, type Package } from '../stores/packages'
import { useRealtimeStore } from '../stores/realtime'
import type { EventType, RealtimeEvent } from '@/lib/ws'
+3
View File
@@ -70,6 +70,8 @@
</CardContent>
</Card>
<TrendChart />
<Card>
<CardHeader>
<CardTitle as="h2">Registry breakdown</CardTitle>
@@ -109,6 +111,7 @@ import {
StatGroup,
type DataTableColumn,
} from '@perfect-design/ui'
import TrendChart from './TrendChart.vue'
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
+213
View File
@@ -0,0 +1,213 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import TrendChart from './TrendChart.vue'
import { TREND } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
import { formatTrendDate, trendValues } from '@/lib/trend'
vi.mock('axios')
let restore: (() => void) | undefined
beforeEach(() => {
setActivePinia(createPinia())
vi.mocked(axios.get).mockReset()
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
})
afterEach(() => {
restore?.()
restore = undefined
vi.restoreAllMocks()
})
async function open(props: Record<string, unknown> = {}) {
const router = await createTestRouter('/stats')
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
restore = mounted.restore
await flushPromises()
return mounted
}
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
describe('TrendChart', () => {
it('requests the 30 day trend and draws both charts with accessible names', async () => {
const { wrapper, problems } = await open()
expect(problems).toEqual([])
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
expect(labels).toHaveLength(2)
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
})
it('offers every value as text through the chart data table', async () => {
const { wrapper } = await open()
const tables = wrapper.findAll('table')
expect(tables.length).toBeGreaterThanOrEqual(2)
expect(tables[0]!.text()).toContain('Cached packages')
expect(tables[0]!.text()).toContain('4')
})
it('refetches when the period changes', async () => {
const { wrapper } = await open()
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
await ninety.trigger('click')
await flushPromises()
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
})
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
const { wrapper } = await open()
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
expect(vulnerable()).not.toContain('lines for')
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
expect(critical.attributes('aria-pressed')).toBe('false')
await critical.trigger('click')
await flushPromises()
expect(critical.attributes('aria-pressed')).toBe('true')
expect(vulnerable()).toContain('with lines for critical')
expect(wrapper.text()).toContain('Critical (highest severity)')
await critical.trigger('click')
await flushPromises()
expect(vulnerable()).not.toContain('lines for')
})
it('offers all four severities as toggle buttons', async () => {
const { wrapper } = await open()
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
})
it('says plainly when vulnerability history starts after the first day', async () => {
const { wrapper } = await open()
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
})
it('shows no note when every day has vulnerability data', async () => {
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
vi.mocked(axios.get).mockResolvedValue({ data: full })
const { wrapper } = await open()
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
})
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
const noScans = {
...TREND,
vulnerability_history_start: null,
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
}
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
const { wrapper, problems } = await open()
expect(problems).toEqual([])
expect(charts(wrapper)).toHaveLength(1)
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
})
it('shows an empty state when the server holds no snapshots', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
const { wrapper } = await open()
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
expect(charts(wrapper)).toHaveLength(0)
})
it('shows a loading state until the first answer arrives', async () => {
let resolve!: (value: unknown) => void
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
const { wrapper } = await open()
expect(wrapper.text()).toContain('Loading package history...')
resolve({ data: TREND })
await flushPromises()
expect(wrapper.text()).not.toContain('Loading package history...')
expect(charts(wrapper)).toHaveLength(2)
})
it('shows the error with a retry that fetches again', async () => {
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
const { wrapper, problems } = await open()
expect(problems).toEqual([])
const state = wrapper.get('[data-slot="error-state"]')
expect(state.text()).toContain('502')
expect(charts(wrapper)).toHaveLength(0)
await state.get('button').trigger('click')
await flushPromises()
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
expect(charts(wrapper)).toHaveLength(2)
expect(requested()).toHaveLength(2)
})
it('rejects a body without points as an error, not an empty chart', async () => {
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
const { wrapper } = await open()
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
})
it('ignores an answer that a newer request has replaced', async () => {
const answers: Array<(v: unknown) => void> = []
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
const { wrapper } = await open()
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
await flushPromises()
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
await flushPromises()
answers[0]!({ data: TREND })
await flushPromises()
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
})
describe('compact', () => {
it('always asks for 30 days, draws one chart and links to the full history', async () => {
const { wrapper, problems } = await open({ compact: true })
expect(problems).toEqual([])
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
expect(charts(wrapper)).toHaveLength(1)
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
})
it('says so when the latest day has no vulnerability data', async () => {
const last = { ...TREND.points[2]!, vulnerable_packages: null }
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
const { wrapper } = await open({ compact: true })
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
})
})
})
describe('trend helpers', () => {
it('formats a UTC date without shifting it with the viewer zone', () => {
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
})
it('turns unknown counts into gaps, never zeros', () => {
const values = trendValues(TREND.points, 'vulnerable_packages')
expect(values[0]).toBeNaN()
expect(values.slice(1)).toEqual([1, 2])
})
})
+196
View File
@@ -0,0 +1,196 @@
<template>
<Card data-testid="trend-card">
<CardHeader>
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
<CardDescription>
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
</CardDescription>
<CardAction>
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
<Button v-else as-child variant="link" size="sm">
<RouterLink to="/stats">Open the full history</RouterLink>
</Button>
</CardAction>
</CardHeader>
<CardContent class="flex flex-col gap-8">
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
<ErrorState
v-else-if="error"
variant="inline"
title="Could not load the package history"
:message="error"
@retry="load"
/>
<EmptyState
v-else-if="points.length === 0"
title="No history yet"
description="The server records the first daily snapshot when it starts, then one more each day."
/>
<template v-else>
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
<LineChart
variant="area"
:size="compact ? 'sm' : 'md'"
:y-min="0"
:labels="labels"
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
:label="packagesLabel"
/>
</section>
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
{{ compactVulnerable }}
</p>
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
<ToggleGroup
v-model="severities"
type="multiple"
variant="outline"
size="sm"
aria-label="Add a line per highest severity"
>
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
{{ formatSeverityName(level) }}
</ToggleGroupItem>
</ToggleGroup>
</div>
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
{{ vulnerabilityNote }}
</p>
<LineChart
v-if="data?.vulnerability_history_start"
:y-min="0"
:labels="labels"
:series="vulnerableSeries"
:label="vulnerableLabel"
/>
<EmptyState
v-else
size="sm"
title="Vulnerability history has not started"
description="Scan results are counted from the first daily snapshot that includes them."
/>
</section>
</template>
</CardContent>
</Card>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { RouterLink } from 'vue-router'
import {
Button,
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
EmptyState,
ErrorState,
LineChart,
LoadingState,
SegmentedControl,
ToggleGroup,
ToggleGroupItem,
} from '@perfect-design/ui'
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
import {
DEFAULT_TREND_PERIOD,
SEVERITY_LINE_TONES,
TREND_PERIODS,
formatTrendDate,
trendValues,
type TrendPeriod,
type TrendPoint,
type TrendResponse,
} from '@/lib/trend'
const props = defineProps<{
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
compact?: boolean
}>()
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
const severities = ref<SeverityLevel[]>([])
const data = ref<TrendResponse | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
let request = 0
async function load() {
const current = ++request
loading.value = true
error.value = null
try {
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
if (current !== request) return
const body = response.data as TrendResponse | undefined
if (!body || !Array.isArray(body.points)) {
data.value = null
error.value = 'Unexpected response format from server'
return
}
data.value = body
} catch (err) {
if (current !== request) return
data.value = null
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
} finally {
if (current === request) loading.value = false
}
}
onMounted(load)
watch(period, load)
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
function span(key: keyof Omit<TrendPoint, 'date'>): string {
const known = points.value.filter((p) => p[key] !== null)
const first = known[0]
const last = known[known.length - 1]
if (!first || !last) return ''
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
}
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
const vulnerableLabel = computed(() => {
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
})
const vulnerableSeries = computed(() => [
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
name: `${formatSeverityName(level)} (highest severity)`,
data: values(level),
tone: SEVERITY_LINE_TONES[level],
})),
])
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
const vulnerabilityNote = computed(() => {
const start = data.value?.vulnerability_history_start
const first = points.value[0]
if (!start) return 'Vulnerability history has not started in this period.'
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
return ''
})
const compactVulnerable = computed(() => {
const last = points.value[points.value.length - 1]
const n = last?.vulnerable_packages
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
return `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
})
</script>
+2 -1
View File
@@ -12,7 +12,7 @@ import Stats from './Stats.vue'
import VulnerabilityBadge from './VulnerabilityBadge.vue'
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
import { usePackageStore } from '@/stores/packages'
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
@@ -22,6 +22,7 @@ const API_KEY_STORAGE = 'admin_api_key'
function respond(url: string) {
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
if (url.startsWith('/api/stats/trend')) return { data: TREND }
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
+63
View File
@@ -0,0 +1,63 @@
import type { SeverityLevel } from '@/lib/severity'
export type TrendPeriod = '30day' | '90day' | '1year'
export const TREND_PERIODS: { value: TrendPeriod; label: string }[] = [
{ value: '30day', label: '30 days' },
{ value: '90day', label: '90 days' },
{ value: '1year', label: '1 year' },
]
export const DEFAULT_TREND_PERIOD: TrendPeriod = '30day'
/** One UTC day. A null count is unknown (no scan history yet), not zero. */
export interface TrendPoint {
date: string
total_packages: number
total_size: number
vulnerable_packages: number | null
critical: number | null
high: number | null
moderate: number | null
low: number | null
blocked: number | null
}
export interface TrendResponse {
period: TrendPeriod
from: string
to: string
/** First day in the window with vulnerability data; null when the window has none. */
vulnerability_history_start: string | null
points: TrendPoint[]
}
/** Chart tone of each severity line, from the LineChart tone set. */
export const SEVERITY_LINE_TONES: Record<SeverityLevel, 'danger' | 'warning' | 'info' | 'muted'> = {
critical: 'danger',
high: 'warning',
moderate: 'info',
low: 'muted',
}
/** "2026-11-23" as "23 Nov", read in UTC so the label never shifts a day with the viewer's zone. */
export function formatTrendDate(iso: string, withYear = false): string {
const date = new Date(`${iso}T00:00:00Z`)
if (Number.isNaN(date.getTime())) return iso
return date.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short',
year: withYear ? 'numeric' : undefined,
timeZone: 'UTC',
})
}
/** Chart values of one count; unknown days become NaN, which breaks the line instead of drawing zero. */
export function trendValues(points: readonly TrendPoint[], key: keyof Omit<TrendPoint, 'date'>): number[] {
return points.map((p) => p[key] ?? Number.NaN)
}
/** True when some day in the window has no vulnerability data. */
export function hasUnknownVulnerabilityDays(points: readonly TrendPoint[]): boolean {
return points.some((p) => p.vulnerable_packages === null)
}
+3
View File
@@ -10,6 +10,7 @@
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
@@ -59,6 +60,8 @@
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
+16
View File
@@ -158,3 +158,19 @@ export const BYPASSES = [
active: false,
},
]
function trendDay(offset: number): string {
return new Date(Date.UTC(2026, 0, 4 + offset)).toISOString().slice(0, 10)
}
export const TREND = {
period: '30day',
from: trendDay(-2),
to: trendDay(0),
vulnerability_history_start: trendDay(-1),
points: [
{ date: trendDay(-2), total_packages: 3, total_size: 3072, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null, blocked: null },
{ date: trendDay(-1), total_packages: 4, total_size: 7168, vulnerable_packages: 1, critical: 0, high: 1, moderate: 0, low: 0, blocked: null },
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
],
}
+112
View File
@@ -6,6 +6,10 @@ import Mathlib
Models `pkg/metadata/gormstore/aggregation_worker.go` (`AggregateHourly`, `AggregateDaily`) and
`pkg/metadata/gormstore/gormstore_v2.go` `GetTimeSeriesStats`. Time is in whole minutes since the
epoch; an hour is 60 minutes and a day 24 hours. Omits: unique IPs, packages, registries.
The last three sections model the trend snapshots and backfill in `pkg/metadata/gormstore/snapshots.go`,
the soft-delete purge in `pkg/metadata/gormstore/purge.go` and `pkg/cache/cache.go` `purgeDeleted`,
and the severity filter in `pkg/metadata/gormstore/dashboard.go`.
-/
namespace Gohoarder.Stats
@@ -107,4 +111,112 @@ theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) :
chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive]
/-! ### Daily snapshots and backfill (`snapshots.go`) -/
/-- Minutes in a UTC day. -/
def dayLen : ℕ := 1440
/-- `stateAtDayEnd`: a package cached at `cached` and deleted at `x` (`none` = still cached) counts in
the snapshot of day `d` iff it was cached before the day ended and not deleted before it ended. -/
def aliveAtEnd (cached : ℕ) (deleted : Option ℕ) (d : ℕ) : Prop :=
cached < dayLen * (d + 1) ∧ ∀ x, deleted = some x → dayLen * (d + 1) ≤ x
/-- A package cached and deleted inside one day is in no snapshot. -/
theorem same_day_package_never_counted (cached x d : ℕ) (hx : x < dayLen * (d + 1)) :
¬ aliveAtEnd cached (some x) d := by
rintro ⟨_, h⟩
exact absurd (h x rfl) (by omega)
theorem undeleted_package_counts_from_its_day (cached d : ℕ) :
aliveAtEnd cached none d ↔ cached < dayLen * (d + 1) := by
simp [aliveAtEnd]
/-- The backfill adds only each day's change to a running total (`deltas`, then the cumulative loop). -/
def delta (s : ℕ → ℤ) (d : ℕ) : ℤ := s d - (if d = 0 then 0 else s (d - 1))
/-- The running total of the daily changes equals the end-of-day state: the sweep loses nothing. -/
theorem sweep_telescopes (s : ℕ → ℤ) (n : ℕ) :
∑ d ∈ Finset.range (n + 1), delta s d = s n := by
induction n with
| zero => simp [delta]
| succ n ih =>
rw [Finset.sum_range_succ, ih]
simp [delta]
/-- One snapshot row per day, `none` = no row. `upsertSnapshot` (`SnapshotStats`) replaces the day's row. -/
def upsertSnapshot (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ := Function.update rows day (some v)
/-- Running the snapshot twice in a day leaves the last write only. -/
theorem snapshot_last_write_wins (rows : ℕ → Option ℕ) (day a b : ℕ) :
upsertSnapshot (upsertSnapshot rows day a) day b = upsertSnapshot rows day b :=
Function.update_idem _ _ _
theorem snapshot_leaves_other_days (rows : ℕ → Option ℕ) (day other v : ℕ) (h : other ≠ day) :
upsertSnapshot rows day v other = rows other :=
Function.update_of_ne h _ _
/-- The backfill insert (`ON CONFLICT DO NOTHING`) never replaces an existing row. -/
def insertMissing (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ :=
fun d => if d = day then (rows d).or (some v) else rows d
theorem backfill_keeps_existing (rows : ℕ → Option ℕ) (day a v : ℕ) (h : rows day = some a) :
insertMissing rows day v day = some a := by
simp [insertMissing, h]
/-- The backfill runs only while no past-day snapshot exists, so it cannot rewrite history. -/
def backfillRuns (pastRows : ℕ) : Bool := pastRows == 0
theorem backfill_idle_once_history_exists (n : ℕ) : backfillRuns (n + 1) = false := by
simp [backfillRuns]
/-! ### Soft-delete purge (`purge.go`, `cache.go` `purgeDeleted`) -/
/-- Cutoff = now - retention; a row is purged iff it was deleted before the cutoff. A row that is
not deleted (`none`) is never purged. -/
def purgeable (now retention : ℕ) (deleted : Option ℕ) : Prop :=
∃ x, deleted = some x ∧ x + retention < now
theorem active_row_never_purged (now retention : ℕ) : ¬ purgeable now retention none := by
rintro ⟨x, h, _⟩
cases h
theorem recent_delete_kept (now retention x : ℕ) (h : now ≤ x + retention) :
¬ purgeable now retention (some x) := by
rintro ⟨y, hy, hlt⟩
cases hy
omega
/-- The purge touches package rows only; the snapshot rows come out as they went in. -/
def purgeStep {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
List P × (ℕ → Option ℕ) := (pkgs.filter keep, snaps)
theorem purge_keeps_snapshots {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
(purgeStep pkgs keep snaps).2 = snaps := rfl
/-- One pass purges at most `maxPurgeBatches` batches of `limit` rows. -/
def maxPurgeBatches : ℕ := 100
theorem purge_pass_bounded (batches limit : ℕ) (h : batches ≤ maxPurgeBatches) :
batches * limit ≤ maxPurgeBatches * limit :=
Nat.mul_le_mul_right limit h
/-! ### Severity filter (`dashboard.go` `severityFilter`, `latestScanWith`) -/
/-- A package passes when no severity is selected, or its latest scan counts one of them. -/
def passes (selected : List ℕ) (counts : ℕ → ℕ) : Prop := selected = [] ∨ ∃ s ∈ selected, 0 < counts s
/-- OR semantics: selecting one more severity never hides a package. -/
theorem passes_monotone (sel sel' : List ℕ) (counts : ℕ → ℕ) (h : ∀ s ∈ sel, s ∈ sel')
(hne : sel ≠ []) (hp : passes sel counts) : passes sel' counts := by
right
rcases hp with hp | ⟨s, hs, hc⟩
· exact absurd hp hne
· exact ⟨s, h s hs, hc⟩
/-- A package with no finding of any selected severity is filtered out. -/
theorem clean_package_filtered (sel : List ℕ) (hne : sel ≠ []) : ¬ passes sel (fun _ => 0) := by
rintro (h | ⟨s, _, hc⟩)
· exact hne h
· exact absurd hc (by simp)
end Gohoarder.Stats
+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)
}
}
}
+6
View File
@@ -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.
+8
View File
@@ -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.
+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
+6
View File
@@ -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
}