285 lines
7.7 KiB
Go
285 lines
7.7 KiB
Go
package history
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
_ "modernc.org/sqlite"
|
|
|
|
"git.gsdistance.org/tyuXX/RUD/internal/store"
|
|
)
|
|
|
|
// hourLayout is the UTC hour-bucket key format used in hourly_stats.
|
|
const hourLayout = "2006-01-02T15:04:05Z"
|
|
|
|
const statsSchema = `
|
|
CREATE TABLE IF NOT EXISTS hourly_stats (
|
|
monitor_id TEXT NOT NULL,
|
|
hour TEXT NOT NULL,
|
|
checks INTEGER NOT NULL DEFAULT 0,
|
|
up INTEGER NOT NULL DEFAULT 0,
|
|
degraded INTEGER NOT NULL DEFAULT 0,
|
|
down INTEGER NOT NULL DEFAULT 0,
|
|
sum_latency_ms REAL NOT NULL DEFAULT 0,
|
|
min_latency_ms REAL,
|
|
max_latency_ms REAL,
|
|
PRIMARY KEY (monitor_id, hour)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_hourly_stats_hour ON hourly_stats(hour);
|
|
`
|
|
|
|
// HourlyStat is an aggregate bucket of check results for one monitor and hour.
|
|
type HourlyStat struct {
|
|
Hour time.Time `json:"hour"`
|
|
Checks int `json:"checks"`
|
|
Up int `json:"up"`
|
|
Degraded int `json:"degraded"`
|
|
Down int `json:"down"`
|
|
AvgLatencyMs float64 `json:"avg_latency_ms"`
|
|
MinLatencyMs float64 `json:"min_latency_ms"`
|
|
MaxLatencyMs float64 `json:"max_latency_ms"`
|
|
}
|
|
|
|
// DailyStat is a per-day rollup of HourlyStat rows for one monitor.
|
|
type DailyStat struct {
|
|
Date string `json:"date"` // YYYY-MM-DD (UTC)
|
|
Checks int `json:"checks"`
|
|
Up int `json:"up"`
|
|
Degraded int `json:"degraded"`
|
|
Down int `json:"down"`
|
|
UptimePct float64 `json:"uptime_pct"`
|
|
AvgLatencyMs float64 `json:"avg_latency_ms"`
|
|
}
|
|
|
|
// StatsDB stores aggregated per-hour check statistics in SQLite and prunes
|
|
// rows older than the configured retention window.
|
|
type StatsDB struct {
|
|
db *sql.DB
|
|
retention time.Duration
|
|
mu sync.Mutex
|
|
lastPrune time.Time
|
|
}
|
|
|
|
// NewStatsDB opens (creating if needed) the SQLite database at path and
|
|
// applies the schema. retentionDays <= 0 disables pruning.
|
|
func NewStatsDB(path string, retentionDays int) (*StatsDB, error) {
|
|
if path == "" {
|
|
return nil, fmt.Errorf("stats db path is empty")
|
|
}
|
|
db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open stats db %s: %w", path, err)
|
|
}
|
|
if _, err := db.Exec(statsSchema); err != nil {
|
|
db.Close()
|
|
return nil, fmt.Errorf("init stats db schema: %w", err)
|
|
}
|
|
s := &StatsDB{db: db}
|
|
if retentionDays > 0 {
|
|
s.retention = time.Duration(retentionDays) * 24 * time.Hour
|
|
}
|
|
if err := s.prune(time.Now()); err != nil {
|
|
db.Close()
|
|
return nil, err
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
// Close closes the underlying database handle.
|
|
func (s *StatsDB) Close() error {
|
|
return s.db.Close()
|
|
}
|
|
|
|
// Record aggregates one check result into its UTC hour bucket.
|
|
func (s *StatsDB) Record(monitorID string, res store.CheckResult) error {
|
|
ts := res.Timestamp
|
|
if ts.IsZero() {
|
|
ts = time.Now().UTC()
|
|
}
|
|
ts = ts.UTC()
|
|
hour := ts.Truncate(time.Hour).Format(hourLayout)
|
|
|
|
stateCol := "down"
|
|
switch res.State {
|
|
case store.StateUp:
|
|
stateCol = "up"
|
|
case store.StateDegraded:
|
|
stateCol = "degraded"
|
|
}
|
|
|
|
// Sum latency only for non-negative measurements; min/max likewise.
|
|
lat := res.LatencyMs
|
|
hasLat := lat >= 0
|
|
sumLat := 0.0
|
|
if hasLat {
|
|
sumLat = lat
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
// Opportunistic prune at most once per hour.
|
|
if s.retention > 0 && time.Since(s.lastPrune) >= time.Hour {
|
|
_ = s.pruneLocked(time.Now())
|
|
}
|
|
|
|
_, err := s.db.Exec(`
|
|
INSERT INTO hourly_stats (monitor_id, hour, checks, up, degraded, down, sum_latency_ms, min_latency_ms, max_latency_ms)
|
|
VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(monitor_id, hour) DO UPDATE SET
|
|
checks = checks + 1,
|
|
up = up + excluded.up,
|
|
degraded = degraded + excluded.degraded,
|
|
down = down + excluded.down,
|
|
sum_latency_ms = sum_latency_ms + excluded.sum_latency_ms,
|
|
min_latency_ms = MIN(COALESCE(min_latency_ms, excluded.min_latency_ms), COALESCE(excluded.min_latency_ms, min_latency_ms)),
|
|
max_latency_ms = MAX(COALESCE(max_latency_ms, excluded.max_latency_ms), COALESCE(excluded.max_latency_ms, max_latency_ms))`,
|
|
monitorID, hour,
|
|
boolInt(stateCol == "up"), boolInt(stateCol == "degraded"), boolInt(stateCol == "down"),
|
|
sumLat, nullIf(!hasLat, lat), nullIf(!hasLat, lat),
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (s *StatsDB) prune(now time.Time) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.pruneLocked(now)
|
|
}
|
|
|
|
func (s *StatsDB) pruneLocked(now time.Time) error {
|
|
if s.retention <= 0 {
|
|
s.lastPrune = now
|
|
return nil
|
|
}
|
|
cutoff := now.UTC().Add(-s.retention).Format(hourLayout)
|
|
if _, err := s.db.Exec(`DELETE FROM hourly_stats WHERE hour < ?`, cutoff); err != nil {
|
|
return fmt.Errorf("prune stats db: %w", err)
|
|
}
|
|
s.lastPrune = now
|
|
return nil
|
|
}
|
|
|
|
// HourlyStats returns aggregate buckets for monitorID covering the last hours
|
|
// hours, oldest first.
|
|
func (s *StatsDB) HourlyStats(monitorID string, hours int) ([]HourlyStat, error) {
|
|
if hours <= 0 {
|
|
hours = 24
|
|
}
|
|
if hours > 24*366 {
|
|
hours = 24 * 366
|
|
}
|
|
cutoff := time.Now().UTC().Add(-time.Duration(hours) * time.Hour).Format(hourLayout)
|
|
rows, err := s.db.Query(`
|
|
SELECT hour, checks, up, degraded, down, sum_latency_ms, min_latency_ms, max_latency_ms
|
|
FROM hourly_stats
|
|
WHERE monitor_id = ? AND hour >= ?
|
|
ORDER BY hour`, monitorID, cutoff)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
out := make([]HourlyStat, 0)
|
|
for rows.Next() {
|
|
var st HourlyStat
|
|
var hourStr string
|
|
var sumLat float64
|
|
var minLat, maxLat sql.NullFloat64
|
|
if err := rows.Scan(&hourStr, &st.Checks, &st.Up, &st.Degraded, &st.Down,
|
|
&sumLat, &minLat, &maxLat); err != nil {
|
|
return nil, err
|
|
}
|
|
if t, err := time.Parse(hourLayout, hourStr); err == nil {
|
|
st.Hour = t
|
|
}
|
|
if st.Checks > 0 {
|
|
st.AvgLatencyMs = sumLat / float64(st.Checks)
|
|
}
|
|
if minLat.Valid {
|
|
st.MinLatencyMs = minLat.Float64
|
|
}
|
|
if maxLat.Valid {
|
|
st.MaxLatencyMs = maxLat.Float64
|
|
}
|
|
out = append(out, st)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// DailyStats returns per-day rollups (UTC dates) for monitorID covering the
|
|
// last days days, oldest first.
|
|
func (s *StatsDB) DailyStats(monitorID string, days int) ([]DailyStat, error) {
|
|
if days <= 0 {
|
|
days = 30
|
|
}
|
|
maxDays := int(s.retention.Hours() / 24)
|
|
if maxDays > 0 && days > maxDays {
|
|
days = maxDays
|
|
}
|
|
if days > 3660 {
|
|
days = 3660
|
|
}
|
|
cutoffDay := time.Now().UTC().Add(-time.Duration(days-1) * 24 * time.Hour).Format("2006-01-02")
|
|
rows, err := s.db.Query(`
|
|
SELECT substr(hour, 1, 10) AS day,
|
|
SUM(checks), SUM(up), SUM(degraded), SUM(down), SUM(sum_latency_ms)
|
|
FROM hourly_stats
|
|
WHERE monitor_id = ? AND hour >= ?
|
|
GROUP BY day
|
|
ORDER BY day`, monitorID, cutoffDay+"T00:00:00Z")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
out := make([]DailyStat, 0)
|
|
for rows.Next() {
|
|
var d DailyStat
|
|
var sumLat float64
|
|
if err := rows.Scan(&d.Date, &d.Checks, &d.Up, &d.Degraded, &d.Down, &sumLat); err != nil {
|
|
return nil, err
|
|
}
|
|
if d.Checks > 0 {
|
|
d.UptimePct = float64(d.Up+d.Degraded) / float64(d.Checks) * 100.0
|
|
d.AvgLatencyMs = sumLat / float64(d.Checks)
|
|
}
|
|
out = append(out, d)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// MonitorIDs returns distinct monitor IDs that have recorded stats.
|
|
func (s *StatsDB) MonitorIDs(ctx context.Context) ([]string, error) {
|
|
rows, err := s.db.QueryContext(ctx, `SELECT DISTINCT monitor_id FROM hourly_stats ORDER BY monitor_id`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
ids := make([]string, 0)
|
|
for rows.Next() {
|
|
var id string
|
|
if err := rows.Scan(&id); err != nil {
|
|
return nil, err
|
|
}
|
|
ids = append(ids, id)
|
|
}
|
|
return ids, rows.Err()
|
|
}
|
|
|
|
func boolInt(b bool) int {
|
|
if b {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func nullIf(null bool, v float64) interface{} {
|
|
if null {
|
|
return nil
|
|
}
|
|
return v
|
|
}
|