Remove historical analytics from the registry page

This commit is contained in:
ayurishchev committed 2026-11-23 12:11:03 +03:00
1 parent b58d5f5b82
commit 7eeb8c4ae9
16 files changed
+16 -794

No files matched your search

-279
View File
@@ -1,14 +1,12 @@
package dashboard
import (
"encoding/json"
"errors"
"net/http"
"net/netip"
"net/url"
"strconv"
"strings"
"time"
)
// Values of the registry's direction and protocol filters; same as
@@ -32,8 +30,6 @@ type registryPageData struct {
Runs []runOption
SubnetOptions []subnetOption
Breakdown *breakdownView // nil unless a direction or protocol is chosen
Trend *trendShell // nil without a direction
TrendView string // trendViewPct or trendViewCount
AnalyticsURL string // the analytics page of Run with the same subnet, direction and protocol
Page, PerPage int
Total int
@@ -121,10 +117,6 @@ func (s *Server) handleRegistryPage(w http.ResponseWriter, r *http.Request) {
PerPageOptions: perPageOptions,
}
data.ActiveNav = "registry"
data.TrendView = parseTrendView(r.URL.Query().Get("trend_view"))
if direction != "" {
data.Trend = newTrendShell(query, data.TrendView, r.URL.Query())
}
if run > 0 {
data.AnalyticsURL = analyticsURL(run, query)
}
@@ -353,274 +345,3 @@ func (s *Server) handleRegistryDetail(w http.ResponseWriter, r *http.Request) {
data.Banner = bannerFor(err)
s.renderPage(w, r, "registry_detail_page", data)
}
// Values of the trend's ?trend_view=: the Y axis in percent or in checks.
const (
trendViewPct = "pct"
trendViewCount = "count"
)
func parseTrendView(v string) string {
if v == trendViewCount {
return trendViewCount
}
return trendViewPct
}
// parseTrendDate reads ?trend_from= / ?trend_to= (YYYY-MM-DD); a value that is
// not a date is dropped.
func parseTrendDate(v string) string {
if _, err := time.Parse("2006-01-02", v); err != nil {
return ""
}
return v
}
// trendShell is the frame of the chart "dynamics over runs" on the registry
// page: the controls render at once, the chart itself (registry_trend_data) is
// loaded by htmx from /registry/trend, so the table does not wait for it. QS is
// the query that request carries: the subnet, direction, protocol and period.
type trendShell struct {
Scope, View, From, To, QS string
APQS string // the query of the always-pass tile: QS plus the address search
}
func newTrendShell(q registryQuery, view string, v url.Values) *trendShell {
t := &trendShell{View: view, From: parseTrendDate(v.Get("trend_from")), To: parseTrendDate(v.Get("trend_to"))}
t.Scope = strings.ToUpper(q.Direction[:1]) + q.Direction[1:] + " · " + trendProtocol(q)
p := url.Values{"direction": {q.Direction}}
for k, x := range map[string]string{"protocol": q.Protocol, "subnet": q.Subnet, "trend_from": t.From, "trend_to": t.To} {
if x != "" {
p.Set(k, x)
}
}
t.QS = p.Encode()
if q.Q != "" {
p.Set("q", q.Q)
}
t.APQS = p.Encode()
return t
}
func trendProtocol(q registryQuery) string {
if q.Protocol == "" {
return "все протоколы"
}
return q.Protocol
}
// trendView is the loaded chart: the data for registry-trend.js (JSON, in the
// element's data-trend), and the same numbers as a table for screen readers.
// With Err set the chart could not be loaded, with Empty there is nothing to draw.
type trendView struct {
Err, Note, JSON string
Empty bool
Runs []trendRunView
Rows []trendRowView
}
type trendRunView struct {
ID int64
Date string
Addresses int
}
type trendRowView struct {
Label string
Cells []string
}
// trendClientData is what registry-trend.js draws: runs oldest first, and per
// target or site its points [index of the run, successful, all checks].
type trendClientData struct {
Runs []trendClientRun `json:"runs"`
Series []trendClientSeries `json:"series"`
}
type trendClientRun struct {
ID int64 `json:"id"`
At string `json:"at"`
Addresses int `json:"n"`
}
type trendClientSeries struct {
Label string `json:"l"`
Points [][3]int `json:"p"`
}
// handleRegistryTrend serves the loaded chart as an htmx fragment: the page's
// subnet, direction and protocol plus the period (?trend_from=&trend_to=). An
// error of control-api shows in the fragment, not as a banner.
func (s *Server) handleRegistryTrend(w http.ResponseWriter, r *http.Request) {
q := parseSliceFilter(r.URL.Query())
v := &trendView{}
if q.Direction == "" {
v.Err = "Выберите направление, чтобы увидеть динамику по запускам."
} else {
from, to := parseTrendDate(r.URL.Query().Get("trend_from")), parseTrendDate(r.URL.Query().Get("trend_to"))
t, err := s.CA.GetRegistryTrend(r.Context(), q, from, to)
if err != nil {
v.Err = "Не удалось получить динамику: " + err.Error()
} else {
s.fillTrendView(v, t, from != "" || to != "")
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if err := s.tmpl.ExecuteTemplate(w, "registry_trend_data", v); err != nil {
s.Log.Error("render fragment", "template", "registry_trend_data", "err", err)
}
}
func (s *Server) fillTrendView(v *trendView, t registryTrend, period bool) {
if len(t.Runs) == 0 || len(t.Series) == 0 {
v.Empty = true
return
}
idx := make(map[int64]int, len(t.Runs))
d := trendClientData{Runs: make([]trendClientRun, len(t.Runs)), Series: make([]trendClientSeries, len(t.Series))}
for i, x := range t.Runs {
idx[x.ID] = i
d.Runs[i] = trendClientRun{ID: x.ID, At: x.StartedAt.UTC().Format(time.RFC3339), Addresses: x.Addresses}
v.Runs = append(v.Runs, trendRunView{ID: x.ID, Date: x.StartedAt.UTC().Format("2006-01-02 15:04"), Addresses: x.Addresses})
}
for i, sr := range t.Series {
row := trendRowView{Label: sr.Label, Cells: make([]string, len(t.Runs))}
for j := range row.Cells {
row.Cells[j] = "—"
}
d.Series[i].Label = sr.Label
for _, p := range sr.Points {
if j, ok := idx[p.RunID]; ok {
d.Series[i].Points = append(d.Series[i].Points, [3]int{j, p.OK, p.Total})
row.Cells[j] = strconv.Itoa(p.OK) + " из " + strconv.Itoa(p.Total)
}
}
v.Rows = append(v.Rows, row)
}
b, _ := json.Marshal(d)
v.JSON = string(b)
v.Note = "Показаны завершённые запуски: " + strconv.Itoa(len(t.Runs)) + "."
if t.Truncated {
v.Note += " Запусков больше, чем помещается на график, — показаны самые поздние."
if !period {
v.Note += " Чтобы увидеть более ранние, задайте период."
}
}
}
// alwaysPassView is the tile "always passed" above the trend chart. With Err
// set the tile could not be loaded; with Hint there is nothing to count. QS is
// the query of its list (the filter and the period), Label the title of the
// list's dialog and Slice what the count covers.
type alwaysPassView struct {
Err, Hint string
N, M int
Pct, Period, Label string
Slice, Aria, QS string
}
// pluralRuns declines "запуск" for n.
func pluralRuns(n int) string {
if n%100 >= 11 && n%100 <= 14 {
return "запусков"
}
switch n % 10 {
case 1:
return "запуск"
case 2, 3, 4:
return "запуска"
default:
return "запусков"
}
}
// alwaysPassQuery reads the request of the tile and its list proxies: the
// page's subnet, direction, protocol and address search, and the period
// (?trend_from=&trend_to=); direction is required.
func alwaysPassQuery(r *http.Request) (q registryQuery, from, to string, ok bool) {
q = parseRegistryQuery(r)
q.Run, q.LastResult = 0, "" // the run and the status describe the current state, not a history
return q, parseTrendDate(r.URL.Query().Get("trend_from")), parseTrendDate(r.URL.Query().Get("trend_to")), q.Direction != ""
}
// handleRegistryAlwaysPass serves the tile as an htmx fragment. An error of
// control-api shows in the tile, not as a banner.
func (s *Server) handleRegistryAlwaysPass(w http.ResponseWriter, r *http.Request) {
q, from, to, ok := alwaysPassQuery(r)
v := &alwaysPassView{}
if !ok {
v.Hint = "Выберите направление, чтобы увидеть, какие адреса всегда проходили проверку."
} else if a, err := s.CA.GetRegistryAlwaysPass(r.Context(), q, from, to); err != nil {
v.Err = "Не удалось получить показатель: " + err.Error()
} else {
fillAlwaysPassView(v, q, from, to, a)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if err := s.tmpl.ExecuteTemplate(w, "registry_always_pass", v); err != nil {
s.Log.Error("render fragment", "template", "registry_always_pass", "err", err)
}
}
func fillAlwaysPassView(v *alwaysPassView, q registryQuery, from, to string, a registryAlwaysPass) {
v.N, v.M, v.Pct = a.AlwaysPass, a.Addresses, pct1(a.AlwaysPass, a.Addresses)
v.Label = "Всегда проходили · " + strings.ToUpper(q.Direction[:1]) + q.Direction[1:] + " · " + trendProtocol(q)
p := q.filter()
p.Del("run")
p.Del("last_result")
if from != "" {
p.Set("trend_from", from)
}
if to != "" {
p.Set("trend_to", to)
}
v.QS = p.Encode()
if a.Runs == 0 || a.FirstRunAt == nil || a.LastRunAt == nil {
v.Period = "в этом периоде нет завершённых запусков"
} else {
v.Period = "за " + strconv.Itoa(a.Runs) + " " + pluralRuns(a.Runs) + ", " + a.FirstRunAt.UTC().Format("2006-01-02") + " — " + a.LastRunAt.UTC().Format("2006-01-02")
}
v.Slice = "Учтены направление, протокол, подсеть, поиск по IP и период. Не учтены запуск и статус. Берутся адреса, у которых в запусках периода есть проверки; адрес засчитан, если ни одна из них не провалена."
if a.Truncated {
v.Slice += " Запусков больше, чем учтено, — взяты самые поздние."
}
v.Aria = "Всегда проходили: " + strconv.Itoa(a.AlwaysPass) + " из " + strconv.Itoa(a.Addresses) + " адресов, " + v.Pct + " %, " + v.Period + ". Открыть список адресов."
}
// handleRegistryAlwaysPassList proxies the addresses behind the tile as JSON.
func (s *Server) handleRegistryAlwaysPassList(w http.ResponseWriter, r *http.Request) {
q, from, to, ok := alwaysPassQuery(r)
if !ok {
http.Error(w, "direction is required", http.StatusBadRequest)
return
}
out, err := s.CA.GetRegistryAlwaysPassList(r.Context(), q, from, to)
if err != nil {
writeProxyError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(out)
}
// handleRegistryAlwaysPassCSV proxies the same table as a CSV download.
func (s *Server) handleRegistryAlwaysPassCSV(w http.ResponseWriter, r *http.Request) {
q, from, to, ok := alwaysPassQuery(r)
if !ok {
http.Error(w, "direction is required", http.StatusBadRequest)
return
}
body, disposition, err := s.CA.GetRegistryAlwaysPassCSV(r.Context(), q, from, to)
if err != nil {
writeProxyError(w, err)
return
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
if disposition != "" {
w.Header().Set("Content-Disposition", disposition)
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}