control-api: reduce SQLite disk writes; add diagnostic mode

Disk writes:
- SQLite pragmas in DSN: wal_autocheckpoint=10000, journal_size_limit=64MB, cache_size=64MB
- migration 0013: drop redundant idx_checks_registry_cycle
- results batched: UpsertChecksIfOpen in one transaction; agent flushes every 5s and before complete
- heartbeat kept in memory, persisted on state change or every 60s; startup grace for stale sweeps

Diagnostic mode:
- POST /api/v1/admin/diagnostics/attach|detach, GET /api/v1/admin/diagnostics
- migration 0014: diagnostic_holds; validator state "diagnostic"
- held addresses are not queued, held validators skip sweeps, port release and delete

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Opus 5.5 committed 2026-11-03 07:01:24 +03:00
1 parent d0ab6b94f9
commit 55d383bd34
41 files changed
+1214 -94

No files matched your search

+2 -2
View File
@@ -97,8 +97,8 @@ func TestRouteTableIsClassified(t *testing.T) {
t.Fatalf("admin route %q is %s, want admin", rt.Pattern, rt.Access)
}
}
if counts["admin"] != 46 || counts["agent"] != 5 || counts["open"] != 8 {
t.Fatalf("access counts = %v, want admin=46 agent=5 open=8", counts)
if counts["admin"] != 49 || counts["agent"] != 5 || counts["open"] != 8 {
t.Fatalf("access counts = %v, want admin=49 agent=5 open=8", counts)
}
}
+3
View File
@@ -203,6 +203,9 @@ func (s *Server) handleAdminValidators(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
for i := range validators {
s.Orch.OverlayValidatorHeartbeat(&validators[i])
}
writeJSON(w, http.StatusOK, validators)
}
+13 -9
View File
@@ -42,7 +42,7 @@ func (s *Server) handleAgentHeartbeat(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
var req heartbeatRequest
_ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing
if err := s.DB.Heartbeat(r.Context(), id); err != nil {
if err := s.Orch.ValidatorHeartbeat(r.Context(), id); err != nil {
writeError(w, http.StatusNotFound, "unknown validator: "+id)
return
}
@@ -149,7 +149,7 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
dropped := map[int64]int{}
checks := make([]db.Check, 0, len(req.Results))
for _, res := range req.Results {
item, err := s.DB.GetIP(r.Context(), res.IPID)
if err != nil {
@@ -160,17 +160,21 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
if err != nil {
checkedAt = db.Now()
}
written, err := s.Orch.RecordCheckIfOpen(r.Context(), db.Check{
checks = append(checks, db.Check{
IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber,
ValidatorID: id, Source: db.SourceEgress, CheckType: res.CheckType, Target: res.Target,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt,
})
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
if !written {
dropped[item.ID]++
}
written, err := s.Orch.RecordChecksIfOpen(r.Context(), checks)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
dropped := map[int64]int{}
for i, ok := range written {
if !ok {
dropped[checks[i].IPID]++
}
}
writeJSON(w, http.StatusOK, s.reportDropped(r.Context(), "validator-agent", id, db.SourceEgress, dropped))
+2
View File
@@ -18,6 +18,7 @@ func (s *Server) handleConfigListValidators(w http.ResponseWriter, r *http.Reque
}
out := make([]validatorDTO, len(validators))
for i, v := range validators {
s.Orch.OverlayValidatorHeartbeat(&v)
out[i] = validatorDTO{
ValidatorID: v.ValidatorID, Hostname: v.Hostname, OSPortID: v.OSPortID,
State: v.State, LastHeartbeatAt: v.LastHeartbeatAt,
@@ -76,6 +77,7 @@ func (s *Server) handleConfigListSites(w http.ResponseWriter, r *http.Request) {
}
out := make([]siteDTO, len(sites))
for i, site := range sites {
s.Orch.OverlaySiteHeartbeat(&site)
out[i] = siteDTO{
Index: site.Index, SiteID: site.SiteID, Hostname: site.Hostname,
State: site.State, LastHeartbeatAt: site.LastHeartbeatAt,
+1
View File
@@ -46,6 +46,7 @@ func newConfigTestHarness(t *testing.T) (*fakeClient, *db.DB, *orchestrator.Orch
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
orch := orchestrator.New(d, mock, cfg, log)
orch.EndStartupGrace()
// A background scan must never outlive the database it writes to.
t.Cleanup(func() { orch.CancelScan() })
srv := New(d, orch, log)
+69
View File
@@ -0,0 +1,69 @@
package httpapi
import (
"net/http"
"strings"
"cloudipvalidator/internal/orchestrator"
)
type diagnosticAttachRequest struct {
Items []struct {
Address string `json:"address"`
ValidatorID string `json:"validator_id"`
} `json:"items"`
Note string `json:"note"`
}
type diagnosticDetachRequest struct {
Addresses []string `json:"addresses"`
All bool `json:"all"`
}
type diagnosticResultsResponse struct {
Results []orchestrator.DiagnosticResult `json:"results"`
}
func (s *Server) handleAdminDiagnosticAttach(w http.ResponseWriter, r *http.Request) {
var req diagnosticAttachRequest
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if len(req.Items) == 0 {
writeError(w, http.StatusBadRequest, "items must not be empty")
return
}
items := make([]orchestrator.DiagnosticItem, len(req.Items))
for i, it := range req.Items {
addr := strings.TrimSpace(it.Address)
if addr == "" {
writeError(w, http.StatusBadRequest, "address must not be empty")
return
}
items[i] = orchestrator.DiagnosticItem{Address: addr, ValidatorID: strings.TrimSpace(it.ValidatorID)}
}
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticAttach(r.Context(), items, req.Note)})
}
func (s *Server) handleAdminDiagnosticDetach(w http.ResponseWriter, r *http.Request) {
var req diagnosticDetachRequest
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if !req.All && len(req.Addresses) == 0 {
writeError(w, http.StatusBadRequest, "addresses or all=true is required")
return
}
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticDetach(r.Context(), req.Addresses, req.All)})
}
func (s *Server) handleAdminDiagnosticList(w http.ResponseWriter, r *http.Request) {
holds, err := s.Orch.DiagnosticList(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, holds)
}
+17 -14
View File
@@ -36,7 +36,7 @@ func (s *Server) handleProberHeartbeat(w http.ResponseWriter, r *http.Request) {
siteID := r.PathValue("site_id")
var req heartbeatRequest
_ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing
if err := s.DB.SiteHeartbeat(r.Context(), siteID); err != nil {
if err := s.Orch.SiteHeartbeat(r.Context(), siteID); err != nil {
writeError(w, http.StatusNotFound, "unknown site_id: "+siteID)
return
}
@@ -97,8 +97,7 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
return
}
completed := map[int64]bool{}
dropped := map[int64]int{}
checks := make([]db.Check, 0, len(req.Results))
for _, res := range req.Results {
item, err := s.DB.GetIP(r.Context(), res.IPID)
if err != nil {
@@ -109,21 +108,25 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
if err != nil {
checkedAt = db.Now()
}
written, err := s.Orch.RecordCheckIfOpen(r.Context(), db.Check{
checks = append(checks, db.Check{
IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber,
Source: db.InboundSource(siteIndex), CheckType: res.CheckType, Target: res.IPAddress,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt,
})
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
if !written {
dropped[item.ID]++
continue
}
if res.Complete {
completed[res.IPID] = true
}
written, err := s.Orch.RecordChecksIfOpen(r.Context(), checks)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
completed := map[int64]bool{}
dropped := map[int64]int{}
for i, ok := range written {
switch {
case !ok:
dropped[checks[i].IPID]++
case req.Results[i].Complete:
completed[checks[i].IPID] = true
}
}
for ipID := range completed {
+3
View File
@@ -59,6 +59,9 @@ func (s *Server) routeTable() []route {
{"POST /api/v1/admin/ips/delete", s.handleAdminDeleteIPs, accessAdmin},
{"POST /api/v1/admin/ips/clear", s.handleAdminClearQueue, accessAdmin},
{"GET /api/v1/admin/validators", s.handleAdminValidators, accessAdmin},
{"POST /api/v1/admin/diagnostics/attach", s.handleAdminDiagnosticAttach, accessAdmin},
{"POST /api/v1/admin/diagnostics/detach", s.handleAdminDiagnosticDetach, accessAdmin},
{"GET /api/v1/admin/diagnostics", s.handleAdminDiagnosticList, accessAdmin},
{"GET /api/v1/admin/auto-cycle", s.handleAdminGetAutoCycle, accessAdmin},
{"PUT /api/v1/admin/auto-cycle", s.handleAdminPutAutoCycle, accessAdmin},
{"POST /api/v1/admin/auto-cycle/start", s.handleAdminStartAutoCycle, accessAdmin},