Skip to content

Commit deff991

Browse files
committed
fix: index listener statistics
1 parent bd45be5 commit deff991

4 files changed

Lines changed: 175 additions & 28 deletions

File tree

‎broadcast/ringbuf_test.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ import (
88
)
99

1010
func TestRingBufferConcurrentReaders(t *testing.T) {
11-
rb := NewRingBuffer(64 * 1024)
12-
1311
const (
1412
numReaders = 100
1513
numFrames = 500
1614
frameSize = 417 // typical MP3 frame at 128kbps
1715
)
16+
rb := NewRingBuffer(numFrames * frameSize)
1817

1918
// Write a frame to get an initial position.
2019
frame := make([]byte, frameSize)

‎handler/statistics.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,11 @@ type stationStatsPayload struct {
9292
func (g *GlobalStatistics) ServeHTTP(w http.ResponseWriter, r *http.Request) {
9393
w.Header().Set("Access-Control-Allow-Origin", "*")
9494

95-
allStats, err := g.StatsDB.AllStats()
95+
stationIDs := make([]string, 0, len(g.Stations))
96+
for id := range g.Stations {
97+
stationIDs = append(stationIDs, id)
98+
}
99+
allStats, err := g.StatsDB.AllStats(stationIDs)
96100
if err != nil {
97101
http.Error(w, "internal error", http.StatusInternalServerError)
98102
return

‎stats/stats.go‎

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,24 @@ func Open(path string) (*DB, error) {
5757
return nil, err
5858
}
5959

60+
// These indexes cover the per-station aggregates used by the public
61+
// statistics endpoints. Without them, every request scans the full history.
62+
const indexes = `
63+
CREATE INDEX IF NOT EXISTS idx_listener_sessions_station_connected_at
64+
ON listener_sessions (station, connected_at, duration_seconds);
65+
66+
CREATE INDEX IF NOT EXISTS idx_listener_sessions_station_country
67+
ON listener_sessions (station, country, country_code, duration_seconds)
68+
WHERE country != '';
69+
70+
CREATE INDEX IF NOT EXISTS idx_listener_sessions_station_city
71+
ON listener_sessions (station, city, country_code, duration_seconds)
72+
WHERE city != '';`
73+
if _, err := db.Exec(indexes); err != nil {
74+
db.Close()
75+
return nil, err
76+
}
77+
6078
return &DB{db: db}, nil
6179
}
6280

@@ -82,11 +100,11 @@ func (d *DB) Record(s Session) error {
82100

83101
// StationStatsResult holds aggregated statistics for a single station.
84102
type StationStatsResult struct {
85-
TotalSessions int64 `json:"total_sessions"`
86-
TotalListenHours float64 `json:"total_listen_hours"`
87-
TopCountries []CountryStats `json:"top_countries"`
88-
TopCities []CityStats `json:"top_cities"`
89-
Daily []DailyStats `json:"daily"`
103+
TotalSessions int64 `json:"total_sessions"`
104+
TotalListenHours float64 `json:"total_listen_hours"`
105+
TopCountries []CountryStats `json:"top_countries"`
106+
TopCities []CityStats `json:"top_cities"`
107+
Daily []DailyStats `json:"daily"`
90108
}
91109

92110
// CountryStats holds aggregated data for a country.
@@ -147,26 +165,8 @@ func (d *DB) StationStats(station string) (*StationStatsResult, error) {
147165
return result, nil
148166
}
149167

150-
// AllStats returns aggregated statistics across all stations, keyed by station ID.
151-
func (d *DB) AllStats() (map[string]*StationStatsResult, error) {
152-
rows, err := d.db.Query(`SELECT DISTINCT station FROM listener_sessions`)
153-
if err != nil {
154-
return nil, err
155-
}
156-
defer rows.Close()
157-
158-
var stationIDs []string
159-
for rows.Next() {
160-
var id string
161-
if err := rows.Scan(&id); err != nil {
162-
return nil, err
163-
}
164-
stationIDs = append(stationIDs, id)
165-
}
166-
if err := rows.Err(); err != nil {
167-
return nil, err
168-
}
169-
168+
// AllStats returns aggregated statistics for stationIDs, keyed by station ID.
169+
func (d *DB) AllStats(stationIDs []string) (map[string]*StationStatsResult, error) {
170170
result := make(map[string]*StationStatsResult, len(stationIDs))
171171
for _, id := range stationIDs {
172172
s, err := d.StationStats(id)

‎stats/stats_test.go‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
package stats
2+
3+
import (
4+
"database/sql"
5+
"path/filepath"
6+
"testing"
7+
"time"
8+
9+
_ "github.com/ncruces/go-sqlite3/driver"
10+
_ "github.com/ncruces/go-sqlite3/embed"
11+
)
12+
13+
func TestOpenCreatesStatisticsIndexes(t *testing.T) {
14+
path := filepath.Join(t.TempDir(), "stats.db")
15+
legacy, err := sql.Open("sqlite3", path)
16+
if err != nil {
17+
t.Fatal(err)
18+
}
19+
_, err = legacy.Exec(`CREATE TABLE listener_sessions (
20+
id INTEGER PRIMARY KEY AUTOINCREMENT,
21+
station TEXT NOT NULL,
22+
country TEXT NOT NULL DEFAULT '',
23+
country_code TEXT NOT NULL DEFAULT '',
24+
city TEXT NOT NULL DEFAULT '',
25+
latitude REAL NOT NULL DEFAULT 0,
26+
longitude REAL NOT NULL DEFAULT 0,
27+
connected_at TEXT NOT NULL,
28+
disconnected_at TEXT NOT NULL,
29+
duration_seconds INTEGER NOT NULL
30+
)`)
31+
if err != nil {
32+
legacy.Close()
33+
t.Fatal(err)
34+
}
35+
if _, err := legacy.Exec(`INSERT INTO listener_sessions (station, connected_at, disconnected_at, duration_seconds) VALUES ('lofi', '2026-01-01T00:00:00Z', '2026-01-01T01:00:00Z', 3600)`); err != nil {
36+
legacy.Close()
37+
t.Fatal(err)
38+
}
39+
if err := legacy.Close(); err != nil {
40+
t.Fatal(err)
41+
}
42+
43+
db, err := Open(path)
44+
if err != nil {
45+
t.Fatal(err)
46+
}
47+
defer db.Close()
48+
49+
rows, err := db.db.Query(`SELECT name FROM sqlite_master WHERE type = 'index' ORDER BY name`)
50+
if err != nil {
51+
t.Fatal(err)
52+
}
53+
defer rows.Close()
54+
55+
want := []string{
56+
"idx_listener_sessions_station_city",
57+
"idx_listener_sessions_station_connected_at",
58+
"idx_listener_sessions_station_country",
59+
}
60+
for _, name := range want {
61+
if !rows.Next() {
62+
t.Fatalf("missing index %q", name)
63+
}
64+
var got string
65+
if err := rows.Scan(&got); err != nil {
66+
t.Fatal(err)
67+
}
68+
if got != name {
69+
t.Errorf("index = %q, want %q", got, name)
70+
}
71+
}
72+
if rows.Next() {
73+
t.Error("found unexpected index")
74+
}
75+
if err := rows.Err(); err != nil {
76+
t.Fatal(err)
77+
}
78+
var count int
79+
if err := db.db.QueryRow(`SELECT COUNT(*) FROM listener_sessions`).Scan(&count); err != nil {
80+
t.Fatal(err)
81+
}
82+
if count != 1 {
83+
t.Errorf("session count = %d, want 1", count)
84+
}
85+
}
86+
87+
func TestStationStats(t *testing.T) {
88+
db, err := Open(filepath.Join(t.TempDir(), "stats.db"))
89+
if err != nil {
90+
t.Fatal(err)
91+
}
92+
defer db.Close()
93+
94+
now := time.Now().UTC()
95+
for _, session := range []Session{
96+
{
97+
Station: "lofi", Country: "Norway", CountryCode: "NO", City: "Oslo",
98+
ConnectedAt: now.Add(-time.Hour), DisconnectedAt: now, DurationSeconds: 3600,
99+
},
100+
{
101+
Station: "lofi", Country: "Norway", CountryCode: "NO", City: "Oslo",
102+
ConnectedAt: now.Add(-2 * time.Hour), DisconnectedAt: now.Add(-time.Hour), DurationSeconds: 1800,
103+
},
104+
{
105+
Station: "lofi", ConnectedAt: now.Add(-48 * time.Hour), DisconnectedAt: now.Add(-47 * time.Hour), DurationSeconds: 600,
106+
},
107+
{
108+
Station: "old", Country: "Sweden", CountryCode: "SE", City: "Stockholm",
109+
ConnectedAt: now.Add(-time.Hour), DisconnectedAt: now, DurationSeconds: 3600,
110+
},
111+
} {
112+
if err := db.Record(session); err != nil {
113+
t.Fatal(err)
114+
}
115+
}
116+
117+
got, err := db.StationStats("lofi")
118+
if err != nil {
119+
t.Fatal(err)
120+
}
121+
if got.TotalSessions != 3 {
122+
t.Errorf("TotalSessions = %d, want 3", got.TotalSessions)
123+
}
124+
if got.TotalListenHours != 1.7 {
125+
t.Errorf("TotalListenHours = %v, want 1.7", got.TotalListenHours)
126+
}
127+
if len(got.TopCountries) != 1 || got.TopCountries[0].CountryCode != "NO" || got.TopCountries[0].Sessions != 2 {
128+
t.Errorf("TopCountries = %#v, want Norway with 2 sessions", got.TopCountries)
129+
}
130+
if len(got.TopCities) != 1 || got.TopCities[0].City != "Oslo" || got.TopCities[0].Sessions != 2 {
131+
t.Errorf("TopCities = %#v, want Oslo with 2 sessions", got.TopCities)
132+
}
133+
if len(got.Daily) != 2 {
134+
t.Errorf("Daily = %#v, want two days", got.Daily)
135+
}
136+
137+
all, err := db.AllStats([]string{"lofi"})
138+
if err != nil {
139+
t.Fatal(err)
140+
}
141+
if len(all) != 1 || all["lofi"].TotalSessions != 3 {
142+
t.Errorf("AllStats() = %#v, want lofi only", all)
143+
}
144+
}

0 commit comments

Comments
 (0)