mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
The dashboard waited seconds for /api/packages and /api/stats. Both handlers ran queries per package, so the cost grew with the cache. Baseline, measured live through a port-forward (median of 5): - /api/packages: 3033 ms, 594 items, limit ignored - /api/packages?limit=50&offset=0: 2813 ms - /api/stats: 3813 ms - /api/stats/timeseries?period=1day: 12 ms Baseline queries per request, counted on SQLite with 20 and 120 rows: - /api/packages: 141 and 841 queries (7 per package) - /api/stats: 103 and 603 queries (5 per package) Both handlers now run a constant number of queries: 4 for the full list, 6 for a page, 6 for stats. The query-count tests fail on the old code. - /api/packages pages (registry, name) groups with page, page_size, registry, q, sort and order, and returns total_groups. Without page and page_size it returns every package, so old clients keep working. - A batched scan lookup replaces the per-package GetScanResult and CheckVulnerabilities calls. ScanDecisions returns the same verdicts as CheckVulnerabilities, proven by a policy and bypass matrix test. - The silent 1000-row cap is gone from the list and the Go delete. - /api/stats sums per registry with GROUP BY and judges blocked packages in one batch. - Migration 202611240001 adds scan_results (package_id, scanned_at) on SQLite, PostgreSQL and MySQL. The existing (registry_id, name, version) index already serves the group lookups.
43 lines
1.2 KiB
Go
43 lines
1.2 KiB
Go
// Package dbcount counts the SQL statements a GORM handle runs, for query-count tests.
|
|
package dbcount
|
|
|
|
import (
|
|
"context"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
// Counter holds the number of statements seen since the last Reset.
|
|
type Counter struct {
|
|
n atomic.Int64
|
|
}
|
|
|
|
// Attach returns a session of db that counts every statement it executes. It
|
|
// swaps the logger instead of registering callbacks, because callback
|
|
// registration is not safe while other goroutines already run queries.
|
|
// GORM runs a subquery as a dry run with a discarded logger, so subqueries do not count.
|
|
func Attach(db *gorm.DB) (*gorm.DB, *Counter) {
|
|
c := &Counter{}
|
|
return db.Session(&gorm.Session{Logger: &countingLogger{Interface: logger.Discard, c: c}}), c
|
|
}
|
|
|
|
// Reset zeroes the count.
|
|
func (c *Counter) Reset() { c.n.Store(0) }
|
|
|
|
// Count returns the statements counted since the last Reset.
|
|
func (c *Counter) Count() int { return int(c.n.Load()) }
|
|
|
|
type countingLogger struct {
|
|
logger.Interface
|
|
c *Counter
|
|
}
|
|
|
|
func (l *countingLogger) LogMode(logger.LogLevel) logger.Interface { return l }
|
|
|
|
func (l *countingLogger) Trace(context.Context, time.Time, func() (string, int64), error) {
|
|
l.c.n.Add(1)
|
|
}
|