diff --git a/pkg/app/timeseries_test.go b/pkg/app/timeseries_test.go new file mode 100644 index 0000000..6cd82bf --- /dev/null +++ b/pkg/app/timeseries_test.go @@ -0,0 +1,52 @@ +package app + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/lukaszraczylo/gohoarder/pkg/config" +) + +func TestTimeSeriesCountsCacheHitDownloads(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/left-pad/-/left-pad-1.3.0.tgz" { + _, _ = w.Write([]byte("TARBALL")) + return + } + http.NotFound(w, r) + })) + t.Cleanup(upstream.Close) + a := newTestApp(t, func(c *config.Config) { c.Handlers.NPM.UpstreamRegistry = upstream.URL }) + + // The npm handler tracks every tarball request, the first miss included. + const downloads = 4 + for i := 0; i < downloads; i++ { + if code, _, body := doRequest(t, a, "/npm/left-pad/-/left-pad-1.3.0.tgz", nil); code != http.StatusOK { + t.Fatalf("download %d: status %d, body %q", i, code, body) + } + } + + for _, period := range []string{"1h", "1day", "7day", "30day"} { + code, _, body := doRequest(t, a, "/api/stats/timeseries?period="+period, nil) + if code != http.StatusOK { + t.Fatalf("%s: status %d, body %q", period, code, body) + } + var ts struct { + DataPoints []struct { + Value int64 `json:"value"` + } `json:"data_points"` + } + if err := json.Unmarshal([]byte(body), &ts); err != nil { + t.Fatalf("%s: decode %q: %v", period, body, err) + } + var total int64 + for _, p := range ts.DataPoints { + total += p.Value + } + if total != downloads { + t.Errorf("%s: timeseries total = %d, want %d (body %s)", period, total, downloads, body) + } + } +} diff --git a/pkg/metadata/gormstore/gormstore_v2.go b/pkg/metadata/gormstore/gormstore_v2.go index b9a8678..f067832 100644 --- a/pkg/metadata/gormstore/gormstore_v2.go +++ b/pkg/metadata/gormstore/gormstore_v2.go @@ -652,110 +652,110 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg DataPoints: make([]*metadata.TimeSeriesDataPoint, 0), } - // Determine which table to query based on period - var tableName string - var since time.Time - var bucketDuration time.Duration - + now := time.Now().UTC() + var span, bucketDuration time.Duration + daily := false switch period { case "1h": - tableName = "download_stats_hourly" - since = time.Now().Add(-1 * time.Hour).Truncate(time.Hour) - bucketDuration = time.Hour - case "1day": - tableName = "download_stats_hourly" - since = time.Now().Add(-24 * time.Hour).Truncate(time.Hour) - bucketDuration = time.Hour + span, bucketDuration = time.Hour, time.Hour case "7day": - tableName = "download_stats_daily" - since = time.Now().Add(-7 * 24 * time.Hour).Truncate(24 * time.Hour) - bucketDuration = 24 * time.Hour + span, bucketDuration, daily = 7*24*time.Hour, 24*time.Hour, true case "30day": - tableName = "download_stats_daily" - since = time.Now().Add(-30 * 24 * time.Hour).Truncate(24 * time.Hour) - bucketDuration = 24 * time.Hour + span, bucketDuration, daily = 30*24*time.Hour, 24*time.Hour, true default: - tableName = "download_stats_hourly" - since = time.Now().Add(-24 * time.Hour).Truncate(time.Hour) - bucketDuration = time.Hour + span, bucketDuration = 24*time.Hour, time.Hour } + since := now.Add(-span).Truncate(bucketDuration) - now := time.Now() - - // Try to get registry-level aggregate stats first - query := s.db.WithContext(ctx). - Table(tableName). - Select("time_bucket as timestamp, download_count as value"). - Where("time_bucket >= ? AND time_bucket <= ?", since, now) - - // Filter by registry if specified + var registryID int32 if registry != "" { - registryID, err := s.getRegistryID(registry) + id, err := s.getRegistryID(registry) if err != nil { return nil, err } - query = query.Where("registry_id = ? AND package_id IS NULL", registryID) - } else { - query = query.Where("package_id IS NULL") + registryID = id } - query = query.Order("time_bucket ASC") + // Aggregation lags behind: the current hour sits in download_events and + // completed hours not yet rolled into a day sit in download_stats_hourly, + // so all three sources are merged. Aggregation deletes the events it + // counts, so no download is counted twice. + counts := make(map[int64]int64) + add := func(t time.Time, v int64) { counts[t.UTC().Truncate(bucketDuration).Unix()] += v } - type Result struct { - Timestamp time.Time - Value int64 + hourly, err := s.aggregateRows(ctx, "download_stats_hourly", since, now, registryID) + if err != nil { + return nil, err + } + for _, r := range hourly { + add(r.Timestamp, r.Value) } - var results []Result - if err := query.Scan(&results).Error; err != nil { - return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to get time series stats") + var events []time.Time + eventQuery := s.db.WithContext(ctx).Table("download_events").Where("downloaded_at >= ?", since) + if registryID != 0 { + eventQuery = eventQuery.Where("registry_id = ?", registryID) + } + if err := eventQuery.Pluck("downloaded_at", &events).Error; err != nil { + return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to get recent download events") + } + for _, t := range events { + add(t, 1) } - // If no aggregate data found, try summing package-level stats - if len(results) == 0 { - sumQuery := s.db.WithContext(ctx). - Table(tableName). - Select("time_bucket as timestamp, SUM(download_count) as value"). - Where("time_bucket >= ? AND time_bucket <= ?", since, now) - - if registry != "" { - registryID, err := s.getRegistryID(registry) - if err != nil { - return nil, err - } - sumQuery = sumQuery.Where("registry_id = ? AND package_id IS NOT NULL", registryID) - } else { - sumQuery = sumQuery.Where("package_id IS NOT NULL") + if daily { + // A completed day's rollup is authoritative over its leftover hourly rows. + rollups, err := s.aggregateRows(ctx, "download_stats_daily", since, now, registryID) + if err != nil { + return nil, err } - - sumQuery = sumQuery.Group("time_bucket").Order("time_bucket ASC") - - if err := sumQuery.Scan(&results).Error; err != nil { - return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to get time series stats from package data") + for _, r := range rollups { + counts[r.Timestamp.UTC().Truncate(bucketDuration).Unix()] = r.Value } } - // Create a map of existing data points - dataMap := make(map[time.Time]int64) - for _, r := range results { - dataMap[r.Timestamp] = r.Value - } - - // Generate continuous time series with 0 values for missing periods - for t := since; t.Before(now) || t.Equal(now); t = t.Add(bucketDuration) { - value := int64(0) - if v, exists := dataMap[t]; exists { - value = v - } + for t := since; !t.After(now); t = t.Add(bucketDuration) { stats.DataPoints = append(stats.DataPoints, &metadata.TimeSeriesDataPoint{ Timestamp: t, - Value: value, + Value: counts[t.Unix()], }) } return stats, nil } +type timeSeriesRow struct { + Timestamp time.Time + Value int64 +} + +// aggregateRows reads registry-level rows (package_id NULL), falling back to +// summing package-level rows when none exist. registryID 0 means all registries. +func (s *GORMStoreV2) aggregateRows(ctx context.Context, table string, since, until time.Time, registryID int32) ([]timeSeriesRow, error) { + var rows []timeSeriesRow + for _, packageLevel := range []bool{false, true} { + cond := "package_id IS NULL" + if packageLevel { + cond = "package_id IS NOT NULL" + } + query := s.db.WithContext(ctx). + Table(table). + Select("time_bucket as timestamp, SUM(download_count) as value"). + Where("time_bucket >= ? AND time_bucket <= ?", since, until). + Where(cond) + if registryID != 0 { + query = query.Where("registry_id = ?", registryID) + } + if err := query.Group("time_bucket").Order("time_bucket ASC").Scan(&rows).Error; err != nil { + return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to get time series stats") + } + if len(rows) > 0 { + return rows, nil + } + } + return rows, nil +} + // AggregateDownloadData aggregates raw download events into hourly/daily stats func (s *GORMStoreV2) AggregateDownloadData(ctx context.Context) error { if s.aggregationWorker == nil { diff --git a/pkg/metadata/gormstore/timeseries_test.go b/pkg/metadata/gormstore/timeseries_test.go new file mode 100644 index 0000000..11a5901 --- /dev/null +++ b/pkg/metadata/gormstore/timeseries_test.go @@ -0,0 +1,85 @@ +package gormstore + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/metadata" + "github.com/stretchr/testify/require" +) + +func sumPoints(ts *metadata.TimeSeriesStats) int64 { + var total int64 + for _, p := range ts.DataPoints { + total += p.Value + } + return total +} + +func newTimeSeriesStore(t *testing.T) *GORMStoreV2 { + t.Helper() + store, err := NewV2(Config{ + Driver: "sqlite", + DSN: fmt.Sprintf("file:ts_%d?mode=memory&cache=shared", time.Now().UnixNano()), + MaxOpenConns: 1, + MaxIdleConns: 1, + LogLevel: "silent", + }) + require.NoError(t, err) + return store +} + +func recordDownloads(t *testing.T, store *GORMStoreV2, n int) { + t.Helper() + ctx := context.Background() + now := time.Now() + require.NoError(t, store.SavePackage(ctx, &metadata.Package{ + Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0", + Size: 10, CachedAt: now, LastAccessed: now, + })) + for i := 0; i < n; i++ { + require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "left-pad", "1.3.0")) + } +} + +func TestTimeSeriesIncludesFreshDownloads(t *testing.T) { + for _, period := range []string{"1h", "1day", "7day", "30day"} { + t.Run(period+"/before aggregation", func(t *testing.T) { + store := newTimeSeriesStore(t) + recordDownloads(t, store, 3) + ts, err := store.GetTimeSeriesStats(context.Background(), period, "") + require.NoError(t, err) + require.Equal(t, int64(3), sumPoints(ts)) + }) + t.Run(period+"/after aggregation", func(t *testing.T) { + store := newTimeSeriesStore(t) + recordDownloads(t, store, 3) + require.NoError(t, store.AggregateDownloadData(context.Background())) + require.NoError(t, store.AggregateDownloadData(context.Background())) + ts, err := store.GetTimeSeriesStats(context.Background(), period, "npm") + require.NoError(t, err) + require.Equal(t, int64(3), sumPoints(ts)) + }) + } +} + +func TestTimeSeriesReadsAggregatedBuckets(t *testing.T) { + ctx := context.Background() + store := newTimeSeriesStore(t) + recordDownloads(t, store, 2) + // Move the events into completed hours so the worker aggregates them. + require.NoError(t, store.db.Exec("UPDATE download_events SET downloaded_at = ?", time.Now().UTC().Add(-3*time.Hour)).Error) + require.NoError(t, store.AggregateDownloadData(ctx)) + + var raw int64 + require.NoError(t, store.db.Table("download_events").Count(&raw).Error) + require.Zero(t, raw, "aggregation must consume the events it counted") + + for _, period := range []string{"1day", "7day"} { + ts, err := store.GetTimeSeriesStats(ctx, period, "") + require.NoError(t, err) + require.Equal(t, int64(2), sumPoints(ts), period) + } +}