stillbox/pkg/alerting/stats.go

76 lines
1.8 KiB
Go
Raw Permalink Normal View History

package alerting
import (
_ "embed"
"html/template"
"net/http"
"time"
2024-11-03 07:19:03 -05:00
"dynatron.me/x/stillbox/pkg/config"
"dynatron.me/x/stillbox/pkg/database"
2024-11-03 08:09:49 -05:00
"dynatron.me/x/stillbox/pkg/talkgroups"
2024-10-31 00:10:53 -04:00
"dynatron.me/x/stillbox/internal/common"
"dynatron.me/x/stillbox/internal/trending"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
)
//go:embed stats.html
var statsTemplateFile string
2024-11-07 23:17:16 -05:00
var (
statTmpl = template.Must(template.New("stats").Funcs(common.FuncMap).Parse(statsTemplateFile))
)
type stats interface {
PrivateRoutes(chi.Router)
}
func (as *alerter) PrivateRoutes(r chi.Router) {
2024-10-30 09:49:45 -04:00
r.Get("/tgstats", as.tgStatsHandler)
r.Post("/tgstats", as.simulateHandler)
2024-10-31 00:10:53 -04:00
r.Get("/testnotify", as.testNotifyHandler)
}
func (as *noopAlerter) PrivateRoutes(r chi.Router) {}
2024-10-30 09:49:45 -04:00
func (as *alerter) tgStatsHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
db := database.FromCtx(ctx)
2024-11-17 21:46:10 -05:00
tgt := as.scoredTGsTuple()
tgs, err := db.GetTalkgroupsWithLearnedBySysTGID(ctx, tgt)
if err != nil {
log.Error().Err(err).Msg("stats TG get failed")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-11-15 08:46:29 -05:00
tgMap := make(map[talkgroups.ID]database.GetTalkgroupsRow, len(tgs))
for _, t := range tgs {
2024-11-15 11:34:54 -05:00
tgMap[talkgroups.ID{System: uint32(t.System.ID), Talkgroup: uint32(t.Talkgroup.TGID)}] = t
}
renderData := struct {
2024-11-15 08:46:29 -05:00
TGs map[talkgroups.ID]database.GetTalkgroupsRow
2024-11-03 08:09:49 -05:00
Scores trending.Scores[talkgroups.ID]
2024-10-30 09:49:45 -04:00
LastScore time.Time
Simulation *Simulation
Config config.Alerting
}{
2024-10-30 09:49:45 -04:00
TGs: tgMap,
Scores: as.scores,
LastScore: as.lastScore,
Config: as.cfg,
Simulation: as.sim,
}
w.WriteHeader(http.StatusOK)
err = statTmpl.Execute(w, renderData)
if err != nil {
log.Error().Err(err).Msg("stat template exec")
}
}