mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(stats): upsert hourly and daily stats on SQLite as PostgreSQL does
This commit is contained in:
@@ -139,7 +139,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
|||||||
// SQLite: Use strftime for time bucketing
|
// SQLite: Use strftime for time bucketing
|
||||||
// Note: SQLite doesn't support UPSERT as elegantly, need to handle separately
|
// Note: SQLite doesn't support UPSERT as elegantly, need to handle separately
|
||||||
aggregateSQL = `
|
aggregateSQL = `
|
||||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||||
SELECT
|
SELECT
|
||||||
de.registry_id,
|
de.registry_id,
|
||||||
de.package_id,
|
de.package_id,
|
||||||
@@ -152,6 +152,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
|||||||
FROM download_events de
|
FROM download_events de
|
||||||
WHERE de.downloaded_at < ?
|
WHERE de.downloaded_at < ?
|
||||||
GROUP BY de.registry_id, de.package_id, time_bucket
|
GROUP BY de.registry_id, de.package_id, time_bucket
|
||||||
|
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||||
|
DO UPDATE SET
|
||||||
|
download_count = download_stats_hourly.download_count + excluded.download_count,
|
||||||
|
unique_ips = MAX(download_stats_hourly.unique_ips, excluded.unique_ips),
|
||||||
|
auth_downloads = download_stats_hourly.auth_downloads + excluded.auth_downloads,
|
||||||
|
updated_at = datetime('now')
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,7 +227,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
|||||||
default:
|
default:
|
||||||
// SQLite
|
// SQLite
|
||||||
registryAggSQL = `
|
registryAggSQL = `
|
||||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||||
SELECT
|
SELECT
|
||||||
registry_id,
|
registry_id,
|
||||||
NULL as package_id,
|
NULL as package_id,
|
||||||
@@ -234,6 +240,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
|||||||
FROM download_stats_hourly
|
FROM download_stats_hourly
|
||||||
WHERE package_id IS NOT NULL
|
WHERE package_id IS NOT NULL
|
||||||
GROUP BY registry_id, time_bucket
|
GROUP BY registry_id, time_bucket
|
||||||
|
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||||
|
DO UPDATE SET
|
||||||
|
download_count = excluded.download_count,
|
||||||
|
unique_ips = excluded.unique_ips,
|
||||||
|
auth_downloads = excluded.auth_downloads,
|
||||||
|
updated_at = datetime('now')
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,7 +329,7 @@ func (w *AggregationWorker) AggregateDaily() error {
|
|||||||
|
|
||||||
default: // SQLite
|
default: // SQLite
|
||||||
aggregateSQL = `
|
aggregateSQL = `
|
||||||
INSERT OR REPLACE INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
INSERT INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||||
SELECT
|
SELECT
|
||||||
registry_id,
|
registry_id,
|
||||||
package_id,
|
package_id,
|
||||||
@@ -331,6 +343,12 @@ func (w *AggregationWorker) AggregateDaily() error {
|
|||||||
FROM download_stats_hourly
|
FROM download_stats_hourly
|
||||||
WHERE time_bucket >= ? AND time_bucket < ?
|
WHERE time_bucket >= ? AND time_bucket < ?
|
||||||
GROUP BY registry_id, package_id, date(time_bucket)
|
GROUP BY registry_id, package_id, date(time_bucket)
|
||||||
|
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||||
|
DO UPDATE SET
|
||||||
|
download_count = excluded.download_count,
|
||||||
|
unique_ips = excluded.unique_ips,
|
||||||
|
auth_downloads = excluded.auth_downloads,
|
||||||
|
updated_at = datetime('now')
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -103,6 +103,12 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.Driver == "sqlite" {
|
||||||
|
if err := ensureSQLiteStatsIndexes(db); err != nil {
|
||||||
|
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to create stats indexes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err := dropEmptyTable(db, legacyDownloadEventsTable); err != nil {
|
if err := dropEmptyTable(db, legacyDownloadEventsTable); err != nil {
|
||||||
log.Warn().Err(err).Str("table", legacyDownloadEventsTable).Msg("Failed to drop empty legacy table")
|
log.Warn().Err(err).Str("table", legacyDownloadEventsTable).Msg("Failed to drop empty legacy table")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package gormstore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ensureSQLiteStatsIndexes gives SQLite the unique indexes PostgreSQL gets from
|
||||||
|
// the partition manager, merging duplicate rows written before they existed.
|
||||||
|
func ensureSQLiteStatsIndexes(db *gorm.DB) error {
|
||||||
|
var present int64
|
||||||
|
if err := db.Raw("SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name IN ('idx_stats_hourly_upsert', 'idx_stats_daily_upsert')").Scan(&present).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if present == int64(len(statsUpsertIndexes)) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
// Hourly package rows come from passes over disjoint events, so they add up.
|
||||||
|
// Registry rows (NULL package) and daily rows are derived and recomputed by the
|
||||||
|
// next pass; one copy of each is enough.
|
||||||
|
const group = "d.registry_id = download_stats_hourly.registry_id AND d.package_id = download_stats_hourly.package_id AND d.time_bucket = download_stats_hourly.time_bucket"
|
||||||
|
merge := `UPDATE download_stats_hourly SET
|
||||||
|
download_count = (SELECT SUM(d.download_count) FROM download_stats_hourly d WHERE ` + group + `),
|
||||||
|
auth_downloads = (SELECT SUM(d.auth_downloads) FROM download_stats_hourly d WHERE ` + group + `),
|
||||||
|
unique_ips = (SELECT MAX(d.unique_ips) FROM download_stats_hourly d WHERE ` + group + `)
|
||||||
|
WHERE package_id IS NOT NULL AND id = (SELECT MIN(d.id) FROM download_stats_hourly d WHERE ` + group + `)`
|
||||||
|
if err := tx.Exec(merge).Error; err != nil {
|
||||||
|
return fmt.Errorf("merge duplicate hourly stats rows: %w", err)
|
||||||
|
}
|
||||||
|
for _, table := range []string{"download_stats_hourly", "download_stats_daily"} {
|
||||||
|
dedupe := fmt.Sprintf("DELETE FROM %[1]s WHERE id NOT IN (SELECT MIN(id) FROM %[1]s GROUP BY registry_id, COALESCE(package_id, 0), time_bucket)", table)
|
||||||
|
if err := tx.Exec(dedupe).Error; err != nil {
|
||||||
|
return fmt.Errorf("delete duplicate %s rows: %w", table, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, stmt := range statsUpsertIndexes {
|
||||||
|
if err := tx.Exec(stmt).Error; err != nil {
|
||||||
|
return fmt.Errorf("create stats upsert index: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
//go:build pgintegration
|
||||||
|
|
||||||
|
package gormstore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The same scenario the SQLite test runs: both dialects must report the same totals.
|
||||||
|
func TestPostgresHourlyTotalsMatchSQLite(t *testing.T) {
|
||||||
|
store, _ := newPostgresStore(t)
|
||||||
|
require.Equal(t, wantHourlyScenario(), runHourlyScenario(t, store))
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package gormstore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// statsScenario drives the same hourly passes on any dialect and returns the
|
||||||
|
// observable totals, so SQLite and PostgreSQL can be held to one expectation.
|
||||||
|
type statsScenario struct {
|
||||||
|
packageRows, registryRows int64
|
||||||
|
packageCount, registryCnt int64
|
||||||
|
chartTotal int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func runHourlyScenario(t *testing.T, store *GORMStoreV2) statsScenario {
|
||||||
|
t.Helper()
|
||||||
|
hour := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
|
||||||
|
|
||||||
|
seedEventsAt(t, store, hour.Add(10*time.Minute), hour.Add(20*time.Minute))
|
||||||
|
tick(t, store, hour.Add(2*time.Hour), false)
|
||||||
|
tick(t, store, hour.Add(2*time.Hour+5*time.Minute), false) // nothing new: must change nothing
|
||||||
|
|
||||||
|
seedEventsAt(t, store, hour.Add(50*time.Minute)) // a late download for the same bucket
|
||||||
|
tick(t, store, hour.Add(3*time.Hour), false)
|
||||||
|
|
||||||
|
var s statsScenario
|
||||||
|
db := store.db.Table("download_stats_hourly")
|
||||||
|
require.NoError(t, db.Where("package_id IS NOT NULL").Count(&s.packageRows).Error)
|
||||||
|
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NULL").Count(&s.registryRows).Error)
|
||||||
|
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NOT NULL").Select("COALESCE(SUM(download_count),0)").Scan(&s.packageCount).Error)
|
||||||
|
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NULL").Select("COALESCE(SUM(download_count),0)").Scan(&s.registryCnt).Error)
|
||||||
|
s.chartTotal = totalAt(t, store, hour.Add(3*time.Hour+10*time.Minute), "24hour")
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func wantHourlyScenario() statsScenario {
|
||||||
|
return statsScenario{packageRows: 1, registryRows: 1, packageCount: 3, registryCnt: 3, chartTotal: 3}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SQLite carried no unique index, so INSERT OR REPLACE inserted a new row every pass.
|
||||||
|
func TestSQLiteHourlyTotalsMatchPostgresSemantics(t *testing.T) {
|
||||||
|
store := newTimeSeriesStore(t)
|
||||||
|
require.Equal(t, wantHourlyScenario(), runHourlyScenario(t, store))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSQLiteDailyRollupIsIdempotent(t *testing.T) {
|
||||||
|
store := newTimeSeriesStore(t)
|
||||||
|
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||||
|
seedEventsAt(t, store, day.Add(5*time.Hour), day.Add(6*time.Hour))
|
||||||
|
tick(t, store, day.Add(24*time.Hour+30*time.Minute), false)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
store.aggregationWorker.now = func() time.Time { return day.Add(25 * time.Hour) }
|
||||||
|
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||||
|
}
|
||||||
|
|
||||||
|
var rows, total int64
|
||||||
|
require.NoError(t, store.db.Table("download_stats_daily").Where("package_id IS NOT NULL").Count(&rows).Error)
|
||||||
|
require.NoError(t, store.db.Table("download_stats_daily").Where("package_id IS NOT NULL").Select("COALESCE(SUM(download_count),0)").Scan(&total).Error)
|
||||||
|
require.EqualValues(t, 1, rows)
|
||||||
|
require.EqualValues(t, 2, total)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Databases written by the old code hold duplicate rows; the migration merges them.
|
||||||
|
func TestSQLiteStatsDedupeMigration(t *testing.T) {
|
||||||
|
store := newTimeSeriesStore(t)
|
||||||
|
for _, name := range []string{"idx_stats_hourly_upsert", "idx_stats_daily_upsert"} {
|
||||||
|
require.NoError(t, store.db.Exec("DROP INDEX IF EXISTS "+name).Error)
|
||||||
|
}
|
||||||
|
bucket := "2026-03-10 05:00:00"
|
||||||
|
insert := func(table string, pkg any, n int) {
|
||||||
|
require.NoError(t, store.db.Exec(
|
||||||
|
"INSERT INTO "+table+" (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at) VALUES (1, ?, ?, ?, 1, 0, datetime('now'), datetime('now'))",
|
||||||
|
pkg, bucket, n).Error)
|
||||||
|
}
|
||||||
|
// Package rows from separate passes hold disjoint events: they add up.
|
||||||
|
insert("download_stats_hourly", 7, 2)
|
||||||
|
insert("download_stats_hourly", 7, 3)
|
||||||
|
// Registry rows are derived copies: one survives.
|
||||||
|
insert("download_stats_hourly", nil, 5)
|
||||||
|
insert("download_stats_hourly", nil, 5)
|
||||||
|
insert("download_stats_daily", nil, 5)
|
||||||
|
insert("download_stats_daily", nil, 5)
|
||||||
|
|
||||||
|
require.NoError(t, ensureSQLiteStatsIndexes(store.db))
|
||||||
|
|
||||||
|
count := func(table, where string) (rows, total int64) {
|
||||||
|
require.NoError(t, store.db.Table(table).Where(where).Count(&rows).Error)
|
||||||
|
require.NoError(t, store.db.Table(table).Where(where).Select("COALESCE(SUM(download_count),0)").Scan(&total).Error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, total := count("download_stats_hourly", "package_id = 7")
|
||||||
|
require.EqualValues(t, 1, rows)
|
||||||
|
require.EqualValues(t, 5, total)
|
||||||
|
rows, total = count("download_stats_hourly", "package_id IS NULL")
|
||||||
|
require.EqualValues(t, 1, rows)
|
||||||
|
require.EqualValues(t, 5, total)
|
||||||
|
rows, _ = count("download_stats_daily", "package_id IS NULL")
|
||||||
|
require.EqualValues(t, 1, rows)
|
||||||
|
|
||||||
|
require.Error(t, store.db.Exec(
|
||||||
|
"INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at) VALUES (1, NULL, ?, 1, 1, 0, datetime('now'), datetime('now'))", bucket).Error,
|
||||||
|
"unique index must reject a duplicate registry row")
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user