stillbox/pkg/gordio/sinks/alerting/alerting.go

123 lines
2.8 KiB
Go
Raw Normal View History

2024-10-23 08:55:19 -04:00
package alerting
import (
"context"
"fmt"
"sync"
"time"
cl "dynatron.me/x/stillbox/pkg/calls"
"dynatron.me/x/stillbox/pkg/gordio/database"
"dynatron.me/x/stillbox/internal/timeseries"
"dynatron.me/x/stillbox/internal/trending"
"github.com/rs/zerolog/log"
)
const (
StorageLookbackDays = 2
HalfLife = time.Hour
RecentDuration = time.Hour
)
type AlertSink struct {
sync.RWMutex
scorer trending.Scorer[cl.Talkgroup]
}
func NewSink(ctx context.Context) *AlertSink {
as := &AlertSink{
scorer: trending.NewScorer[cl.Talkgroup](
trending.WithTimeSeries(newTimeSeries),
trending.WithStorageDuration[cl.Talkgroup](StorageLookbackDays*24*time.Hour),
trending.WithRecentDuration[cl.Talkgroup](RecentDuration),
trending.WithHalfLife[cl.Talkgroup](HalfLife),
),
}
go as.startBackfill(ctx)
return as
}
func (as *AlertSink) startBackfill(ctx context.Context) {
since := time.Now().Add(StorageLookbackDays * -24 * time.Hour)
log.Debug().Time("since", since).Msg("starting stats backfill")
count, err := as.backfill(ctx, since)
if err != nil {
log.Error().Err(err).Msg("backfill failed")
return
}
log.Debug().Int("count", count).Int("len", as.scorer.Score().Len()).Msg("backfill finished")
as.printScores()
}
type score[K comparable] struct {
ID K
Score float64
Probability float64
Expectation float64
Maximum float64
KLScore float64
}
func (as *AlertSink) printScores() {
scores := as.scorer.Score()
fmt.Printf("score len is %d\n", scores.Len())
for _, s := range scores {
fmt.Printf("%d:%d score %f prob %f exp %f max %f kl %f", s.ID.System, s.ID.Talkgroup, s.Score,
s.Probability, s.Expectation, s.Maximum, s.KLScore)
}
}
func (as *AlertSink) backfill(ctx context.Context, since time.Time) (count int, err error) {
db := database.FromCtx(ctx)
const backfillStatsQuery = `SELECT system, talkgroup, call_date FROM calls WHERE call_date > $1`
rows, err := db.Query(ctx, backfillStatsQuery, since)
if err != nil {
return count, err
}
defer rows.Close()
as.Lock()
defer as.Unlock()
for rows.Next() {
var tg cl.Talkgroup
var callDate time.Time
if err := rows.Scan(&tg.System, &tg.Talkgroup, &callDate); err != nil {
return count, err
}
as.scorer.AddEvent(tg, callDate)
count++
}
if err := rows.Err(); err != nil {
return count, err
}
return count, nil
}
func newTimeSeries(id cl.Talkgroup) trending.TimeSeries {
ts, _ := timeseries.NewTimeSeries(timeseries.WithGranularities(
[]timeseries.Granularity{
{Granularity: time.Second, Count: 60},
{Granularity: time.Minute, Count: 10},
{Granularity: time.Hour, Count: 24},
{Granularity: time.Hour * 24, Count: StorageLookbackDays},
},
))
return ts
}
func (as *AlertSink) SinkType() string {
return "alerting"
}
func (ns *AlertSink) Call(ctx context.Context, call *cl.Call) error {
return nil
}