From 3bfc367898568abe5ef081809be77ba1e9b1ab2f Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Tue, 24 Nov 2026 02:33:21 +0000 Subject: [PATCH] feat(analytics): serve trending packages from persisted downloads Trending read the in-memory analytics engine, which restarts empty. The endpoint now ranks packages by the last 7 days of stored downloads and reports the previous 7 days for the change. It counts a Go module once and skips metadata entries. A daily time_bucket index serves the range read. The Overview panel shows the change and no longer says the data resets on restart. --- .../src/components/parts/TopPackages.spec.ts | 16 +- frontend/src/components/parts/TopPackages.vue | 23 ++- pkg/app/handlers_analytics.go | 43 +++++- pkg/app/handlers_trending_test.go | 84 ++++++++++ pkg/metadata/gormstore/migrations.go | 13 ++ pkg/metadata/gormstore/models_v2.go | 4 +- pkg/metadata/gormstore/trending.go | 112 ++++++++++++++ pkg/metadata/gormstore/trending_test.go | 145 ++++++++++++++++++ pkg/metadata/interface.go | 14 ++ 9 files changed, 444 insertions(+), 10 deletions(-) create mode 100644 pkg/app/handlers_trending_test.go create mode 100644 pkg/metadata/gormstore/trending.go create mode 100644 pkg/metadata/gormstore/trending_test.go diff --git a/frontend/src/components/parts/TopPackages.spec.ts b/frontend/src/components/parts/TopPackages.spec.ts index 889d20e..0880e48 100644 --- a/frontend/src/components/parts/TopPackages.spec.ts +++ b/frontend/src/components/parts/TopPackages.spec.ts @@ -74,11 +74,25 @@ describe('TopPackages', () => { expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet') }) + it('shows the change against the previous 7 days for trending packages', async () => { + serve([], [ + { Registry: 'npm', Name: 'left-pad', Downloads: 9, RecentDownloads: 9, PreviousDownloads: 4 }, + { Registry: 'npm', Name: 'six', Downloads: 3, RecentDownloads: 3, PreviousDownloads: 8 }, + ]) + const wrapper = await open() + const rows = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text()) + const pad = rows.find((r) => r.includes('left-pad')) + const six = rows.find((r) => r.includes('six')) + expect(pad).toMatch(/\+5/) + expect(six).toMatch(/[-−]5/) + }) + 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.') + expect(text).toContain('the change from the 7 days before') + expect(text).not.toContain('restarts with the server') }) }) diff --git a/frontend/src/components/parts/TopPackages.vue b/frontend/src/components/parts/TopPackages.vue index 0e6f57d..1820797 100644 --- a/frontend/src/components/parts/TopPackages.vue +++ b/frontend/src/components/parts/TopPackages.vue @@ -15,7 +15,7 @@ Trending - Downloads in the last 7 days. Counted in memory, so it restarts with the server. + Downloads in the last 7 days, and the change from the 7 days before. The counts survive restarts. @@ -44,12 +44,13 @@ import { } from '@perfect-design/ui' import { modulePath } from '@/lib/format' -/** The analytics engine serialises Go field names. */ +/** The trending endpoint serialises Go field names. */ interface PopularPackage { Registry: string Name: string Downloads: number RecentDownloads: number + PreviousDownloads?: number } /** One stored version row; its count is kept in the database. */ @@ -69,13 +70,17 @@ const loading = ref(false) const error = ref(null) // Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package. -function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number): LeaderboardEntry[] { +function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number, change?: (p: PopularPackage) => number): LeaderboardEntry[] { const totals = new Map() for (const row of rows) { const id = `${row.Registry}/${modulePath(row.Name)}` const existing = totals.get(id) - if (existing) existing.value += pick(row) - else totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row) }) + if (existing) { + existing.value += pick(row) + if (change) existing.delta = (existing.delta ?? 0) + change(row) + } else { + totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row), ...(change ? { delta: change(row) } : {}) }) + } } return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT) } @@ -88,7 +93,13 @@ const top = computed(() => (p) => p.Downloads, ), ) -const trending = computed(() => entries(recent.value, (p) => p.RecentDownloads)) +const trending = computed(() => + entries( + recent.value, + (p) => p.RecentDownloads, + (p) => p.RecentDownloads - (p.PreviousDownloads ?? 0), + ), +) async function load() { loading.value = true diff --git a/pkg/app/handlers_analytics.go b/pkg/app/handlers_analytics.go index b3ed3df..04bd3c4 100644 --- a/pkg/app/handlers_analytics.go +++ b/pkg/app/handlers_analytics.go @@ -4,6 +4,7 @@ import ( "strconv" "github.com/gofiber/fiber/v3" + "github.com/lukaszraczylo/gohoarder/pkg/metadata" "github.com/rs/zerolog/log" ) @@ -27,7 +28,18 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error { }) } -// handleAnalyticsTrendingPackages returns trending packages +// trendingPackage keeps the Go field names the dashboard reads from the analytics engine. +type trendingPackage struct { + Registry string + Name string + Downloads int64 + RecentDownloads int64 + PreviousDownloads int64 + Trend float64 +} + +// handleAnalyticsTrendingPackages ranks packages by downloads in the last 7 days. Persisted +// history serves it so a restart keeps the ranking; the in-memory engine covers stores without it. func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error { c.Set("Content-Type", "application/json") @@ -39,6 +51,35 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error { } } + if source, ok := a.metadata.(metadata.TrendingSource); ok { + stored, err := source.GetTrendingPackages(c.Context(), limit) + if err != nil { + log.Error().Err(err).Msg("Failed to read trending packages") + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ + "error": "failed to read trending packages", + }) + } + packages := make([]trendingPackage, 0, len(stored)) + for _, p := range stored { + trend := 0.0 + if p.Previous > 0 { + trend = float64(p.Recent-p.Previous) / float64(p.Previous) * 100 + } + packages = append(packages, trendingPackage{ + Registry: p.Registry, + Name: p.Name, + Downloads: p.Recent, + RecentDownloads: p.Recent, + PreviousDownloads: p.Previous, + Trend: trend, + }) + } + return c.Status(fiber.StatusOK).JSON(fiber.Map{ + "packages": packages, + "total": len(packages), + }) + } + packages := a.analyticsEngine.GetTrendingPackages(limit) return c.Status(fiber.StatusOK).JSON(fiber.Map{ diff --git a/pkg/app/handlers_trending_test.go b/pkg/app/handlers_trending_test.go new file mode 100644 index 0000000..34e97aa --- /dev/null +++ b/pkg/app/handlers_trending_test.go @@ -0,0 +1,84 @@ +package app + +import ( + "context" + "encoding/json" + "fmt" + "net/http/httptest" + "testing" + "time" + + "github.com/gofiber/fiber/v3" + "github.com/lukaszraczylo/gohoarder/pkg/analytics" + "github.com/lukaszraczylo/gohoarder/pkg/metadata" + "github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore" + "github.com/stretchr/testify/require" +) + +type trendingResponse struct { + Packages []trendingPackage `json:"packages"` + Total int `json:"total"` +} + +func getTrending(t *testing.T, a *App, query string) trendingResponse { + t.Helper() + f := fiber.New() + f.Get("/api/analytics/trending", a.handleAnalyticsTrendingPackages) + resp, err := f.Test(httptest.NewRequest("GET", "/api/analytics/trending"+query, nil)) + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode) + var out trendingResponse + require.NoError(t, json.NewDecoder(resp.Body).Decode(&out)) + return out +} + +func seedDownloads(t *testing.T, store metadata.Store, registry, name, version string, n int) { + t.Helper() + ctx := context.Background() + now := time.Now() + require.NoError(t, store.SavePackage(ctx, &metadata.Package{ + Registry: registry, Name: name, Version: version, StorageKey: registry + "/" + name + "/" + version, + Size: 1, CachedAt: now, LastAccessed: now, + })) + for i := 0; i < n; i++ { + require.NoError(t, store.UpdateDownloadCount(ctx, registry, name, version)) + } +} + +func TestTrendingServedFromPersistedDownloads(t *testing.T) { + store, err := gormstore.NewV2(gormstore.Config{ + Driver: "sqlite", DSN: fmt.Sprintf("file:trend_%d?mode=memory&cache=shared", time.Now().UnixNano()), + MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent", + }) + require.NoError(t, err) + t.Cleanup(func() { _ = store.Close() }) + seedDownloads(t, store, "npm", "left-pad", "1.3.0", 3) + seedDownloads(t, store, "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", 2) + seedDownloads(t, store, "go", "github.com/google/uuid/@v/v1.6.0.mod", "v1.6.0", 2) + + // A fresh engine is what a restarted server has: it must not decide the ranking. + engine := analytics.NewEngine(analytics.Config{MaxEvents: 10, FlushInterval: time.Minute}) + t.Cleanup(engine.Close) + + got := getTrending(t, &App{metadata: store, analyticsEngine: engine}, "") + require.Equal(t, 2, got.Total) + require.Equal(t, "npm", got.Packages[0].Registry) + require.Equal(t, "left-pad", got.Packages[0].Name) + require.Equal(t, int64(3), got.Packages[0].RecentDownloads) + require.Equal(t, int64(0), got.Packages[0].PreviousDownloads) + require.Equal(t, "github.com/google/uuid", got.Packages[1].Name) + require.Equal(t, int64(2), got.Packages[1].RecentDownloads) + + limited := getTrending(t, &App{metadata: store, analyticsEngine: engine}, "?limit=1") + require.Len(t, limited.Packages, 1) +} + +func TestTrendingFallsBackToEngineWithoutPersistedHistory(t *testing.T) { + engine := analytics.NewEngine(analytics.Config{MaxEvents: 10, FlushInterval: time.Minute}) + t.Cleanup(engine.Close) + engine.TrackDownload(analytics.PackageDownload{Registry: "npm", Name: "lodash", Version: "4", Timestamp: time.Now()}) + + got := getTrending(t, &App{analyticsEngine: engine}, "") + require.Equal(t, 1, got.Total) + require.Equal(t, "lodash", got.Packages[0].Name) +} diff --git a/pkg/metadata/gormstore/migrations.go b/pkg/metadata/gormstore/migrations.go index c3305e7..32a3899 100644 --- a/pkg/metadata/gormstore/migrations.go +++ b/pkg/metadata/gormstore/migrations.go @@ -113,9 +113,22 @@ func GetMigrations() []*gormigrate.Migration { return tx.Migrator().DropTable(&StatsSnapshotModel{}) }, }, + { + // Serves the previous-week range read behind trending packages. + ID: "202611250002", + Migrate: func(tx *gorm.DB) error { + return createIndexIfMissing(tx, &DownloadStatsDailyModel{}, dailyTimeIndex) + }, + Rollback: func(tx *gorm.DB) error { + return tx.Migrator().DropIndex(&DownloadStatsDailyModel{}, dailyTimeIndex) + }, + }, } } +// dailyTimeIndex is download_stats_daily (time_bucket). +const dailyTimeIndex = "idx_stats_daily_time" + // scanPackageScannedAtIndex is scan_results (package_id, scanned_at). const scanPackageScannedAtIndex = "idx_scan_package_scanned_at" diff --git a/pkg/metadata/gormstore/models_v2.go b/pkg/metadata/gormstore/models_v2.go index df1f113..c172fc9 100644 --- a/pkg/metadata/gormstore/models_v2.go +++ b/pkg/metadata/gormstore/models_v2.go @@ -238,8 +238,8 @@ func (DownloadStatsHourlyModel) TableName() string { // DownloadStatsDailyModel represents pre-aggregated daily statistics type DownloadStatsDailyModel struct { - TimeBucket time.Time `gorm:"not null;index:idx_stats_daily_composite,priority:2"` // Truncated to day - PackageID *int64 `gorm:"index:idx_stats_daily_package"` // NULL = all packages in registry + TimeBucket time.Time `gorm:"not null;index:idx_stats_daily_composite,priority:2;index:idx_stats_daily_time"` // Truncated to day + PackageID *int64 `gorm:"index:idx_stats_daily_package"` // NULL = all packages in registry TopUserAgents JSONBField // Top 10 user agents BaseModel diff --git a/pkg/metadata/gormstore/trending.go b/pkg/metadata/gormstore/trending.go new file mode 100644 index 0000000..11a92e3 --- /dev/null +++ b/pkg/metadata/gormstore/trending.go @@ -0,0 +1,112 @@ +package gormstore + +import ( + "context" + "sort" + "strings" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/errors" + "github.com/lukaszraczylo/gohoarder/pkg/metadata" +) + +const trendingWindow = 7 * 24 * time.Hour + +type trendingKey struct{ registry, name string } + +type trendingRow struct { + Registry string + Name string + Version string + Count int64 +} + +// GetTrendingPackages ranks packages by downloads in the last 7 days, with the 7 days before +// for the change. Downloads sit in raw events (current hour), hourly rows (last 7 days) and +// daily rollups (older), the same layering GetTimeSeriesStats merges. +func (s *GORMStoreV2) GetTrendingPackages(ctx context.Context, limit int) ([]*metadata.TrendingPackage, error) { + now := s.clock().UTC() + since := now.Add(-trendingWindow) + // Daily rows hold whole days, so the previous window ends at the day boundary at or before since. + // The 12h shift keeps midnight rows on the right side whether the driver stores a date or a timestamp. + prevEnd := since.Truncate(24 * time.Hour).Add(-12 * time.Hour) + prevStart := prevEnd.Add(-trendingWindow) + + hourly, err := s.packageDownloads(ctx, "download_stats_hourly s", "SUM(s.download_count)", "s.time_bucket >= ?", since) + if err != nil { + return nil, err + } + events, err := s.packageDownloads(ctx, "download_events s", "COUNT(*)", "s.downloaded_at >= ?", since) + if err != nil { + return nil, err + } + daily, err := s.packageDownloads(ctx, "download_stats_daily s", "SUM(s.download_count)", "s.time_bucket >= ? AND s.time_bucket < ?", prevStart, prevEnd) + if err != nil { + return nil, err + } + + totals := make(map[trendingKey]*metadata.TrendingPackage) + add := func(rows []trendingRow, recent bool) { + for _, r := range rows { + if metadata.IsMetadataEntry(r.Registry, r.Name, r.Version) { + continue + } + name := r.Name + if r.Registry == metadata.GoRegistry { + name, _, _ = strings.Cut(name, "/@v/") + } + key := trendingKey{r.Registry, name} + pkg := totals[key] + if pkg == nil { + pkg = &metadata.TrendingPackage{Registry: r.Registry, Name: name} + totals[key] = pkg + } + if recent { + pkg.Recent += r.Count + } else { + pkg.Previous += r.Count + } + } + } + add(hourly, true) + add(events, true) + add(daily, false) + + ranked := make([]*metadata.TrendingPackage, 0, len(totals)) + for _, pkg := range totals { + if pkg.Recent > 0 { + ranked = append(ranked, pkg) + } + } + sort.Slice(ranked, func(i, j int) bool { + if ranked[i].Recent != ranked[j].Recent { + return ranked[i].Recent > ranked[j].Recent + } + if ranked[i].Registry != ranked[j].Registry { + return ranked[i].Registry < ranked[j].Registry + } + return ranked[i].Name < ranked[j].Name + }) + if limit > 0 && limit < len(ranked) { + ranked = ranked[:limit] + } + return ranked, nil +} + +// packageDownloads sums one download table per package row; table carries the alias "s". +func (s *GORMStoreV2) packageDownloads(ctx context.Context, table, sum, cond string, args ...interface{}) ([]trendingRow, error) { + var rows []trendingRow + err := s.db.WithContext(ctx). + Table(table). + Select("r.name AS registry, p.name AS name, p.version AS version, "+sum+" AS count"). + Joins("JOIN packages p ON p.id = s.package_id"). + Joins("JOIN registries r ON r.id = p.registry_id"). + Where("s.package_id IS NOT NULL"). + Where(cond, args...). + Group("r.name, p.name, p.version"). + Scan(&rows).Error + if err != nil { + return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read trending downloads") + } + return rows, nil +} diff --git a/pkg/metadata/gormstore/trending_test.go b/pkg/metadata/gormstore/trending_test.go new file mode 100644 index 0000000..891cc2b --- /dev/null +++ b/pkg/metadata/gormstore/trending_test.go @@ -0,0 +1,145 @@ +package gormstore + +import ( + "context" + "testing" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/metadata" + "github.com/stretchr/testify/require" +) + +var trendingNow = time.Date(2026, 11, 24, 10, 30, 0, 0, time.UTC) + +func trendingStore(t *testing.T) *GORMStoreV2 { + t.Helper() + store := newTimeSeriesStore(t) + store.now = func() time.Time { return trendingNow } + return store +} + +func trendingPackage(t *testing.T, store *GORMStoreV2, registry, name, version string) int64 { + t.Helper() + ctx := context.Background() + require.NoError(t, store.SavePackage(ctx, &metadata.Package{ + Registry: registry, Name: name, Version: version, StorageKey: registry + "/" + name + "/" + version, + Size: 10, CachedAt: trendingNow, LastAccessed: trendingNow, + })) + var pkg PackageModel + require.NoError(t, store.db.Where("name = ? AND version = ?", name, version).First(&pkg).Error) + return pkg.ID +} + +func trendingEvents(t *testing.T, store *GORMStoreV2, packageID int64, at time.Time, n int) { + t.Helper() + var pkg PackageModel + require.NoError(t, store.db.First(&pkg, packageID).Error) + for i := 0; i < n; i++ { + require.NoError(t, store.db.Create(&DownloadEventModel{PackageID: packageID, RegistryID: pkg.RegistryID, DownloadedAt: at}).Error) + } +} + +func trendingStat(t *testing.T, store *GORMStoreV2, model interface{}, packageID int64, bucket time.Time, n int64) { + t.Helper() + var pkg PackageModel + require.NoError(t, store.db.First(&pkg, packageID).Error) + switch model.(type) { + case *DownloadStatsHourlyModel: + require.NoError(t, store.db.Create(&DownloadStatsHourlyModel{RegistryID: pkg.RegistryID, PackageID: &packageID, TimeBucket: bucket, DownloadCount: n}).Error) + default: + require.NoError(t, store.db.Create(&DownloadStatsDailyModel{RegistryID: pkg.RegistryID, PackageID: &packageID, TimeBucket: bucket, DownloadCount: n}).Error) + } +} + +func TestTrendingCombinesEventsHourlyAndPreviousWeek(t *testing.T) { + store := trendingStore(t) + ctx := context.Background() + pad := trendingPackage(t, store, "npm", "left-pad", "1.3.0") + + trendingEvents(t, store, pad, trendingNow.Add(-10*time.Minute), 2) + trendingStat(t, store, &DownloadStatsHourlyModel{}, pad, trendingNow.Add(-3*24*time.Hour).Truncate(time.Hour), 5) + trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC), 4) + trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 15, 0, 0, 0, 0, time.UTC), 3) + + got, err := store.GetTrendingPackages(ctx, 10) + require.NoError(t, err) + require.Equal(t, []*metadata.TrendingPackage{{Registry: "npm", Name: "left-pad", Recent: 7, Previous: 7}}, got) +} + +func TestTrendingExcludesDownloadsOutsideBothWindows(t *testing.T) { + store := trendingStore(t) + pad := trendingPackage(t, store, "npm", "left-pad", "1.3.0") + trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 5, 0, 0, 0, 0, time.UTC), 50) + trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 17, 0, 0, 0, 0, time.UTC), 60) + trendingEvents(t, store, pad, trendingNow.Add(-time.Minute), 1) + + got, err := store.GetTrendingPackages(context.Background(), 10) + require.NoError(t, err) + require.Len(t, got, 1) + require.Equal(t, int64(1), got[0].Recent) + require.Equal(t, int64(0), got[0].Previous) +} + +func TestTrendingKeepsOnlyPackagesDownloadedThisWeek(t *testing.T) { + store := trendingStore(t) + old := trendingPackage(t, store, "npm", "old", "1.0.0") + trendingStat(t, store, &DownloadStatsDailyModel{}, old, time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC), 9) + + got, err := store.GetTrendingPackages(context.Background(), 10) + require.NoError(t, err) + require.Empty(t, got) +} + +func TestTrendingCountsGoModuleOnceAndSkipsMetadata(t *testing.T) { + store := trendingStore(t) + zip := trendingPackage(t, store, "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0") + mod := trendingPackage(t, store, "go", "github.com/google/uuid/@v/v1.6.0.mod", "v1.6.0") + list := trendingPackage(t, store, "go", "github.com/google/uuid/@v/list", "list") + other := trendingPackage(t, store, "go", "github.com/google/uuid/@v/v1.5.0.zip", "v1.5.0") + meta := trendingPackage(t, store, "npm", "left-pad", "metadata") + for _, id := range []int64{zip, mod, list, meta} { + trendingEvents(t, store, id, trendingNow.Add(-time.Hour), 3) + } + trendingEvents(t, store, other, trendingNow.Add(-time.Hour), 2) + + got, err := store.GetTrendingPackages(context.Background(), 10) + require.NoError(t, err) + require.Equal(t, []*metadata.TrendingPackage{{Registry: "go", Name: "github.com/google/uuid", Recent: 5}}, got) +} + +func TestTrendingKeysByRegistryAndRanksWithLimit(t *testing.T) { + store := trendingStore(t) + npm := trendingPackage(t, store, "npm", "six", "1.0.0") + pypi := trendingPackage(t, store, "pypi", "six", "six-1.0.tar.gz") + third := trendingPackage(t, store, "npm", "a", "1.0.0") + trendingEvents(t, store, npm, trendingNow.Add(-time.Hour), 4) + trendingEvents(t, store, pypi, trendingNow.Add(-time.Hour), 6) + trendingEvents(t, store, third, trendingNow.Add(-time.Hour), 1) + + got, err := store.GetTrendingPackages(context.Background(), 2) + require.NoError(t, err) + require.Equal(t, []*metadata.TrendingPackage{ + {Registry: "pypi", Name: "six", Recent: 6}, + {Registry: "npm", Name: "six", Recent: 4}, + }, got) +} + +func TestTrendingSurvivesAggregation(t *testing.T) { + store := newTimeSeriesStore(t) + recordDownloads(t, store, 3) + require.NoError(t, store.db.Exec("UPDATE download_events SET downloaded_at = ?", time.Now().Add(-3*time.Hour)).Error) + require.NoError(t, store.AggregateDownloadData(context.Background())) + var raw int64 + require.NoError(t, store.db.Table("download_events").Count(&raw).Error) + require.Zero(t, raw, "events are rolled into hourly rows") + + got, err := store.GetTrendingPackages(context.Background(), 10) + require.NoError(t, err) + require.Len(t, got, 1) + require.Equal(t, int64(3), got[0].Recent) +} + +func TestDailyTimeIndexExists(t *testing.T) { + store := trendingStore(t) + require.True(t, store.db.Migrator().HasIndex(&DownloadStatsDailyModel{}, dailyTimeIndex)) +} diff --git a/pkg/metadata/interface.go b/pkg/metadata/interface.go index 03518eb..5055ed7 100644 --- a/pkg/metadata/interface.go +++ b/pkg/metadata/interface.go @@ -443,3 +443,17 @@ func DedupeVersions(rows []*Package) []*Package { } return out } + +// TrendingPackage is a package's download count over the last 7 days and the 7 days before. +type TrendingPackage struct { + Registry string `json:"registry"` + Name string `json:"name"` + Recent int64 `json:"recent"` + Previous int64 `json:"previous"` +} + +// TrendingSource ranks packages from persisted download history. Backends without +// persisted downloads do not implement it. +type TrendingSource interface { + GetTrendingPackages(ctx context.Context, limit int) ([]*TrendingPackage, error) +}