Harden core packages and add interactive CLI config builder (rud config/validate/test)
This commit is contained in:
parent
d37503c863
commit
99e24be6c9
29 changed files with 6763 additions and 165 deletions
380
internal/builder/editors_core.go
Normal file
380
internal/builder/editors_core.go
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/checker"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/store"
|
||||
)
|
||||
|
||||
// MonitorTestResult captures the outcome of a live one-shot monitor check.
|
||||
type MonitorTestResult struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Method string `json:"method"`
|
||||
Target string `json:"target"`
|
||||
State string `json:"state"`
|
||||
LatencyMs float64 `json:"latency_ms"`
|
||||
Code int `json:"code,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// RunLiveTests executes live health checks concurrently for the selected monitors
|
||||
// (or all monitors when filterIDs is empty).
|
||||
func RunLiveTests(ctx context.Context, cfg *config.Config, filterIDs []string, retry bool) ([]MonitorTestResult, error) {
|
||||
byID := make(map[string]config.MonitorConfig, len(cfg.Monitors))
|
||||
for _, m := range cfg.Monitors {
|
||||
byID[m.ID] = m
|
||||
}
|
||||
|
||||
var targets []config.MonitorConfig
|
||||
if len(filterIDs) == 0 {
|
||||
targets = append(targets, cfg.Monitors...)
|
||||
} else {
|
||||
seen := make(map[string]bool, len(filterIDs))
|
||||
for _, id := range filterIDs {
|
||||
m, ok := byID[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown monitor id %q", id)
|
||||
}
|
||||
if !seen[id] {
|
||||
seen[id] = true
|
||||
targets = append(targets, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results := make([]MonitorTestResult, len(targets))
|
||||
var wg sync.WaitGroup
|
||||
for i, mon := range targets {
|
||||
wg.Add(1)
|
||||
go func(idx int, m config.MonitorConfig) {
|
||||
defer wg.Done()
|
||||
if !retry {
|
||||
m.Retries = config.IntPtr(0)
|
||||
}
|
||||
res := checker.RunCheckWithRetries(ctx, m, cfg.Defaults)
|
||||
name := m.Name
|
||||
if name == "" {
|
||||
name = m.ID
|
||||
}
|
||||
results[idx] = MonitorTestResult{
|
||||
ID: m.ID,
|
||||
Name: name,
|
||||
Method: strings.ToUpper(m.Method),
|
||||
Target: m.DisplayTarget(),
|
||||
State: res.State,
|
||||
LatencyMs: res.LatencyMs,
|
||||
Code: res.Code,
|
||||
Message: res.Message,
|
||||
}
|
||||
}(i, mon)
|
||||
}
|
||||
wg.Wait()
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// PrintLiveTestTable formats MonitorTestResult rows into a readable table.
|
||||
func PrintLiveTestTable(out io.Writer, results []MonitorTestResult, color bool) {
|
||||
if len(results) == 0 {
|
||||
_, _ = fmt.Fprintln(out, "No monitors to test.")
|
||||
return
|
||||
}
|
||||
|
||||
idW, methW, stateW := len("ID"), len("METHOD"), len("STATE")
|
||||
for _, r := range results {
|
||||
if len(r.ID) > idW {
|
||||
idW = len(r.ID)
|
||||
}
|
||||
if len(r.Method) > methW {
|
||||
methW = len(r.Method)
|
||||
}
|
||||
st := strings.ToUpper(r.State)
|
||||
if len(st) > stateW {
|
||||
stateW = len(st)
|
||||
}
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(out, "%-*s %-*s %-*s %9s %s\n", idW, "ID", methW, "METHOD", stateW, "STATE", "LATENCY", "DETAILS")
|
||||
_, _ = fmt.Fprintf(out, "%s %s %s %s %s\n",
|
||||
strings.Repeat("-", idW),
|
||||
strings.Repeat("-", methW),
|
||||
strings.Repeat("-", stateW),
|
||||
"---------",
|
||||
"-------",
|
||||
)
|
||||
for _, r := range results {
|
||||
stUpper := strings.ToUpper(r.State)
|
||||
paddedState := fmt.Sprintf("%-*s", stateW, stUpper)
|
||||
if color {
|
||||
switch r.State {
|
||||
case store.StateUp:
|
||||
paddedState = "\x1b[32m" + paddedState + "\x1b[0m"
|
||||
case store.StateDegraded:
|
||||
paddedState = "\x1b[33m" + paddedState + "\x1b[0m"
|
||||
case store.StateDown:
|
||||
paddedState = "\x1b[31m" + paddedState + "\x1b[0m"
|
||||
}
|
||||
}
|
||||
details := r.Message
|
||||
if r.Target != "" {
|
||||
if details != "" {
|
||||
details = fmt.Sprintf("[%s] %s", r.Target, details)
|
||||
} else {
|
||||
details = r.Target
|
||||
}
|
||||
}
|
||||
_, _ = fmt.Fprintf(out, "%-*s %-*s %s %7.1fms %s\n",
|
||||
idW, r.ID, methW, r.Method, paddedState, r.LatencyMs, details)
|
||||
}
|
||||
}
|
||||
|
||||
func editServer(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("Listen: %s | Endpoint: %s | Refresh: %s",
|
||||
cfg.Server.Listen, cfg.Server.Endpoint, cfg.Server.RefreshInterval.Std())
|
||||
opts := []Option{
|
||||
{Label: "Listen address", Description: cfg.Server.Listen},
|
||||
{Label: "HTTP endpoint path", Description: cfg.Server.Endpoint},
|
||||
{Label: "Browser auto-refresh interval", Description: cfg.Server.RefreshInterval.Std().String()},
|
||||
{
|
||||
Label: "HTML HTTP status codes",
|
||||
Description: fmt.Sprintf("up=%d degraded=%d down=%d pending=%d", cfg.Server.StatusCodes.HTML.Up, cfg.Server.StatusCodes.HTML.Degraded, cfg.Server.StatusCodes.HTML.Down, cfg.Server.StatusCodes.HTML.Pending),
|
||||
},
|
||||
{
|
||||
Label: "JSON HTTP status codes",
|
||||
Description: fmt.Sprintf("up=%d degraded=%d down=%d pending=%d", cfg.Server.StatusCodes.JSON.Up, cfg.Server.StatusCodes.JSON.Degraded, cfg.Server.StatusCodes.JSON.Down, cfg.Server.StatusCodes.JSON.Pending),
|
||||
},
|
||||
{Label: "Back to main hub"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Server Settings", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
v, err := ui.PromptString("Listen address", cfg.Server.Listen, "host:port or :8080", false, requireNonEmpty("listen"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Server.Listen = v
|
||||
case 1:
|
||||
v, err := ui.PromptString("Endpoint path", cfg.Server.Endpoint, "must start with /", false, requireNonEmpty("endpoint"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !strings.HasPrefix(v, "/") {
|
||||
v = "/" + v
|
||||
}
|
||||
cfg.Server.Endpoint = v
|
||||
case 2:
|
||||
d, err := ui.PromptDuration("Browser refresh interval", cfg.Server.RefreshInterval, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Server.RefreshInterval = d
|
||||
case 3:
|
||||
if err := editStatusCodes(ui, "HTML Status Codes (keep 200 for Cloudflare Tunnel)", &cfg.Server.StatusCodes.HTML); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
if err := editStatusCodes(ui, "JSON Status Codes", &cfg.Server.StatusCodes.JSON); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editStatusCodes(ui *UI, title string, sc *config.StatusCodesByState) error {
|
||||
ui.Header(title, "HTTP status codes returned for each global state (100-599)")
|
||||
var err error
|
||||
if sc.Up, err = ui.PromptInt("HTTP status when UP", sc.Up, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
if sc.Degraded, err = ui.PromptInt("HTTP status when DEGRADED", sc.Degraded, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
if sc.Down, err = ui.PromptInt("HTTP status when DOWN", sc.Down, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
if sc.Pending, err = ui.PromptInt("HTTP status when PENDING", sc.Pending, 100, 599); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func editDefaultsAndStorage(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
persist := cfg.Storage.PersistenceFile
|
||||
if persist == "" {
|
||||
persist = "(disabled)"
|
||||
}
|
||||
sub := fmt.Sprintf("Interval: %s | Timeout: %s | History: %d | Persistence: %s",
|
||||
cfg.Defaults.Interval.Std(), cfg.Defaults.Timeout.Std(), cfg.Storage.HistorySize, persist)
|
||||
opts := []Option{
|
||||
{Label: "Default check interval", Description: cfg.Defaults.Interval.Std().String()},
|
||||
{Label: "Default check timeout", Description: cfg.Defaults.Timeout.Std().String()},
|
||||
{Label: "Default retries", Description: fmt.Sprintf("%d", cfg.Defaults.Retries)},
|
||||
{Label: "Default degraded latency threshold", Description: cfg.Defaults.DegradedLatency.Std().String()},
|
||||
{Label: "Ring-buffer history size", Description: fmt.Sprintf("%d checks per monitor", cfg.Storage.HistorySize)},
|
||||
{Label: "Persistence file path", Description: persist},
|
||||
{Label: "Persistence save interval", Description: cfg.Storage.SaveInterval.Std().String()},
|
||||
{Label: "Back to main hub"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Defaults & Storage", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
d, err := ui.PromptDuration("Default interval", cfg.Defaults.Interval, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.Interval = d
|
||||
case 1:
|
||||
d, err := ui.PromptDuration("Default timeout", cfg.Defaults.Timeout, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.Timeout = d
|
||||
case 2:
|
||||
r, err := ui.PromptInt("Default retries", cfg.Defaults.Retries, 0, 20)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.Retries = r
|
||||
case 3:
|
||||
d, err := ui.PromptDuration("Default degraded latency threshold", cfg.Defaults.DegradedLatency, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Defaults.DegradedLatency = d
|
||||
case 4:
|
||||
h, err := ui.PromptInt("History size", cfg.Storage.HistorySize, 1, 100000)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.HistorySize = h
|
||||
case 5:
|
||||
p, err := ui.PromptString("Persistence file", cfg.Storage.PersistenceFile, "e.g. ./data/rud_state.json", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.PersistenceFile = p
|
||||
case 6:
|
||||
d, err := ui.PromptDuration("Save interval", cfg.Storage.SaveInterval, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Storage.SaveInterval = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type diffLine struct {
|
||||
kind byte // ' ', '-', '+'
|
||||
text string
|
||||
}
|
||||
|
||||
// FormatDiff produces a compact contextual diff between two JSON configuration strings.
|
||||
func FormatDiff(before, after string) string {
|
||||
if before == after {
|
||||
return "(no changes)"
|
||||
}
|
||||
a := strings.Split(strings.TrimRight(before, "\n"), "\n")
|
||||
b := strings.Split(strings.TrimRight(after, "\n"), "\n")
|
||||
|
||||
// LCS dynamic programming table
|
||||
m, n := len(a), len(b)
|
||||
dp := make([][]int, m+1)
|
||||
for i := range dp {
|
||||
dp[i] = make([]int, n+1)
|
||||
}
|
||||
for i := m - 1; i >= 0; i-- {
|
||||
for j := n - 1; j >= 0; j-- {
|
||||
if a[i] == b[j] {
|
||||
dp[i][j] = dp[i+1][j+1] + 1
|
||||
} else if dp[i+1][j] >= dp[i][j+1] {
|
||||
dp[i][j] = dp[i+1][j]
|
||||
} else {
|
||||
dp[i][j] = dp[i][j+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var ops []diffLine
|
||||
i, j := 0, 0
|
||||
for i < m && j < n {
|
||||
if a[i] == b[j] {
|
||||
ops = append(ops, diffLine{' ', a[i]})
|
||||
i++
|
||||
j++
|
||||
} else if dp[i+1][j] >= dp[i][j+1] {
|
||||
ops = append(ops, diffLine{'-', a[i]})
|
||||
i++
|
||||
} else {
|
||||
ops = append(ops, diffLine{'+', b[j]})
|
||||
j++
|
||||
}
|
||||
}
|
||||
for i < m {
|
||||
ops = append(ops, diffLine{'-', a[i]})
|
||||
i++
|
||||
}
|
||||
for j < n {
|
||||
ops = append(ops, diffLine{'+', b[j]})
|
||||
j++
|
||||
}
|
||||
|
||||
const ctxLines = 2
|
||||
show := make([]bool, len(ops))
|
||||
for idx, op := range ops {
|
||||
if op.kind != ' ' {
|
||||
lo := idx - ctxLines
|
||||
if lo < 0 {
|
||||
lo = 0
|
||||
}
|
||||
hi := idx + ctxLines
|
||||
if hi >= len(ops) {
|
||||
hi = len(ops) - 1
|
||||
}
|
||||
for k := lo; k <= hi; k++ {
|
||||
show[k] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
skipping := false
|
||||
for idx, op := range ops {
|
||||
if !show[idx] {
|
||||
if !skipping && out.Len() > 0 {
|
||||
out.WriteString(" ...\n")
|
||||
skipping = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
skipping = false
|
||||
out.WriteByte(op.kind)
|
||||
out.WriteByte(' ')
|
||||
out.WriteString(op.text)
|
||||
out.WriteByte('\n')
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue