fix(ui): rank most requested packages by the stored download counts

The ranking read in-memory analytics, so it was empty after every restart
while the Downloads chart and the package pages read the database. It now
sums the stored counts per package, counts a Go module once by its zip,
and says which ranking is kept across restarts and which is not.
This commit is contained in:
2026-11-24 02:06:14 +00:00
parent 798fadb4bb
commit a685b71c7f
5 changed files with 111 additions and 8 deletions
+3 -1
View File
@@ -6,7 +6,8 @@ import Overview from './Overview.vue'
import { usePackageStore } from '../stores/packages'
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
import { __resetSystem } from '@/lib/system'
import { REGISTRIES, STATS, SYSTEM, TIMESERIES, TOP_PACKAGES } from '@/test/fixtures'
import { PACKAGES, REGISTRIES, STATS, SYSTEM, TIMESERIES, TOP_PACKAGES } from '@/test/fixtures'
import { serveRows } from '@/test/rowsServer'
import { mountStrict } from '@/test/mountStrict'
import { createTestRouter } from '@/test/router'
@@ -20,6 +21,7 @@ beforeEach(() => {
__resetSystem()
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.startsWith('/api/system')) return { data: SYSTEM } as never
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) } as never
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES } as never
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES } as never
return { data: { stats: STATS, registries: REGISTRIES } } as never
@@ -0,0 +1,84 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import TopPackages from './TopPackages.vue'
import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
let restore: (() => void) | undefined
const row = (registry: string, name: string, download_count: number) => ({ registry, name, version: '1.0.0', download_count })
function serve(rows: unknown[], trending: unknown[] = []) {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.startsWith('/api/analytics/trending')) return { data: { packages: trending } } as never
if (url.startsWith('/api/packages?layout=rows')) return { data: { packages: rows } } as never
throw new Error(`unexpected request: ${url}`)
})
}
async function open() {
const mounted = await mountStrict(TopPackages)
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
beforeEach(() => {
vi.mocked(axios.get).mockReset()
})
afterEach(() => {
restore?.()
restore = undefined
})
describe('TopPackages', () => {
it('ranks packages by the stored download counts, so a restart does not empty it', async () => {
serve([row('npm', 'left-pad', 12), row('npm', 'left-pad', 5), row('pypi', 'six', 9)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('npm · left-pad')
expect(text).toContain('pypi · six')
expect(text).not.toContain('No downloads yet')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200')
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith(expect.stringContaining('/api/analytics/top'))
})
it('adds the versions of a package and orders by the sum', async () => {
serve([row('npm', 'a', 10), row('npm', 'b', 15), row('npm', 'a', 9)])
const wrapper = await open()
const labels = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
expect(labels[0]).toContain('npm · a')
expect(labels[1]).toContain('npm · b')
})
it('counts a Go module once, by its zip, and not its .mod and .info files', async () => {
serve([
row('go', 'github.com/google/uuid/@v/v1.6.0.zip', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.mod', 4),
row('go', 'github.com/google/uuid/@v/v1.6.0.info', 4),
])
const wrapper = await open()
const entries = wrapper.findAll('[data-testid="top-packages"] li')
expect(entries).toHaveLength(1)
expect(entries[0].text()).toContain('go · github.com/google/uuid')
expect(entries[0].text()).toContain('4')
expect(entries[0].text()).not.toContain('12')
})
it('says so when no package has a download', async () => {
serve([row('npm', 'left-pad', 0)])
const wrapper = await open()
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
})
it('names where each ranking comes from', async () => {
serve([row('npm', 'left-pad', 3)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('The counts survive restarts.')
expect(text).toContain('Counted in memory, so it restarts with the server.')
})
})
+23 -6
View File
@@ -3,7 +3,7 @@
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Most requested</CardTitle>
<CardDescription>Total downloads since the server started.</CardDescription>
<CardDescription>Downloads served from the cache. The counts survive restarts.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading top packages..." />
@@ -15,7 +15,7 @@
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Trending</CardTitle>
<CardDescription>Downloads in the last 7 days.</CardDescription>
<CardDescription>Downloads in the last 7 days. Counted in memory, so it restarts with the server.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
@@ -52,8 +52,18 @@ interface PopularPackage {
RecentDownloads: number
}
/** One stored version row; its count is kept in the database. */
interface DownloadRow {
registry: string
name: string
download_count: number
}
const LIMIT = 8
const popular = ref<PopularPackage[]>([])
// Go keeps one row per file (.zip, .mod, .info) of a version; only the zip is a module download.
const GO_METADATA = /\.(mod|info)$/
const ROWS_URL = '/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200'
const stored = ref<DownloadRow[]>([])
const recent = ref<PopularPackage[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
@@ -70,7 +80,14 @@ function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number): L
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
}
const top = computed(() => entries(popular.value, (p) => p.Downloads))
const top = computed(() =>
entries(
stored.value
.filter((r) => !(r.registry === 'go' && GO_METADATA.test(r.name)))
.map((r) => ({ Registry: r.registry, Name: r.name, Downloads: r.download_count, RecentDownloads: 0 })),
(p) => p.Downloads,
),
)
const trending = computed(() => entries(recent.value, (p) => p.RecentDownloads))
async function load() {
@@ -78,10 +95,10 @@ async function load() {
error.value = null
try {
const [topRes, trendRes] = await Promise.all([
axios.get<{ packages: PopularPackage[] }>('/api/analytics/top?limit=50'),
axios.get<{ packages: DownloadRow[] }>(ROWS_URL),
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
])
popular.value = topRes.data.packages ?? []
stored.value = topRes.data.packages ?? []
recent.value = trendRes.data.packages ?? []
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to load package rankings'
@@ -106,7 +106,6 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(wrapper.find('[data-testid="cache-capacity"]').text()).toContain('5 GB of 10 GB')
expect(wrapper.find('[data-testid="download-trend"] [role="img"]').exists()).toBe(true)
expect(wrapper.find('[data-testid="top-packages"]').text()).toContain('npm · left-pad')
expect(wrapper.find('[data-testid="top-packages"]').text()).toContain('go · github.com/example/module')
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('grype')
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('Unavailable')
expect(wrapper.find('[data-testid="ws-event-feed"]').text()).toContain('left-pad')
+1
View File
@@ -50,6 +50,7 @@ export function serveRows(url: string, all: readonly Package[]) {
return 0
})
}
if (sort === 'downloads') matched.sort((a, b) => (params.get('order') === 'asc' ? 1 : -1) * (a.download_count - b.download_count))
return {
packages: matched.slice((page - 1) * pageSize, page * pageSize),
total: matched.length,