Show collapsible IP check cycles in the registry

This commit is contained in:
ayurishchev committed 2026-11-23 11:53:08 +03:00
1 parent 94124747ce
commit b58d5f5b82
16 files changed
+332 -36

No files matched your search

+6 -1
View File
@@ -63,6 +63,8 @@ type fakeControlAPI struct {
scanFreeAddresses []string
registry map[string]registryItem
registryChecks map[string][]check
registryEvents []event
registryCycles []registryCycle
// The chart of /registry: the breakdown served (breakdownStatus != 0 makes
// it fail with that status), the table behind a row and the raw queries
// of both endpoints.
@@ -553,7 +555,10 @@ func (f *fakeControlAPI) handler() http.Handler {
writeAPIErr(w, http.StatusNotFound, "unknown ip: "+addr)
return
}
writeJSON(w, http.StatusOK, registryHistoryResponse{Registry: item, Checks: f.registryChecks[addr], SelfCheckFailedOn: f.selfCheckFailedOn})
writeJSON(w, http.StatusOK, registryHistoryResponse{
Registry: item, Checks: f.registryChecks[addr], SelfCheckFailedOn: f.selfCheckFailedOn,
Events: f.registryEvents, Cycles: f.registryCycles,
})
})
mux.HandleFunc("GET /api/v1/admin/config/subnets", func(w http.ResponseWriter, r *http.Request) {
+14 -1
View File
@@ -62,6 +62,7 @@ type ipQueueItem struct {
FIPAssociatedAt *time.Time
AggregatedAt *time.Time
FIPReleasedAt *time.Time
CycleID int
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -88,6 +89,7 @@ type event struct {
SourceType string
SourceID string
IPID *int64
CycleID int
EventType string
Payload string
OccurredAt time.Time
@@ -373,7 +375,18 @@ type registryHistoryResponse struct {
Checks []check `json:"checks"`
// SelfCheckFailedOn lists the validators whose self-check of this address
// failed, over every run.
SelfCheckFailedOn []string `json:"self_check_failed_on"`
SelfCheckFailedOn []string `json:"self_check_failed_on"`
Events []event `json:"events"`
Cycles []registryCycle `json:"cycles"`
CurrentIP *ipQueueItem `json:"current_ip"`
}
type registryCycle struct {
CycleID int `json:"cycle_id"`
RunID int64 `json:"run_id"`
Verdict string `json:"verdict"`
AggregatedAt *time.Time `json:"aggregated_at"`
SelfCheckFailedOn []string `json:"self_check_failed_on"`
}
type validatorDTO struct {
+8 -3
View File
@@ -122,8 +122,13 @@ type ipsPageData struct {
type ipDetailData struct {
PageData
Detail ipDetailResponse
Events []eventView
ipDetailView
}
type ipDetailView struct {
Detail ipDetailResponse
Events []eventView
HasQueueData bool
}
// tracerouteView is a parsed traceroute_result event payload.
@@ -227,7 +232,7 @@ func (s *Server) handleIPsPage(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleIPDetail(w http.ResponseWriter, r *http.Request) {
ip := r.PathValue("ip")
detail, err := s.CA.GetIP(r.Context(), ip)
data := ipDetailData{Detail: detail, Events: buildEventViews(detail.Events)}
data := ipDetailData{ipDetailView: ipDetailView{Detail: detail, Events: buildEventViews(detail.Events), HasQueueData: true}}
data.ActiveNav = "ips"
data.Banner = bannerFor(err)
s.renderPage(w, r, "ip_detail_page", data)
+2 -1
View File
@@ -44,6 +44,7 @@ type registryPageData struct {
type registryDetailData struct {
PageData
History registryHistoryResponse
Cycles []registryCycleView
}
// handleRegistryPage lists every address ever submitted to the check
@@ -347,7 +348,7 @@ func registryRunOptions(runs []analyticsRun, chosen int64) []runOption {
func (s *Server) handleRegistryDetail(w http.ResponseWriter, r *http.Request) {
ip := r.PathValue("ip")
history, err := s.CA.GetRegistryHistory(r.Context(), ip)
data := registryDetailData{History: history}
data := registryDetailData{History: history, Cycles: buildRegistryCycles(history)}
data.ActiveNav = "registry"
data.Banner = bannerFor(err)
s.renderPage(w, r, "registry_detail_page", data)
+32 -4
View File
@@ -637,8 +637,13 @@ func TestRegistryPageAndDetail(t *testing.T) {
TotalCycles: 2, LastResult: "pass", InQueue: false,
}
fake.registryChecks["9.9.9.9"] = []check{
{CycleID: 2, Source: "egress", CheckType: "https", Target: "https://example.test", Success: true, CheckedAt: now},
{CycleID: 1, Source: "egress", CheckType: "https", Target: "https://example.test", Success: false, CheckedAt: now},
{CycleID: 2, AttemptNumber: 1, Source: "egress", CheckType: "https", Target: "https://new.example.test", Success: true, CheckedAt: now},
{CycleID: 1, AttemptNumber: 1, Source: "egress", CheckType: "https", Target: "https://old.example.test", Success: false, CheckedAt: now.Add(-time.Hour)},
}
fake.registryEvents = []event{{CycleID: 2, EventType: "traceroute_result", OccurredAt: now, Payload: `{"output":"trace of cycle two"}`}}
fake.registryCycles = []registryCycle{
{CycleID: 2, RunID: 20, Verdict: "pass", AggregatedAt: &now},
{CycleID: 1, RunID: 19, Verdict: "partial", SelfCheckFailedOn: []string{"older-validator"}},
}
ts := newTestServer(t, caURL)
@@ -651,8 +656,31 @@ func TestRegistryPageAndDetail(t *testing.T) {
if !strings.Contains(detail, "9.9.9.9") {
t.Fatalf("expected detail page to show the address, got:\n%s", detail)
}
if !strings.Contains(detail, "https://example.test") {
t.Fatalf("expected detail page to list retained checks, got:\n%s", detail)
const collapsedCycle = `<details class="registry-cycle">`
cards := strings.Split(detail, collapsedCycle)
if len(cards) != 3 {
t.Fatalf("expected two initially collapsed cycles, got %d:\n%s", len(cards)-1, detail)
}
first, second, _ := strings.Cut(cards[2], "</details>")
for _, tc := range []struct {
card string
want []string
unrelated string
}{
{cards[1], []string{fmtTime(now), "Запуск №20", "Цикл №2", "Успешно 1 из 1", "https://new.example.test", "События", `class="trace-output">trace of cycle two`}, "older-validator"},
{first, []string{fmtTime(now.Add(-time.Hour)), "Запуск №19", "Цикл №1", "Успешно 0 из 1", "https://old.example.test", "Self-check не прошёл на: older-validator"}, "trace of cycle two"},
} {
for _, want := range tc.want {
if !strings.Contains(tc.card, want) {
t.Fatalf("expected %q in cycle card:\n%s", want, tc.card)
}
}
if strings.Contains(tc.card, tc.unrelated) {
t.Fatalf("found another cycle's data %q in:\n%s", tc.unrelated, tc.card)
}
}
if strings.Contains(second, "https://old.example.test") {
t.Fatal("historical check escaped its cycle card")
}
notFound := get(t, ts, "/registry/1.2.3.4")
+118
View File
@@ -0,0 +1,118 @@
package dashboard
import (
"encoding/json"
"sort"
"time"
)
type registryCycleView struct {
ipDetailView
CycleID int
RunID int64
Date time.Time
Passed int
Badge Badge
}
func buildRegistryCycles(history registryHistoryResponse) []registryCycleView {
cycles := map[int]*registryCycleView{}
cycleFor := func(id int) *registryCycleView {
if cycles[id] == nil {
cycles[id] = &registryCycleView{CycleID: id}
}
return cycles[id]
}
for _, check := range history.Checks {
c := cycleFor(check.CycleID)
c.Detail.Checks = append(c.Detail.Checks, check)
c.Detail.IP.AttemptNumber = check.AttemptNumber
if check.ValidatorID != "" {
c.Detail.IP.OwnerValidatorID = &check.ValidatorID
}
if check.Success {
c.Passed++
}
if check.CheckedAt.After(c.Date) {
c.Date = check.CheckedAt
}
}
for _, e := range buildEventViews(history.Events) {
c := cycleFor(e.CycleID)
c.Events = append(c.Events, e)
}
if ip := history.CurrentIP; ip != nil && (ip.State != "queued" || cycles[ip.CycleID] != nil) {
c := cycleFor(ip.CycleID)
c.Detail.IP = *ip
c.HasQueueData = true
}
for _, meta := range history.Cycles {
if c := cycles[meta.CycleID]; c != nil {
c.RunID = meta.RunID
c.Detail.SelfCheckFailedOn = meta.SelfCheckFailedOn
if !c.HasQueueData {
c.Detail.IP.OverallResult = meta.Verdict
c.Detail.IP.AggregatedAt = meta.AggregatedAt
}
}
}
out := make([]registryCycleView, 0, len(cycles))
for _, c := range cycles {
if !c.HasQueueData {
c.restoreEventMetadata()
}
ip := c.Detail.IP
switch {
case c.HasQueueData:
c.Badge = ipBadge(ip.State, ip.OverallResult, ip.FIPAssociatedAt, 0)
case ip.State == "occupied":
c.Badge = ipBadge(ip.State, "", nil, 0)
case ip.OverallResult != "":
c.Badge = ipBadge("done", ip.OverallResult, nil, 0)
}
switch {
case ip.AggregatedAt != nil:
c.Date = *ip.AggregatedAt
case c.Date.IsZero() && len(c.Events) > 0:
c.Date = c.Events[0].OccurredAt
case c.Date.IsZero() && ip.AssignedAt != nil:
c.Date = *ip.AssignedAt
case c.Date.IsZero():
c.Date = ip.CreatedAt
}
out = append(out, *c)
}
sort.Slice(out, func(i, j int) bool { return out[i].CycleID > out[j].CycleID })
return out
}
func (c *registryCycleView) restoreEventMetadata() {
ip := &c.Detail.IP
for _, e := range c.Events {
switch e.EventType {
case "aggregated":
var payload struct{ Result string }
if ip.OverallResult == "" && json.Unmarshal([]byte(e.Payload), &payload) == nil {
switch payload.Result {
case "pass", "partial", "fail":
ip.OverallResult = payload.Result
ip.AggregatedAt = &e.OccurredAt
}
}
case "force_cancel":
if ip.OverallResult == "" {
ip.OverallResult = "cancelled"
ip.AggregatedAt = &e.OccurredAt
}
case "fip_occupied":
ip.State = "occupied"
case "fip_associated":
var payload struct {
ValidatorID string `json:"validator_id"`
}
if ip.OwnerValidatorID == nil && json.Unmarshal([]byte(e.Payload), &payload) == nil && payload.ValidatorID != "" {
ip.OwnerValidatorID = &payload.ValidatorID
}
}
}
}
+12
View File
@@ -407,6 +407,18 @@ tbody tr:hover { background: var(--surface-alt); }
td.addr { font-family: var(--font-mono); font-size: 13px; }
td.num { font-family: var(--font-mono); font-variant-numeric: tabular-nums; color: var(--text-muted); }
.table-scroll { overflow-x: auto; }
.registry-cycles { display: grid; gap: 8px; }
.registry-cycle {
min-width: 0;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
}
.registry-cycle > summary { padding: 10px 14px; cursor: pointer; }
.registry-cycle > summary:hover, .registry-cycle[open] > summary { background: var(--surface-alt); }
.registry-cycle > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.registry-cycle-body { padding: 12px 14px 16px; border-top: 1px solid var(--border); }
.actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }
/* ---------- status tags (square, not pill) ---------- */
+6 -2
View File
@@ -26,8 +26,12 @@
<h1 class="mono" style="display:flex;align-items:center;gap:10px">{{.Detail.IP.IPAddress}} <span class="pill {{$b.Class}}">{{$b.Label}}</span></h1>
</div>
<p class="muted"><a href="/registry/{{.Detail.IP.IPAddress}}">Полная история проверок этого адреса за всё время &rarr;</a></p>
{{template "ip_check_cycle" .}}
{{end}}
{{define "ip_check_cycle"}}
<p class="muted">
попытка {{.Detail.IP.AttemptNumber}} (повторов: {{.Detail.IP.RetryCount}})
попытка {{if .Detail.IP.AttemptNumber}}{{.Detail.IP.AttemptNumber}}{{else}}—{{end}} (повторов: {{if .HasQueueData}}{{.Detail.IP.RetryCount}}{{else}}—{{end}})
· валидатор {{deref .Detail.IP.OwnerValidatorID}}
</p>
<p class="muted">
@@ -36,7 +40,7 @@
</p>
{{if .Detail.SelfCheckFailedOn}}<p class="muted">Self-check не прошёл на: {{join .Detail.SelfCheckFailedOn ", "}}</p>{{end}}
<h2 class="section-title">Проверки (попытка {{.Detail.IP.AttemptNumber}})</h2>
<h2 class="section-title">Проверки{{if .Detail.IP.AttemptNumber}} (попытка {{.Detail.IP.AttemptNumber}}){{end}}</h2>
{{if .Detail.Checks}}
<div class="panel">
<div class="table-scroll">
@@ -36,24 +36,26 @@
</p>
{{if .History.SelfCheckFailedOn}}<p class="muted">Self-check не прошёл на: {{join .History.SelfCheckFailedOn ", "}}</p>{{end}}
<h2 class="section-title">История проверок (все сохранённые циклы)</h2>
{{if .History.Checks}}
<div class="panel">
<div class="table-scroll">
<table>
<thead><tr><th>Цикл</th><th>Источник</th><th>Тип</th><th>Цель</th><th>Успех</th><th>Задержка, мс</th><th>Время</th><th>Детали</th></tr></thead>
<tbody>
{{range .History.Checks}}
<tr>
<td class="num" data-label="Цикл">{{.CycleID}}</td>
<td data-label="Источник">{{.Source}}</td><td data-label="Тип">{{.CheckType}}</td><td class="addr" data-label="Цель">{{.Target}}</td>
<td data-label="Успех">{{if .Success}}<span class="pill pill-success">ok</span>{{else}}<span class="pill pill-danger">fail</span>{{end}}</td>
<td class="num" data-label="Задержка, мс">{{.LatencyMS}}</td><td class="num" data-label="Время">{{fmtTime .CheckedAt}}</td><td data-label="Детали">{{.Detail}}</td>
</tr>
<h2 class="section-title">История проверок</h2>
{{if .Cycles}}
<div class="registry-cycles">
{{range .Cycles}}
<details class="registry-cycle">
<summary>
{{if .Date.IsZero}}<span class="mono">—</span>{{else}}<time class="mono" datetime="{{.Date.Format "2006-01-02T15:04:05Z07:00"}}">{{fmtTime .Date}}</time>{{end}}
<span class="muted">· {{if .RunID}}Запуск №{{.RunID}} · {{end}}Цикл №{{.CycleID}}</span>
{{if .Badge.Label}}<span class="pill {{.Badge.Class}}">{{.Badge.Label}}</span>{{end}}
{{if .Detail.Checks}}
<span class="muted">· Успешно {{.Passed}} из {{len .Detail.Checks}}</span>
{{else}}
<span class="muted">· Проверок нет</span>
{{end}}
</tbody>
</table>
</summary>
<div class="registry-cycle-body">
{{template "ip_check_cycle" .}}
</div>
</details>
{{end}}
</div>
<p class="muted" style="margin-top:8px">Если глубина истории (см. <a href="/settings">настройки</a>) ограничена, здесь
показаны только сохранённые циклы — более старые уже вытеснены.</p>
+14
View File
@@ -37,6 +37,20 @@ func (d *DB) ListEventsForIP(ctx context.Context, ipID int64) ([]Event, error) {
return scanEvents(rows)
}
// ListEventsForRegistry includes events whose queue row has been deleted.
func (d *DB) ListEventsForRegistry(ctx context.Context, registryID int64) ([]Event, error) {
rows, err := d.QueryContext(ctx, `
SELECT id, source_type, source_id, ip_id, registry_id, cycle_id, event_type, payload, occurred_at, created_at
FROM events WHERE registry_id=? AND cycle_id>0
ORDER BY julianday(occurred_at) DESC, id DESC
`, registryID)
if err != nil {
return nil, err
}
defer rows.Close()
return scanEvents(rows)
}
func (d *DB) ListRecentEvents(ctx context.Context, limit int) ([]Event, error) {
rows, err := d.QueryContext(ctx, `
SELECT id, source_type, source_id, ip_id, registry_id, cycle_id, event_type, payload, occurred_at, created_at
+55
View File
@@ -603,6 +603,61 @@ func lastCycleResultFromChecks(ctx context.Context, d *DB, registryID int64) (st
}
}
type RegistryCycle struct {
CycleID int `json:"cycle_id"`
RunID int64 `json:"run_id"`
Verdict string `json:"verdict"`
AggregatedAt *time.Time `json:"aggregated_at"`
SelfCheckFailedOn []string `json:"self_check_failed_on"`
}
// ListRegistryCycles adds run verdicts and self-check failures to the cycles
// that still have queue data, checks, or events. Analytics can keep results
// after registry history is pruned.
func (d *DB) ListRegistryCycles(ctx context.Context, registryID int64) ([]RegistryCycle, error) {
rows, err := d.QueryContext(ctx, `
WITH evidence AS (
SELECT cycle_id, run_id FROM checks WHERE registry_id=?1
UNION ALL
SELECT DISTINCT cycle_id, NULL FROM events WHERE registry_id=?1 AND cycle_id>0
UNION ALL
SELECT cycle_id, run_id FROM ip_queue WHERE registry_id=?1
), cycles AS (
SELECT cycle_id, MAX(run_id) AS run_id FROM evidence GROUP BY cycle_id
)
SELECT c.cycle_id, COALESCE(c.run_id, r.run_id, 0),
COALESCE(CASE WHEN r.verdict_derived=0 THEN r.verdict END, ''),
CASE WHEN r.verdict_derived=0 THEN r.aggregated_at END,
(SELECT json_group_array(validator_id) FROM (
SELECT DISTINCT validator_id FROM ip_self_check_failures
WHERE registry_id=?1 AND cycle_id=c.cycle_id ORDER BY validator_id
))
FROM cycles c LEFT JOIN run_results r ON r.registry_id=?1 AND r.cycle_id=c.cycle_id
ORDER BY c.cycle_id DESC
`, registryID)
if err != nil {
return nil, err
}
defer rows.Close()
var cycles []RegistryCycle
for rows.Next() {
var c RegistryCycle
var aggregatedAt sql.NullString
var failures string
if err := rows.Scan(&c.CycleID, &c.RunID, &c.Verdict, &aggregatedAt, &failures); err != nil {
return nil, err
}
if c.AggregatedAt, err = nullStringToTimePtr(aggregatedAt); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(failures), &c.SelfCheckFailedOn); err != nil {
return nil, err
}
cycles = append(cycles, c)
}
return cycles, rows.Err()
}
func scanRegistryItems(rows *sql.Rows) ([]RegistryItem, error) {
var out []RegistryItem
for rows.Next() {
+24 -4
View File
@@ -1,6 +1,8 @@
package httpapi
import (
"database/sql"
"errors"
"fmt"
"net/http"
"net/netip"
@@ -111,11 +113,29 @@ func (s *Server) handleAdminRegistryHistory(w http.ResponseWriter, r *http.Reque
writeError(w, http.StatusInternalServerError, err.Error())
return
}
events, err := s.DB.ListEventsForRegistry(r.Context(), summary.ID)
if err != nil {
writeDBError(w, err)
return
}
cycles, err := s.DB.ListRegistryCycles(r.Context(), summary.ID)
if err != nil {
writeDBError(w, err)
return
}
currentIP, err := s.DB.GetIPByAddress(r.Context(), summary.IPAddress)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
writeDBError(w, err)
return
}
writeJSON(w, http.StatusOK, struct {
Registry registryDTO `json:"registry"`
Checks []db.Check `json:"checks"`
SelfCheckFailedOn []string `json:"self_check_failed_on"`
}{registrySummaryToDTO(*summary), checks, failedOn})
Registry registryDTO `json:"registry"`
Checks []db.Check `json:"checks"`
SelfCheckFailedOn []string `json:"self_check_failed_on"`
Events []db.Event `json:"events"`
Cycles []db.RegistryCycle `json:"cycles"`
CurrentIP *db.IPQueueItem `json:"current_ip,omitempty"`
}{registrySummaryToDTO(*summary), checks, failedOn, events, cycles, currentIP})
}
func registrySummaryToDTO(s db.RegistrySummary) registryDTO {
+21 -2
View File
@@ -106,8 +106,11 @@ func TestRegistryHistoryOutlivesIPDeletion(t *testing.T) {
t.Fatalf("registry history: status=%d body=%s", resp.StatusCode, body)
}
var hist struct {
Registry registryDTO `json:"registry"`
Checks []db.Check `json:"checks"`
Registry registryDTO `json:"registry"`
Checks []db.Check `json:"checks"`
Events []db.Event `json:"events"`
Cycles []db.RegistryCycle `json:"cycles"`
CurrentIP *db.IPQueueItem `json:"current_ip"`
}
if err := json.Unmarshal(body, &hist); err != nil {
t.Fatalf("unmarshal registry history: %v", err)
@@ -121,6 +124,18 @@ func TestRegistryHistoryOutlivesIPDeletion(t *testing.T) {
if hist.Registry.InQueue {
t.Fatalf("expected registry entry to report not-in-queue after delete, got %+v", hist.Registry)
}
if hist.CurrentIP != nil || len(hist.Cycles) != 1 || hist.Cycles[0].CycleID != item.CycleID ||
hist.Cycles[0].RunID == 0 || hist.Cycles[0].Verdict != item.OverallResult || hist.Cycles[0].AggregatedAt == nil {
t.Fatalf("expected archived cycle with its own verdict and timestamp, got %+v", hist.Cycles)
}
if len(hist.Events) == 0 {
t.Fatal("expected archived events")
}
for _, event := range hist.Events {
if event.CycleID != item.CycleID || event.IPID != nil {
t.Fatalf("event should stay attached to the archived cycle, got %+v", event)
}
}
// Resubmitting starts a second, distinct cycle on the same registry
// entry rather than colliding with the first.
@@ -141,6 +156,10 @@ func TestRegistryHistoryOutlivesIPDeletion(t *testing.T) {
if !hist.Registry.InQueue {
t.Fatalf("expected registry entry to report in-queue again, got %+v", hist.Registry)
}
if hist.CurrentIP == nil || len(hist.Cycles) != 2 || hist.Cycles[0].CycleID != hist.CurrentIP.CycleID ||
hist.Cycles[1].CycleID != item.CycleID || hist.Cycles[0].RunID == hist.Cycles[1].RunID {
t.Fatalf("expected current and archived cycles from different runs, got %+v", hist.Cycles)
}
_, body = fc.do(http.MethodGet, "/api/v1/admin/registry", nil)
var all []registryDTO