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
449
internal/builder/builder.go
Normal file
449
internal/builder/builder.go
Normal file
|
|
@ -0,0 +1,449 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
// Options configures a rud config builder session.
|
||||
type Options struct {
|
||||
ConfigPath string
|
||||
ForceNew bool
|
||||
Plain bool
|
||||
NoColor bool
|
||||
In io.Reader
|
||||
Out io.Writer
|
||||
}
|
||||
|
||||
// Run launches the interactive configuration builder CLI.
|
||||
func Run(ctx context.Context, opts Options) error {
|
||||
path := strings.TrimSpace(opts.ConfigPath)
|
||||
if path == "" {
|
||||
path = "rud.json"
|
||||
}
|
||||
|
||||
ui := NewUI(opts.In, opts.Out, opts.Plain, opts.NoColor)
|
||||
|
||||
var cfg *config.Config
|
||||
var originalRaw []byte
|
||||
var baselineJSON string
|
||||
isNewFile := false
|
||||
|
||||
_, statErr := os.Stat(path)
|
||||
fileExists := statErr == nil
|
||||
|
||||
if !opts.ForceNew && fileExists {
|
||||
loaded, raw, loadErr := config.LoadForEdit(path)
|
||||
if loadErr != nil {
|
||||
ui.Error(fmt.Sprintf("Could not load %s: %v", path, loadErr))
|
||||
recOpts := []Option{
|
||||
{Label: "Start a new config from a template", Description: "Existing file will not be modified until you Save"},
|
||||
{Label: "Exit"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Config Load Error", "", recOpts, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == 1 {
|
||||
return nil
|
||||
}
|
||||
isNewFile = true
|
||||
} else {
|
||||
cfg = loaded
|
||||
originalRaw = raw
|
||||
if b, err := config.MarshalConfig(cfg); err == nil {
|
||||
baselineJSON = string(b)
|
||||
}
|
||||
ui.Ok(fmt.Sprintf("Loaded existing configuration from %s", path))
|
||||
}
|
||||
} else {
|
||||
isNewFile = true
|
||||
}
|
||||
|
||||
if cfg == nil {
|
||||
starter, ok, err := newConfigStarterFlow(ctx, ui, path, fileExists)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cfg = starter
|
||||
}
|
||||
|
||||
return runSectionHub(ctx, ui, cfg, path, isNewFile, baselineJSON, originalRaw)
|
||||
}
|
||||
|
||||
func newConfigStarterFlow(ctx context.Context, ui *UI, path string, fileExists bool) (*config.Config, bool, error) {
|
||||
sub := fmt.Sprintf("Target file: %s", path)
|
||||
if fileExists {
|
||||
sub += " (will be overwritten only when you Save)"
|
||||
}
|
||||
opts := []Option{
|
||||
{Label: "Guided Quick-Start Wizard", Description: "Step-by-step setup for server, monitors, alerts, and theme"},
|
||||
{Label: "Default Demo Config", Description: "All 5 check methods + sample event + dark minimal page"},
|
||||
{Label: "Web & API Starter", Description: "HTTPS endpoints, DNS check, outage alert, grouped layout"},
|
||||
{Label: "Homelab / Infrastructure Starter", Description: "Gateway ping, DB TCP, reverse proxy HTTP, disk space cmd"},
|
||||
{Label: "Blank Minimal Config", Description: "Empty monitors & events with a clean status page scaffold"},
|
||||
{Label: "Exit"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Create New RUD Configuration", sub, opts, 0)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
cfg := BlankMinimalConfig()
|
||||
if err := runQuickStartWizard(ctx, ui, &cfg); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return &cfg, true, nil
|
||||
case 1:
|
||||
cfg := config.DefaultConfig()
|
||||
return &cfg, true, nil
|
||||
case 2:
|
||||
cfg := WebAPIStarterConfig()
|
||||
return &cfg, true, nil
|
||||
case 3:
|
||||
cfg := HomelabStarterConfig()
|
||||
return &cfg, true, nil
|
||||
case 4:
|
||||
cfg := BlankMinimalConfig()
|
||||
return &cfg, true, nil
|
||||
default:
|
||||
return nil, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func runQuickStartWizard(ctx context.Context, ui *UI, cfg *config.Config) error {
|
||||
ui.Header("Quick-Start Wizard (1/4): Server", "Configure the single HTTP endpoint served by RUD")
|
||||
listen, err := ui.PromptString("Listen address", cfg.Server.Listen, "host:port or :8080", false, requireNonEmpty("listen"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Server.Listen = listen
|
||||
|
||||
endpoint, err := ui.PromptString("HTTP endpoint path", cfg.Server.Endpoint, "must start with /", false, requireNonEmpty("endpoint"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !strings.HasPrefix(endpoint, "/") {
|
||||
endpoint = "/" + endpoint
|
||||
}
|
||||
cfg.Server.Endpoint = endpoint
|
||||
|
||||
ui.Header("Quick-Start Wizard (2/4): Monitors", "Add one or more services to monitor")
|
||||
for {
|
||||
added, err := addMonitorFlow(ctx, ui, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !added && len(cfg.Monitors) == 0 {
|
||||
break
|
||||
}
|
||||
more, err := ui.Confirm("Add another monitor?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
ui.Header("Quick-Start Wizard (3/4): Alerts & Events", "Optional outbound webhooks or commands on outage/recovery")
|
||||
addEv, err := ui.Confirm("Configure an alert event rule now?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if addEv {
|
||||
if err := addEventFlow(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ui.Header("Quick-Start Wizard (4/4): Status Page & Theme", "Customize your public status page")
|
||||
title, err := ui.PromptString("Page title", cfg.Page.Title, "shown in browser tab & header", false, requireNonEmpty("title"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Page.Title = title
|
||||
for i := range cfg.Page.Elements {
|
||||
if cfg.Page.Elements[i].Type == "header" {
|
||||
cfg.Page.Elements[i].Title = title
|
||||
}
|
||||
}
|
||||
|
||||
pickTheme, err := ui.Confirm("Choose a color theme preset?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if pickTheme {
|
||||
if err := applyThemePresetFlow(ui, &cfg.Page); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ui.Ok("Quick-start setup complete! Opening the configuration hub for further edits or saving.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func runSectionHub(ctx context.Context, ui *UI, cfg *config.Config, path string, isNewFile bool, baselineJSON string, originalRaw []byte) error {
|
||||
for {
|
||||
currBytes, err := config.MarshalConfig(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
currJSON := string(currBytes)
|
||||
dirty := isNewFile || currJSON != baselineJSON
|
||||
|
||||
lintRaw := currBytes
|
||||
if !dirty && len(originalRaw) > 0 {
|
||||
lintRaw = originalRaw
|
||||
}
|
||||
valErr, lintIssues := evaluateConfigHealth(cfg, lintRaw)
|
||||
|
||||
statusBadge := ui.Green("[saved]")
|
||||
if isNewFile {
|
||||
statusBadge = ui.Yellow("[new unsaved]")
|
||||
} else if dirty {
|
||||
statusBadge = ui.Yellow("[modified]")
|
||||
}
|
||||
|
||||
var healthLine string
|
||||
if valErr != nil {
|
||||
healthLine = ui.Red("✗ Invalid: " + valErr.Error())
|
||||
} else if len(lintIssues) > 0 {
|
||||
healthLine = ui.Yellow(fmt.Sprintf("! Valid with %d warning(s)", len(lintIssues)))
|
||||
} else {
|
||||
healthLine = ui.Green("✓ Valid (0 warnings)")
|
||||
}
|
||||
|
||||
sub := fmt.Sprintf("File: %s %s\nSummary: %d monitor(s) | %d event(s) | %d page element(s)\nHealth: %s",
|
||||
path, statusBadge, len(cfg.Monitors), len(cfg.Events), len(cfg.Page.Elements), healthLine)
|
||||
|
||||
opts := []Option{
|
||||
{Label: fmt.Sprintf("Monitors (%d)", len(cfg.Monitors)), Description: "Add, edit, reorder, duplicate, delete, or test checks live"},
|
||||
{Label: fmt.Sprintf("Events & Alerts (%d)", len(cfg.Events)), Description: "Alert recipes, nested AND/OR condition tree, webhooks & commands"},
|
||||
{Label: fmt.Sprintf("Page & Theme (%d elements)", len(cfg.Page.Elements)), Description: "Theme presets, colors, layout elements & display flags"},
|
||||
{Label: "Server Settings", Description: fmt.Sprintf("listen=%s endpoint=%s refresh=%s", cfg.Server.Listen, cfg.Server.Endpoint, cfg.Server.RefreshInterval.Std())},
|
||||
{Label: "Defaults & Storage", Description: fmt.Sprintf("interval=%s timeout=%s history=%d", cfg.Defaults.Interval.Std(), cfg.Defaults.Timeout.Std(), cfg.Storage.HistorySize)},
|
||||
{Label: "Test Monitors Live", Description: "Run health checks immediately against live targets"},
|
||||
{Label: "Validate & Preview JSON / Diff", Description: "Check errors/warnings, view changes, or inspect full JSON"},
|
||||
{Label: "Save", Description: fmt.Sprintf("Write atomically to %s", path)},
|
||||
{Label: "Save As...", Description: "Save configuration to a different file path"},
|
||||
{Label: "Exit"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("RUD Config Builder", sub, opts, 0)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrAborted) {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !ok || idx == 9 {
|
||||
if !dirty {
|
||||
return nil
|
||||
}
|
||||
exitOpts := []Option{
|
||||
{Label: "Save & Exit", Description: "Validate and write changes to " + path},
|
||||
{Label: "Discard changes & Exit"},
|
||||
{Label: "Cancel (return to hub)"},
|
||||
}
|
||||
eIdx, eOK, eErr := ui.Select("Unsaved Changes", fmt.Sprintf("%s has unsaved changes.", path), exitOpts, 0)
|
||||
if eErr != nil {
|
||||
return eErr
|
||||
}
|
||||
if !eOK || eIdx == 2 {
|
||||
continue
|
||||
}
|
||||
if eIdx == 0 {
|
||||
saved, sErr := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, false)
|
||||
if sErr != nil {
|
||||
return sErr
|
||||
}
|
||||
if saved {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
if err := editMonitors(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 1:
|
||||
if err := editEvents(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 2:
|
||||
if err := editPage(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if err := editServer(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
if err := editDefaultsAndStorage(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 5:
|
||||
if len(cfg.Monitors) == 0 {
|
||||
ui.Warn("No monitors configured yet.")
|
||||
} else if err := testMonitorsMenu(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case 6:
|
||||
if err := previewAndValidateMenu(ui, cfg, baselineJSON, currJSON, lintRaw); err != nil {
|
||||
return err
|
||||
}
|
||||
case 7:
|
||||
if _, err := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case 8:
|
||||
if _, err := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func evaluateConfigHealth(cfg *config.Config, rawJSON []byte) (error, []config.LintIssue) {
|
||||
cloned, err := cfg.Clone()
|
||||
if err != nil {
|
||||
return err, nil
|
||||
}
|
||||
cloned.ApplyFallbacks()
|
||||
valErr := cloned.Validate()
|
||||
issues := cloned.Lint(rawJSON)
|
||||
return valErr, issues
|
||||
}
|
||||
|
||||
func previewAndValidateMenu(ui *UI, cfg *config.Config, baselineJSON, currJSON string, rawJSON []byte) error {
|
||||
valErr, issues := evaluateConfigHealth(cfg, rawJSON)
|
||||
ui.Header("Validation & Lint Report", "")
|
||||
if valErr != nil {
|
||||
ui.Error("Validation failed: " + valErr.Error())
|
||||
} else {
|
||||
ui.Ok("Configuration schema is valid.")
|
||||
}
|
||||
if len(issues) == 0 {
|
||||
ui.Ok("No lint warnings.")
|
||||
} else {
|
||||
ui.Warn(fmt.Sprintf("%d lint warning(s):", len(issues)))
|
||||
for _, iss := range issues {
|
||||
ui.Println(" - " + iss.String())
|
||||
}
|
||||
}
|
||||
|
||||
opts := []Option{
|
||||
{Label: "Show changes diff"},
|
||||
{Label: "Show full JSON preview"},
|
||||
{Label: "Back"},
|
||||
}
|
||||
for {
|
||||
idx, ok, err := ui.Select("Preview", "", opts, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == 2 {
|
||||
return nil
|
||||
}
|
||||
switch idx {
|
||||
case 0:
|
||||
ui.Header("Changes Diff", "")
|
||||
if baselineJSON == "" {
|
||||
ui.Println(FormatDiff("", currJSON))
|
||||
} else {
|
||||
ui.Println(FormatDiff(baselineJSON, currJSON))
|
||||
}
|
||||
case 1:
|
||||
ui.Header("Generated JSON Preview", "")
|
||||
ui.Println(currJSON)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func saveConfigFlow(ui *UI, cfg *config.Config, activePath *string, isNewFile *bool, baselineJSON *string, originalRaw *[]byte, saveAs bool) (bool, error) {
|
||||
targetPath := *activePath
|
||||
if saveAs {
|
||||
p, err := ui.PromptString("Save As path", targetPath, "file path", false, requireNonEmpty("path"))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
targetPath = p
|
||||
}
|
||||
|
||||
currBytes, err := config.MarshalConfig(cfg)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
valErr, issues := evaluateConfigHealth(cfg, currBytes)
|
||||
if valErr != nil {
|
||||
ui.Error("Validation error: " + valErr.Error())
|
||||
force, cErr := ui.Confirm("Configuration has validation errors. Save anyway?", false)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
if !force {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
if len(issues) > 0 {
|
||||
ui.Warn(fmt.Sprintf("%d lint warning(s):", len(issues)))
|
||||
for _, iss := range issues {
|
||||
ui.Println(" - " + iss.String())
|
||||
}
|
||||
cont, cErr := ui.Confirm("Proceed with saving?", true)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
if !cont {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
makeBackup := false
|
||||
if _, statErr := os.Stat(targetPath); statErr == nil {
|
||||
ans, cErr := ui.Confirm(fmt.Sprintf("Create backup (%s.bak) before overwriting?", targetPath), true)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
makeBackup = ans
|
||||
}
|
||||
|
||||
bakPath, err := config.SaveConfigWithBackup(targetPath, cfg, makeBackup)
|
||||
if err != nil {
|
||||
ui.Error(fmt.Sprintf("Save failed: %v", err))
|
||||
return false, nil
|
||||
}
|
||||
|
||||
*activePath = targetPath
|
||||
*isNewFile = false
|
||||
*baselineJSON = string(currBytes)
|
||||
*originalRaw = currBytes
|
||||
|
||||
ui.Ok("Saved configuration to " + targetPath)
|
||||
if bakPath != "" {
|
||||
ui.Info("Created backup at " + bakPath)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
355
internal/builder/builder_test.go
Normal file
355
internal/builder/builder_test.go
Normal file
|
|
@ -0,0 +1,355 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func runScripted(t *testing.T, opts Options, lines []string) string {
|
||||
t.Helper()
|
||||
var out bytes.Buffer
|
||||
opts.Plain = true
|
||||
opts.NoColor = true
|
||||
opts.In = strings.NewReader(strings.Join(lines, "\n") + "\n")
|
||||
opts.Out = &out
|
||||
|
||||
if err := Run(context.Background(), opts); err != nil {
|
||||
t.Fatalf("builder.Run failed: %v\n--- Output ---\n%s", err, out.String())
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func TestStarterTemplatesValidAndLintClean(t *testing.T) {
|
||||
blank := BlankMinimalConfig()
|
||||
if err := blank.Validate(); err != nil {
|
||||
t.Fatalf("BlankMinimalConfig invalid: %v", err)
|
||||
}
|
||||
|
||||
for name, cfg := range map[string]config.Config{
|
||||
"WebAPIStarter": WebAPIStarterConfig(),
|
||||
"HomelabStarter": HomelabStarterConfig(),
|
||||
} {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Fatalf("%s invalid: %v", name, err)
|
||||
}
|
||||
raw, err := config.MarshalConfig(&cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("%s marshal failed: %v", name, err)
|
||||
}
|
||||
if issues := cfg.Lint(raw); len(issues) != 0 {
|
||||
t.Fatalf("%s has lint issues: %v", name, issues)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderNewConfigFromStarter(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "sub", "rud.json")
|
||||
|
||||
// 3 = Web & API Starter, 8 = Save, 10 = Exit
|
||||
out := runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"3",
|
||||
"8",
|
||||
"10",
|
||||
})
|
||||
|
||||
if !strings.Contains(out, "Saved configuration") {
|
||||
t.Fatalf("expected save confirmation in output:\n%s", out)
|
||||
}
|
||||
|
||||
loaded, created, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit on built config failed: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Fatalf("expected file to already exist")
|
||||
}
|
||||
if loaded.Page.Title != "API & Web Status" || len(loaded.Monitors) != 3 {
|
||||
t.Fatalf("unexpected loaded config: title=%q monitors=%d", loaded.Page.Title, len(loaded.Monitors))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderEditAddLiveTestRenameDeleteWithSyncAndBackup(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
cfgPath := filepath.Join(t.TempDir(), "rud.json")
|
||||
seed := config.DefaultConfig()
|
||||
// Use explicit monitor IDs in monitor_group so we test page reference sync as well
|
||||
seed.Page.Elements[3].Monitors = []string{"rud-http", "rud-tcp"}
|
||||
if err := config.SaveConfig(cfgPath, &seed); err != nil {
|
||||
t.Fatalf("seed SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
out := runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"1", // Monitors
|
||||
// Add HTTP monitor and live test it
|
||||
"1", // Add monitor
|
||||
"test-http",
|
||||
"Test HTTP",
|
||||
"Local test endpoint",
|
||||
"2", // Method: http
|
||||
ts.URL, // URL
|
||||
"", // HTTP verb (GET)
|
||||
"200", // Expected status
|
||||
"^ok$", // Body regex
|
||||
"n", // Overrides? no
|
||||
"y", // Test live now? yes
|
||||
|
||||
// Rename rud-http -> core-http and sync refs
|
||||
"2", // Edit monitor
|
||||
"1", // rud-http
|
||||
"1", // Edit identity & metadata
|
||||
"core-http",
|
||||
"", // keep name
|
||||
"", // keep desc
|
||||
"", // keep link
|
||||
"y", // Sync references? yes
|
||||
"6", // Done editing monitor
|
||||
|
||||
// Delete rud-tcp and clean dangling refs
|
||||
"6", // Delete monitor
|
||||
"2", // rud-tcp
|
||||
"y", // Confirm delete
|
||||
"y", // Clean dangling refs
|
||||
|
||||
"7", // Back to main hub
|
||||
"8", // Save
|
||||
"y", // Create .bak backup
|
||||
"10", // Exit
|
||||
})
|
||||
|
||||
if !strings.Contains(out, "test-http") || !strings.Contains(out, "UP") {
|
||||
t.Fatalf("expected live test output for test-http UP, got:\n%s", out)
|
||||
}
|
||||
|
||||
bakBytes, err := os.ReadFile(cfgPath + ".bak")
|
||||
if err != nil {
|
||||
t.Fatalf("expected backup file at %s.bak: %v", cfgPath, err)
|
||||
}
|
||||
if !strings.Contains(string(bakBytes), `"rud-http"`) {
|
||||
t.Fatalf("backup did not preserve original monitor ID")
|
||||
}
|
||||
|
||||
reloaded, _, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit failed: %v", err)
|
||||
}
|
||||
|
||||
byID := make(map[string]config.MonitorConfig)
|
||||
for _, m := range reloaded.Monitors {
|
||||
byID[m.ID] = m
|
||||
}
|
||||
if _, ok := byID["core-http"]; !ok {
|
||||
t.Fatalf("expected renamed monitor 'core-http' in config")
|
||||
}
|
||||
if _, ok := byID["test-http"]; !ok {
|
||||
t.Fatalf("expected added monitor 'test-http' in config")
|
||||
}
|
||||
if _, ok := byID["rud-tcp"]; ok {
|
||||
t.Fatalf("expected deleted monitor 'rud-tcp' to be removed")
|
||||
}
|
||||
|
||||
evMons := reloaded.Events[0].Condition.Conditions[0].Monitors
|
||||
if len(evMons) != 1 || evMons[0] != "core-http" {
|
||||
t.Fatalf("expected event condition monitors to sync to [core-http], got %v", evMons)
|
||||
}
|
||||
pgMons := reloaded.Page.Elements[3].Monitors
|
||||
if len(pgMons) != 1 || pgMons[0] != "core-http" {
|
||||
t.Fatalf("expected page group monitors to sync to [core-http], got %v", pgMons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderRecursiveEventTreeAndDiscordPreset(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "rud.json")
|
||||
seed := BlankMinimalConfig()
|
||||
seed.Monitors = []config.MonitorConfig{
|
||||
{ID: "api", Name: "API", Method: "http", URL: "http://127.0.0.1:8080/health"},
|
||||
}
|
||||
seed.Events = []config.EventConfig{
|
||||
{
|
||||
ID: "api-alert",
|
||||
Name: "API Alert",
|
||||
Condition: config.EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"api"},
|
||||
Match: "all",
|
||||
State: "down",
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{Type: "command", Command: "echo alert", Shell: true},
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := config.SaveConfig(cfgPath, &seed); err != nil {
|
||||
t.Fatalf("seed SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
_ = runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"2", // Events & Alerts
|
||||
"2", // Edit event rule
|
||||
"1", // api-alert
|
||||
"2", // Edit condition tree
|
||||
"1", // Select root leaf node
|
||||
"2", // Wrap in new AND/OR group
|
||||
"1", // or
|
||||
"1", // Select new OR group node
|
||||
"2", // Add child leaf condition
|
||||
"2", // metric
|
||||
"1", // * (All monitors)
|
||||
"2", // any
|
||||
"2", // latency_ms
|
||||
"3", // >
|
||||
"250",
|
||||
"1m",
|
||||
"4", // Done editing condition tree
|
||||
"3", // Edit alert actions
|
||||
"1", // Add action
|
||||
"1", // Webhook from preset
|
||||
"1", // Discord Webhook
|
||||
"https://discord.com/api/webhooks/123456/token",
|
||||
"4", // Done editing actions
|
||||
"5", // Done editing event
|
||||
"5", // Back to main hub
|
||||
"8", // Save
|
||||
"n", // No backup
|
||||
"10", // Exit
|
||||
})
|
||||
|
||||
reloaded, raw, err := config.LoadForEdit(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadForEdit failed: %v", err)
|
||||
}
|
||||
if err := reloaded.Validate(); err != nil {
|
||||
t.Fatalf("reloaded config invalid: %v", err)
|
||||
}
|
||||
if issues := reloaded.Lint(raw); len(issues) != 0 {
|
||||
t.Fatalf("reloaded config has lint issues: %v", issues)
|
||||
}
|
||||
ev := reloaded.Events[0]
|
||||
if ev.Condition.Operator != "or" || len(ev.Condition.Conditions) != 2 {
|
||||
t.Fatalf("expected OR group with 2 children, got %+v", ev.Condition)
|
||||
}
|
||||
if ev.Condition.Conditions[1].Metric != "latency_ms" || ev.Condition.Conditions[1].Value != 250 {
|
||||
t.Fatalf("unexpected second child condition: %+v", ev.Condition.Conditions[1])
|
||||
}
|
||||
if len(ev.Actions) != 2 || !strings.Contains(ev.Actions[1].URL, "discord.com") {
|
||||
t.Fatalf("expected Discord webhook action to be added, got %+v", ev.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderThemePresetReorderAndUnsavedGuard(t *testing.T) {
|
||||
cfgPath := filepath.Join(t.TempDir(), "rud.json")
|
||||
seed := config.DefaultConfig()
|
||||
if err := config.SaveConfig(cfgPath, &seed); err != nil {
|
||||
t.Fatalf("seed SaveConfig failed: %v", err)
|
||||
}
|
||||
|
||||
_ = runScripted(t, Options{ConfigPath: cfgPath}, []string{
|
||||
"3", // Page & Theme
|
||||
"2", // Apply theme preset
|
||||
"4", // Nord
|
||||
"4", // Manage page elements
|
||||
"4", // Reorder page elements
|
||||
"1", // header
|
||||
"2", // Move down
|
||||
"0", // Done reordering
|
||||
"6", // Back from elements
|
||||
"5", // Back to main hub
|
||||
"8", // Save
|
||||
"n", // No backup
|
||||
|
||||
// Make an unsaved modification and test exit guard
|
||||
"3", // Page & Theme
|
||||
"1", // Page HTML title
|
||||
"Unsaved Title", // New title
|
||||
"5", // Back to main hub
|
||||
"10", // Exit
|
||||
"3", // Cancel exit guard
|
||||
"10", // Exit again
|
||||
"2", // Discard changes & Exit
|
||||
})
|
||||
|
||||
reloaded, _, err := config.LoadOrInit(cfgPath, false)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrInit failed: %v", err)
|
||||
}
|
||||
if reloaded.Page.Theme.BgColor != "#2e3440" {
|
||||
t.Fatalf("expected Nord theme BgColor #2e3440, got %q", reloaded.Page.Theme.BgColor)
|
||||
}
|
||||
if reloaded.Page.Elements[0].Type != "status_banner" || reloaded.Page.Elements[1].Type != "header" {
|
||||
t.Fatalf("expected header moved after status_banner, got [%s, %s]",
|
||||
reloaded.Page.Elements[0].Type, reloaded.Page.Elements[1].Type)
|
||||
}
|
||||
if reloaded.Page.Title != "R u ded?" {
|
||||
t.Fatalf("expected discarded title change not to persist, got %q", reloaded.Page.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderQuickStartWizardPreviewAndSaveAs(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
initialPath := filepath.Join(tmpDir, "initial.json")
|
||||
saveAsPath := filepath.Join(tmpDir, "wizard-out.json")
|
||||
|
||||
out := runScripted(t, Options{ConfigPath: initialPath}, []string{
|
||||
"1", // Guided Quick-Start Wizard
|
||||
"", // Listen (:8080)
|
||||
"", // Endpoint (/)
|
||||
// Monitor 1
|
||||
"wiz-cmd",
|
||||
"Wizard Cmd",
|
||||
"", // description
|
||||
"6", // cmd
|
||||
"echo ok",
|
||||
"y", // shell
|
||||
"0", // expected exit code
|
||||
"^ok$",
|
||||
"n", // overrides
|
||||
"y", // test live
|
||||
"n", // add another monitor
|
||||
"n", // add event rule
|
||||
"My Wizard Status",
|
||||
"y", // pick theme preset
|
||||
"2", // Clean Light
|
||||
// Hub: Validate & Preview JSON / Diff
|
||||
"7",
|
||||
"1", // diff
|
||||
"2", // JSON preview
|
||||
"3", // back
|
||||
// Save As
|
||||
"9",
|
||||
saveAsPath,
|
||||
"10", // Exit
|
||||
})
|
||||
|
||||
if !strings.Contains(out, `"My Wizard Status"`) {
|
||||
t.Fatalf("expected preview JSON to contain new title, got:\n%s", out)
|
||||
}
|
||||
if _, err := os.Stat(initialPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected initialPath not to be written when using Save As")
|
||||
}
|
||||
|
||||
loaded, raw, err := config.LoadForEdit(saveAsPath)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadForEdit on Save As file failed: %v", err)
|
||||
}
|
||||
if err := loaded.Validate(); err != nil {
|
||||
t.Fatalf("saved wizard config invalid: %v", err)
|
||||
}
|
||||
if issues := loaded.Lint(raw); len(issues) != 0 {
|
||||
t.Fatalf("saved wizard config has lint issues: %v", issues)
|
||||
}
|
||||
if loaded.Page.Theme.BgColor != "#f8fafc" || len(loaded.Monitors) != 1 || loaded.Monitors[0].ID != "wiz-cmd" {
|
||||
t.Fatalf("unexpected wizard config: theme=%s monitors=%v", loaded.Page.Theme.BgColor, loaded.Monitors)
|
||||
}
|
||||
}
|
||||
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()
|
||||
}
|
||||
1052
internal/builder/editors_events.go
Normal file
1052
internal/builder/editors_events.go
Normal file
File diff suppressed because it is too large
Load diff
841
internal/builder/editors_monitors.go
Normal file
841
internal/builder/editors_monitors.go
Normal file
|
|
@ -0,0 +1,841 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func editMonitors(ctx context.Context, ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("%d monitor(s) configured", len(cfg.Monitors))
|
||||
if len(cfg.Monitors) > 0 {
|
||||
var ids []string
|
||||
for _, m := range cfg.Monitors {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
sub += ": " + strings.Join(ids, ", ")
|
||||
}
|
||||
|
||||
opts := []Option{
|
||||
{Label: "Add monitor", Description: "Create a new HTTP, TCP, Ping, DNS, or Cmd check"},
|
||||
}
|
||||
if len(cfg.Monitors) > 0 {
|
||||
opts = append(opts,
|
||||
Option{Label: "Edit monitor", Description: "Modify an existing monitor's settings"},
|
||||
Option{Label: "Test monitor(s) live", Description: "Run checks immediately against live targets"},
|
||||
Option{Label: "Duplicate monitor", Description: "Clone an existing monitor with a new ID"},
|
||||
Option{Label: "Reorder monitors", Description: "Move a monitor up or down"},
|
||||
Option{Label: "Delete monitor", Description: "Remove a monitor (with reference cleanup)"},
|
||||
)
|
||||
}
|
||||
opts = append(opts, Option{Label: "Back to main hub"})
|
||||
|
||||
idx, ok, err := ui.Select("Monitors", sub, opts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Back to main hub" {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch opts[idx].Label {
|
||||
case "Add monitor":
|
||||
if _, err := addMonitorFlow(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Edit monitor":
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to edit")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
if err := editSingleMonitor(ctx, ui, cfg, mIdx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "Test monitor(s) live":
|
||||
if err := testMonitorsMenu(ctx, ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Duplicate monitor":
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to duplicate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
cp := cloneMonitor(cfg.Monitors[mIdx])
|
||||
defID := uniqueMonitorID(cfg, cp.ID+"-copy")
|
||||
newID, err := ui.PromptString("New monitor ID", defID, "unique identifier", false, validateNewMonitorID(cfg, -1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cp.ID = newID
|
||||
cp.Name = cp.Name + " (Copy)"
|
||||
cfg.Monitors = append(cfg.Monitors, cp)
|
||||
ui.Ok(fmt.Sprintf("Duplicated monitor %q as %q.", cfg.Monitors[mIdx].ID, cp.ID))
|
||||
}
|
||||
case "Reorder monitors":
|
||||
if err := reorderMonitors(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Delete monitor":
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to delete")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
target := cfg.Monitors[mIdx]
|
||||
yes, err := ui.Confirm(fmt.Sprintf("Delete monitor %q (%s)?", target.ID, target.Method), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if yes {
|
||||
cfg.Monitors = append(cfg.Monitors[:mIdx], cfg.Monitors[mIdx+1:]...)
|
||||
ui.Ok(fmt.Sprintf("Deleted monitor %q.", target.ID))
|
||||
evRefs, pgRefs := findMonitorRefs(cfg, target.ID)
|
||||
if len(evRefs) > 0 || len(pgRefs) > 0 {
|
||||
ui.Warn(fmt.Sprintf("Found references to %q in %d event(s) and %d page group(s).", target.ID, len(evRefs), len(pgRefs)))
|
||||
clean, err := ui.Confirm("Remove dangling references automatically?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if clean {
|
||||
removeMonitorRefs(cfg, target.ID)
|
||||
ui.Ok("Cleaned up dangling monitor references.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pickMonitor(ui *UI, monitors []config.MonitorConfig, title string) (int, bool, error) {
|
||||
opts := make([]Option, len(monitors))
|
||||
for i, m := range monitors {
|
||||
opts[i] = Option{
|
||||
Label: fmt.Sprintf("%s (%s)", m.ID, strings.ToUpper(m.Method)),
|
||||
Description: fmt.Sprintf("%s — %s", m.Name, m.DisplayTarget()),
|
||||
}
|
||||
}
|
||||
return ui.Select(title, "", opts, -1)
|
||||
}
|
||||
|
||||
func testMonitorsMenu(ctx context.Context, ui *UI, cfg *config.Config) error {
|
||||
opts := []Option{
|
||||
{Label: "Test all monitors", Description: fmt.Sprintf("Run all %d monitor(s) concurrently", len(cfg.Monitors))},
|
||||
{Label: "Test a specific monitor"},
|
||||
{Label: "Back"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Test Monitors Live", "", opts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == 2 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var ids []string
|
||||
if idx == 1 {
|
||||
mIdx, mOK, err := pickMonitor(ui, cfg.Monitors, "Select monitor to test")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !mOK {
|
||||
return nil
|
||||
}
|
||||
ids = []string{cfg.Monitors[mIdx].ID}
|
||||
}
|
||||
|
||||
ui.Info("Running live health checks...")
|
||||
results, err := RunLiveTests(ctx, cfg, ids, true)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return nil
|
||||
}
|
||||
ui.Println()
|
||||
PrintLiveTestTable(ui.out, results, ui.color)
|
||||
return nil
|
||||
}
|
||||
|
||||
func reorderMonitors(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
if len(cfg.Monitors) < 2 {
|
||||
ui.Info("Need at least 2 monitors to reorder.")
|
||||
return nil
|
||||
}
|
||||
mIdx, ok, err := pickMonitor(ui, cfg.Monitors, "Pick a monitor to move (Esc/0 when done)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
dirOpts := []Option{
|
||||
{Label: "Move up"},
|
||||
{Label: "Move down"},
|
||||
{Label: "Cancel"},
|
||||
}
|
||||
dIdx, dOK, err := ui.Select("Move "+cfg.Monitors[mIdx].ID, "", dirOpts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !dOK || dIdx == 2 {
|
||||
continue
|
||||
}
|
||||
if dIdx == 0 && mIdx > 0 {
|
||||
cfg.Monitors[mIdx-1], cfg.Monitors[mIdx] = cfg.Monitors[mIdx], cfg.Monitors[mIdx-1]
|
||||
} else if dIdx == 1 && mIdx < len(cfg.Monitors)-1 {
|
||||
cfg.Monitors[mIdx+1], cfg.Monitors[mIdx] = cfg.Monitors[mIdx], cfg.Monitors[mIdx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addMonitorFlow(ctx context.Context, ui *UI, cfg *config.Config) (bool, error) {
|
||||
ui.Header("Add Monitor", "Step through the required fields for your new check")
|
||||
|
||||
defID := uniqueMonitorID(cfg, fmt.Sprintf("mon-%d", len(cfg.Monitors)+1))
|
||||
id, err := ui.PromptString("Monitor ID", defID, "unique slug, no spaces", false, validateNewMonitorID(cfg, -1))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
name, err := ui.PromptString("Display name", id, "friendly name shown on status page", false, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
desc, err := ui.PromptString("Description (optional)", "", "short subtitle", true, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
methodOpts := []Option{
|
||||
{Label: "https", Description: "HTTPS endpoint check (status code, headers, body regex, TLS)"},
|
||||
{Label: "http", Description: "HTTP endpoint check"},
|
||||
{Label: "tcp", Description: "TCP socket handshake (host:port)"},
|
||||
{Label: "ping", Description: "ICMP echo reachability & RTT"},
|
||||
{Label: "dns", Description: "DNS record lookup & validation"},
|
||||
{Label: "cmd", Description: "Custom shell command or script"},
|
||||
}
|
||||
mIdx, mOK, err := ui.Select("Check Method", "Choose protocol/method for "+id, methodOpts, 0)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !mOK {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
mon := config.MonitorConfig{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Method: methodOpts[mIdx].Label,
|
||||
}
|
||||
|
||||
if err := editMethodSpecificFields(ui, &mon, true); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
adv, err := ui.Confirm("Configure link or per-monitor timing overrides?", false)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if adv {
|
||||
if err := editMonitorMetadataAndOverrides(ui, &mon); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
cfg.Monitors = append(cfg.Monitors, mon)
|
||||
ui.Ok(fmt.Sprintf("Added monitor %q (%s: %s).", mon.ID, mon.Method, mon.DisplayTarget()))
|
||||
|
||||
runTest, err := ui.Confirm("Test this monitor live now?", true)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
if runTest {
|
||||
results, tErr := RunLiveTests(ctx, cfg, []string{mon.ID}, true)
|
||||
if tErr != nil {
|
||||
ui.Error(tErr.Error())
|
||||
} else {
|
||||
ui.Println()
|
||||
PrintLiveTestTable(ui.out, results, ui.color)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func editSingleMonitor(ctx context.Context, ui *UI, cfg *config.Config, monIdx int) error {
|
||||
for {
|
||||
mon := &cfg.Monitors[monIdx]
|
||||
sub := fmt.Sprintf("Method: %s | Target: %s", strings.ToUpper(mon.Method), mon.DisplayTarget())
|
||||
opts := []Option{
|
||||
{Label: "Edit identity & metadata", Description: fmt.Sprintf("id=%s, name=%q", mon.ID, mon.Name)},
|
||||
{Label: "Change check method", Description: fmt.Sprintf("current: %s", mon.Method)},
|
||||
{Label: "Edit method-specific settings", Description: mon.DisplayTarget()},
|
||||
{Label: "Edit timing & retry overrides", Description: formatMonitorOverrides(*mon)},
|
||||
{Label: "Test this monitor live"},
|
||||
{Label: "Done"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Edit Monitor: "+mon.ID, sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
oldID := mon.ID
|
||||
newID, err := ui.PromptString("Monitor ID", oldID, "unique ID", false, validateNewMonitorID(cfg, monIdx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newName, err := ui.PromptString("Display name", mon.Name, "", false, requireNonEmpty("name"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newDesc, err := ui.PromptString("Description", mon.Description, "optional", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newLink, err := ui.PromptString("Link URL", mon.Link, "optional clickable URL", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ID = newID
|
||||
mon.Name = newName
|
||||
mon.Description = newDesc
|
||||
mon.Link = newLink
|
||||
|
||||
if newID != oldID {
|
||||
evRefs, pgRefs := findMonitorRefs(cfg, oldID)
|
||||
if len(evRefs) > 0 || len(pgRefs) > 0 {
|
||||
ui.Warn(fmt.Sprintf("Found references to %q in %d event(s) and %d page group(s).", oldID, len(evRefs), len(pgRefs)))
|
||||
syncRefs, err := ui.Confirm(fmt.Sprintf("Update those references from %q to %q?", oldID, newID), true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if syncRefs {
|
||||
renameMonitorRefs(cfg, oldID, newID)
|
||||
ui.Ok(fmt.Sprintf("Updated references to %q.", newID))
|
||||
}
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
methodOpts := []Option{
|
||||
{Label: "https"}, {Label: "http"}, {Label: "tcp"}, {Label: "ping"}, {Label: "dns"}, {Label: "cmd"},
|
||||
}
|
||||
mIdx, mOK, err := ui.Select("Select check method", "", methodOpts, -1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
mon.Method = methodOpts[mIdx].Label
|
||||
if err := editMethodSpecificFields(ui, mon, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
if err := editMethodSpecificFields(ui, mon, false); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if err := editMonitorOverrides(ui, mon); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
results, tErr := RunLiveTests(ctx, cfg, []string{mon.ID}, true)
|
||||
if tErr != nil {
|
||||
ui.Error(tErr.Error())
|
||||
} else {
|
||||
ui.Println()
|
||||
PrintLiveTestTable(ui.out, results, ui.color)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editMonitorMetadataAndOverrides(ui *UI, mon *config.MonitorConfig) error {
|
||||
link, err := ui.PromptString("Clickable link URL (optional)", mon.Link, "e.g. https://status.example.com", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Link = link
|
||||
return editMonitorOverrides(ui, mon)
|
||||
}
|
||||
|
||||
func editMonitorOverrides(ui *UI, mon *config.MonitorConfig) error {
|
||||
ui.Header("Monitor Overrides: "+mon.ID, "Leave at 0s / '-' to inherit global defaults")
|
||||
var err error
|
||||
if mon.Interval, err = ui.PromptDuration("Check interval override", mon.Interval, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if mon.Timeout, err = ui.PromptDuration("Timeout override", mon.Timeout, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if mon.Retries, err = ui.PromptOptionalInt("Retries override", mon.Retries, 0, 20); err != nil {
|
||||
return err
|
||||
}
|
||||
if mon.DegradedLatency, err = ui.PromptDuration("Degraded latency override", mon.DegradedLatency, true); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func editMethodSpecificFields(ui *UI, mon *config.MonitorConfig, quickAdd bool) error {
|
||||
method := strings.ToLower(strings.TrimSpace(mon.Method))
|
||||
switch method {
|
||||
case "http", "https":
|
||||
defURL := mon.URL
|
||||
if defURL == "" {
|
||||
defURL = method + "://"
|
||||
}
|
||||
u, err := ui.PromptString("Endpoint URL", defURL, "full http:// or https:// URL", false, validateHTTPURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.URL = u
|
||||
|
||||
defHTTPMethod := mon.HTTPMethod
|
||||
if defHTTPMethod == "" {
|
||||
defHTTPMethod = "GET"
|
||||
}
|
||||
hm, err := ui.PromptString("HTTP verb", defHTTPMethod, "GET, HEAD, POST, etc.", false, requireNonEmpty("http_method"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.HTTPMethod = strings.ToUpper(hm)
|
||||
|
||||
codes, err := promptIntSlice(ui, "Expected HTTP status codes", mon.ExpectedStatus, "comma-separated e.g. 200,204; '-' for any 2xx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ExpectedStatus = codes
|
||||
|
||||
reStr, err := ui.PromptString("Response body regex (optional)", mon.BodyRegex, "Go regexp", true, validateOptionalRegex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.BodyRegex = reStr
|
||||
|
||||
if !quickAdd {
|
||||
body, err := ui.PromptString("Request body (optional)", mon.Body, "", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Body = body
|
||||
|
||||
editHdrs, err := ui.Confirm("Edit custom request headers?", len(mon.Headers) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editHdrs {
|
||||
hdrs, err := ui.EditStringMap("HTTP Request Headers", mon.Headers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Headers = hdrs
|
||||
}
|
||||
}
|
||||
|
||||
if method == "https" || strings.HasPrefix(strings.ToLower(mon.URL), "https://") {
|
||||
skip, err := ui.Confirm("Ignore invalid/self-signed TLS certificates (insecure_skip_verify)?", mon.InsecureSkipVerify)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.InsecureSkipVerify = skip
|
||||
}
|
||||
|
||||
case "tcp":
|
||||
cur := mon.Target
|
||||
if cur == "" {
|
||||
cur = mon.Host
|
||||
}
|
||||
target, err := ui.PromptString("TCP Target", cur, "host:port (e.g. 127.0.0.1:5432)", false, requireNonEmpty("target"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Target = target
|
||||
|
||||
case "ping":
|
||||
cur := mon.Host
|
||||
if cur == "" {
|
||||
cur = mon.Target
|
||||
}
|
||||
host, err := ui.PromptString("Host or IP", cur, "e.g. 1.1.1.1", false, requireNonEmpty("host"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Host = host
|
||||
|
||||
curCount := mon.Count
|
||||
if curCount <= 0 {
|
||||
curCount = 1
|
||||
}
|
||||
cnt, err := ui.PromptInt("Echo packet count", curCount, 1, 20)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Count = cnt
|
||||
|
||||
priv, err := ui.Confirm("Prefer raw ICMP socket (privileged)?", mon.Privileged)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Privileged = priv
|
||||
|
||||
case "dns":
|
||||
cur := mon.Host
|
||||
if cur == "" {
|
||||
cur = mon.Target
|
||||
}
|
||||
host, err := ui.PromptString("Domain name to resolve", cur, "e.g. example.com", false, requireNonEmpty("host"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Host = host
|
||||
|
||||
recTypes := []Option{
|
||||
{Label: "A"}, {Label: "AAAA"}, {Label: "CNAME"}, {Label: "MX"}, {Label: "TXT"}, {Label: "NS"},
|
||||
}
|
||||
defIdx := 0
|
||||
for i, o := range recTypes {
|
||||
if strings.EqualFold(o.Label, mon.RecordType) {
|
||||
defIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
rIdx, rOK, err := ui.Select("DNS Record Type", "", recTypes, defIdx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rOK {
|
||||
mon.RecordType = recTypes[rIdx].Label
|
||||
} else if mon.RecordType == "" {
|
||||
mon.RecordType = "A"
|
||||
}
|
||||
|
||||
res, err := ui.PromptString("Custom DNS resolver (optional)", mon.Resolver, "e.g. 1.1.1.1:53", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Resolver = res
|
||||
|
||||
reStr, err := ui.PromptString("Expected record regex (optional)", mon.ExpectedRegex, "Go regexp", true, validateOptionalRegex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ExpectedRegex = reStr
|
||||
|
||||
case "cmd", "script", "command":
|
||||
cmdStr, err := ui.PromptString("Command", mon.Command, "executable or shell command", false, requireNonEmpty("command"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Command = cmdStr
|
||||
|
||||
sh, err := ui.Confirm("Execute via /bin/sh -c (shell)?", mon.Shell)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Shell = sh
|
||||
|
||||
if !sh && !quickAdd {
|
||||
editArgs, err := ui.Confirm("Edit command arguments?", len(mon.Args) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editArgs {
|
||||
args, err := ui.EditStringSlice("Command Arguments", "argument", mon.Args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Args = args
|
||||
}
|
||||
}
|
||||
|
||||
curExit := mon.ExpectedExitCode
|
||||
if curExit == nil && quickAdd {
|
||||
curExit = config.IntPtr(0)
|
||||
}
|
||||
exitCode, err := ui.PromptOptionalInt("Expected exit code", curExit, 0, 255)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.ExpectedExitCode = exitCode
|
||||
|
||||
reStr, err := ui.PromptString("Output regex (optional)", mon.OutputRegex, "Go regexp matched against stdout+stderr", true, validateOptionalRegex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.OutputRegex = reStr
|
||||
|
||||
if !quickAdd {
|
||||
wd, err := ui.PromptString("Working directory (optional)", mon.WorkingDir, "", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.WorkingDir = wd
|
||||
|
||||
editEnv, err := ui.Confirm("Edit environment variables?", len(mon.Env) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editEnv {
|
||||
env, err := ui.EditStringMap("Command Environment Variables", mon.Env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mon.Env = env
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNewMonitorID(cfg *config.Config, excludeIdx int) func(string) error {
|
||||
return func(id string) error {
|
||||
trimmed := strings.TrimSpace(id)
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("monitor id cannot be empty")
|
||||
}
|
||||
if trimmed == "*" {
|
||||
return fmt.Errorf("'*' is reserved as a wildcard")
|
||||
}
|
||||
if strings.ContainsAny(trimmed, " \t\r\n") {
|
||||
return fmt.Errorf("monitor id cannot contain whitespace")
|
||||
}
|
||||
for i, m := range cfg.Monitors {
|
||||
if i != excludeIdx && m.ID == trimmed {
|
||||
return fmt.Errorf("monitor id %q already exists", trimmed)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func validateHTTPURL(raw string) error {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) || u.Host == "" {
|
||||
return fmt.Errorf("enter a valid http:// or https:// URL with host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOptionalRegex(pattern string) error {
|
||||
if pattern == "" {
|
||||
return nil
|
||||
}
|
||||
if _, err := regexp.Compile(pattern); err != nil {
|
||||
return fmt.Errorf("invalid regex: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func promptIntSlice(ui *UI, label string, current []int, hint string) ([]int, error) {
|
||||
var curParts []string
|
||||
for _, v := range current {
|
||||
curParts = append(curParts, strconv.Itoa(v))
|
||||
}
|
||||
curStr := strings.Join(curParts, ",")
|
||||
|
||||
for {
|
||||
raw, err := ui.PromptString(label, curStr, hint, true, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
normalized := strings.ReplaceAll(raw, ",", " ")
|
||||
fields := strings.Fields(normalized)
|
||||
out := make([]int, 0, len(fields))
|
||||
valid := true
|
||||
for _, f := range fields {
|
||||
n, convErr := strconv.Atoi(f)
|
||||
if convErr != nil || n < 100 || n > 599 {
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
if !valid {
|
||||
ui.Error("Enter comma-separated HTTP status codes (100-599), e.g. 200,204, or '-' to clear.")
|
||||
continue
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
func uniqueMonitorID(cfg *config.Config, base string) string {
|
||||
taken := make(map[string]bool, len(cfg.Monitors))
|
||||
for _, m := range cfg.Monitors {
|
||||
taken[m.ID] = true
|
||||
}
|
||||
if !taken[base] {
|
||||
return base
|
||||
}
|
||||
for n := 2; ; n++ {
|
||||
cand := fmt.Sprintf("%s-%d", base, n)
|
||||
if !taken[cand] {
|
||||
return cand
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cloneMonitor(m config.MonitorConfig) config.MonitorConfig {
|
||||
cp := m
|
||||
if m.ExpectedStatus != nil {
|
||||
cp.ExpectedStatus = append([]int(nil), m.ExpectedStatus...)
|
||||
}
|
||||
if m.Args != nil {
|
||||
cp.Args = append([]string(nil), m.Args...)
|
||||
}
|
||||
if m.Headers != nil {
|
||||
cp.Headers = make(map[string]string, len(m.Headers))
|
||||
for k, v := range m.Headers {
|
||||
cp.Headers[k] = v
|
||||
}
|
||||
}
|
||||
if m.Env != nil {
|
||||
cp.Env = make(map[string]string, len(m.Env))
|
||||
for k, v := range m.Env {
|
||||
cp.Env[k] = v
|
||||
}
|
||||
}
|
||||
if m.Retries != nil {
|
||||
cp.Retries = config.IntPtr(*m.Retries)
|
||||
}
|
||||
if m.ExpectedExitCode != nil {
|
||||
cp.ExpectedExitCode = config.IntPtr(*m.ExpectedExitCode)
|
||||
}
|
||||
return cp
|
||||
}
|
||||
|
||||
func formatMonitorOverrides(m config.MonitorConfig) string {
|
||||
var parts []string
|
||||
if m.Interval > 0 {
|
||||
parts = append(parts, "interval="+m.Interval.Std().String())
|
||||
}
|
||||
if m.Timeout > 0 {
|
||||
parts = append(parts, "timeout="+m.Timeout.Std().String())
|
||||
}
|
||||
if m.Retries != nil {
|
||||
parts = append(parts, fmt.Sprintf("retries=%d", *m.Retries))
|
||||
}
|
||||
if m.DegradedLatency > 0 {
|
||||
parts = append(parts, "degraded="+m.DegradedLatency.Std().String())
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "inheriting all global defaults"
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func findMonitorRefs(cfg *config.Config, monitorID string) (eventIDs []string, pageGroups []string) {
|
||||
for _, ev := range cfg.Events {
|
||||
if conditionUsesMonitor(ev.Condition, monitorID) {
|
||||
eventIDs = append(eventIDs, ev.ID)
|
||||
}
|
||||
}
|
||||
for i, el := range cfg.Page.Elements {
|
||||
for _, id := range el.Monitors {
|
||||
if id == monitorID {
|
||||
label := el.Title
|
||||
if label == "" {
|
||||
label = fmt.Sprintf("element[%d]", i)
|
||||
}
|
||||
pageGroups = append(pageGroups, label)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return eventIDs, pageGroups
|
||||
}
|
||||
|
||||
func conditionUsesMonitor(cond config.EventCondition, monitorID string) bool {
|
||||
if len(cond.Conditions) > 0 {
|
||||
for _, sub := range cond.Conditions {
|
||||
if conditionUsesMonitor(sub, monitorID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, id := range cond.Monitors {
|
||||
if id == monitorID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func renameMonitorRefs(cfg *config.Config, oldID, newID string) {
|
||||
for i := range cfg.Events {
|
||||
renameConditionMonitorRef(&cfg.Events[i].Condition, oldID, newID)
|
||||
}
|
||||
for i := range cfg.Page.Elements {
|
||||
for j, id := range cfg.Page.Elements[i].Monitors {
|
||||
if id == oldID {
|
||||
cfg.Page.Elements[i].Monitors[j] = newID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func renameConditionMonitorRef(cond *config.EventCondition, oldID, newID string) {
|
||||
if len(cond.Conditions) > 0 {
|
||||
for i := range cond.Conditions {
|
||||
renameConditionMonitorRef(&cond.Conditions[i], oldID, newID)
|
||||
}
|
||||
return
|
||||
}
|
||||
for i, id := range cond.Monitors {
|
||||
if id == oldID {
|
||||
cond.Monitors[i] = newID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeMonitorRefs(cfg *config.Config, targetID string) {
|
||||
for i := range cfg.Events {
|
||||
removeConditionMonitorRef(&cfg.Events[i].Condition, targetID)
|
||||
}
|
||||
for i := range cfg.Page.Elements {
|
||||
if len(cfg.Page.Elements[i].Monitors) > 0 {
|
||||
filtered := make([]string, 0, len(cfg.Page.Elements[i].Monitors))
|
||||
for _, id := range cfg.Page.Elements[i].Monitors {
|
||||
if id != targetID {
|
||||
filtered = append(filtered, id)
|
||||
}
|
||||
}
|
||||
cfg.Page.Elements[i].Monitors = filtered
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeConditionMonitorRef(cond *config.EventCondition, targetID string) {
|
||||
if len(cond.Conditions) > 0 {
|
||||
for i := range cond.Conditions {
|
||||
removeConditionMonitorRef(&cond.Conditions[i], targetID)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(cond.Monitors) > 0 {
|
||||
filtered := make([]string, 0, len(cond.Monitors))
|
||||
for _, id := range cond.Monitors {
|
||||
if id != targetID {
|
||||
filtered = append(filtered, id)
|
||||
}
|
||||
}
|
||||
cond.Monitors = filtered
|
||||
}
|
||||
}
|
||||
651
internal/builder/editors_page.go
Normal file
651
internal/builder/editors_page.go
Normal file
|
|
@ -0,0 +1,651 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
func editPage(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("Title: %q | Elements: %d | BG: %s | Up: %s",
|
||||
cfg.Page.Title, len(cfg.Page.Elements), cfg.Page.Theme.BgColor, cfg.Page.Theme.UpColor)
|
||||
opts := []Option{
|
||||
{Label: "Page HTML title", Description: cfg.Page.Title},
|
||||
{Label: "Apply theme preset", Description: "Dark Minimal, Clean Light, Terminal Green, Nord, High Contrast"},
|
||||
{Label: "Customize theme colors & typography", Description: "Edit all 14 CSS theme properties"},
|
||||
{Label: "Manage page elements", Description: fmt.Sprintf("%d element(s): %s", len(cfg.Page.Elements), summarizeElements(cfg.Page.Elements))},
|
||||
{Label: "Back to main hub"},
|
||||
}
|
||||
|
||||
idx, ok, err := ui.Select("Page & Theme", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
t, err := ui.PromptString("Page HTML <title>", cfg.Page.Title, "", false, requireNonEmpty("title"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Page.Title = t
|
||||
case 1:
|
||||
if err := applyThemePresetFlow(ui, &cfg.Page); err != nil {
|
||||
return err
|
||||
}
|
||||
case 2:
|
||||
if err := editCustomTheme(ui, &cfg.Page.Theme); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if err := editPageElements(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func applyThemePresetFlow(ui *UI, page *config.PageConfig) error {
|
||||
presets := ThemePresets()
|
||||
opts := make([]Option, len(presets)+1)
|
||||
for i, p := range presets {
|
||||
opts[i] = Option{Label: p.Name, Description: p.Description}
|
||||
}
|
||||
opts[len(presets)] = Option{Label: "Cancel"}
|
||||
|
||||
idx, ok, err := ui.Select("Choose Theme Preset", "", opts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(presets) {
|
||||
return nil
|
||||
}
|
||||
customCSS := page.Theme.CustomCSS
|
||||
page.Theme = presets[idx].Theme
|
||||
if customCSS != "" && page.Theme.CustomCSS == "" {
|
||||
page.Theme.CustomCSS = customCSS
|
||||
}
|
||||
ui.Ok("Applied theme preset: " + presets[idx].Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func editCustomTheme(ui *UI, theme *config.ThemeConfig) error {
|
||||
for {
|
||||
opts := []Option{
|
||||
{Label: "Background & surface colors", Description: fmt.Sprintf("bg=%s card=%s border=%s", theme.BgColor, theme.CardBgColor, theme.BorderColor)},
|
||||
{Label: "Text & accent colors", Description: fmt.Sprintf("text=%s muted=%s accent=%s", theme.TextColor, theme.MutedTextColor, theme.AccentColor)},
|
||||
{Label: "Status state colors", Description: fmt.Sprintf("up=%s degraded=%s down=%s pending=%s", theme.UpColor, theme.DegradedColor, theme.DownColor, theme.PendingColor)},
|
||||
{Label: "Typography & layout", Description: fmt.Sprintf("font=%q max_width=%s radius=%s", truncateDesc(theme.FontFamily, 24), theme.MaxWidth, theme.BorderRadius)},
|
||||
{Label: "Custom CSS", Description: truncateDesc(theme.CustomCSS, 40)},
|
||||
{Label: "Done"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Customize Theme", "", opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(opts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch idx {
|
||||
case 0:
|
||||
if theme.BgColor, err = ui.PromptString("bg_color", theme.BgColor, "CSS color", false, requireNonEmpty("bg_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.CardBgColor, err = ui.PromptString("card_bg_color", theme.CardBgColor, "CSS color", false, requireNonEmpty("card_bg_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.BorderColor, err = ui.PromptString("border_color", theme.BorderColor, "CSS color", false, requireNonEmpty("border_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 1:
|
||||
if theme.TextColor, err = ui.PromptString("text_color", theme.TextColor, "CSS color", false, requireNonEmpty("text_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.MutedTextColor, err = ui.PromptString("muted_text_color", theme.MutedTextColor, "CSS color", false, requireNonEmpty("muted_text_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.AccentColor, err = ui.PromptString("accent_color", theme.AccentColor, "CSS color", false, requireNonEmpty("accent_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 2:
|
||||
if theme.UpColor, err = ui.PromptString("up_color", theme.UpColor, "CSS color", false, requireNonEmpty("up_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.DegradedColor, err = ui.PromptString("degraded_color", theme.DegradedColor, "CSS color", false, requireNonEmpty("degraded_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.DownColor, err = ui.PromptString("down_color", theme.DownColor, "CSS color", false, requireNonEmpty("down_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.PendingColor, err = ui.PromptString("pending_color", theme.PendingColor, "CSS color", false, requireNonEmpty("pending_color")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 3:
|
||||
if theme.FontFamily, err = ui.PromptString("font_family", theme.FontFamily, "CSS font-family", false, requireNonEmpty("font_family")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.MaxWidth, err = ui.PromptString("max_width", theme.MaxWidth, "e.g. 820px", false, requireNonEmpty("max_width")); err != nil {
|
||||
return err
|
||||
}
|
||||
if theme.BorderRadius, err = ui.PromptString("border_radius", theme.BorderRadius, "e.g. 2px, 6px", false, requireNonEmpty("border_radius")); err != nil {
|
||||
return err
|
||||
}
|
||||
case 4:
|
||||
if theme.CustomCSS, err = ui.PromptString("custom_css", theme.CustomCSS, "raw CSS appended to <style>", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editPageElements(ui *UI, cfg *config.Config) error {
|
||||
for {
|
||||
sub := fmt.Sprintf("%d element(s): %s", len(cfg.Page.Elements), summarizeElements(cfg.Page.Elements))
|
||||
opts := []Option{
|
||||
{Label: "Add page element", Description: "header, status_banner, summary_cards, monitor_group, custom_block, divider"},
|
||||
}
|
||||
if len(cfg.Page.Elements) > 0 {
|
||||
opts = append(opts,
|
||||
Option{Label: "Edit page element"},
|
||||
Option{Label: "Duplicate page element"},
|
||||
Option{Label: "Reorder page elements", Description: "Move elements up or down"},
|
||||
Option{Label: "Delete page element"},
|
||||
)
|
||||
}
|
||||
opts = append(opts, Option{Label: "Back"})
|
||||
|
||||
idx, ok, err := ui.Select("Page Elements", sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Back" {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch opts[idx].Label {
|
||||
case "Add page element":
|
||||
if err := addPageElementFlow(ui, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Edit page element":
|
||||
eIdx, eOK, err := pickPageElement(ui, cfg.Page.Elements, "Select element to edit")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if eOK {
|
||||
if err := editSinglePageElement(ui, cfg, &cfg.Page.Elements[eIdx]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "Duplicate page element":
|
||||
eIdx, eOK, err := pickPageElement(ui, cfg.Page.Elements, "Select element to duplicate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if eOK {
|
||||
cp := clonePageElement(cfg.Page.Elements[eIdx])
|
||||
cfg.Page.Elements = append(cfg.Page.Elements, cp)
|
||||
ui.Ok("Duplicated page element.")
|
||||
}
|
||||
case "Reorder page elements":
|
||||
if err := reorderPageElements(ui, &cfg.Page); err != nil {
|
||||
return err
|
||||
}
|
||||
case "Delete page element":
|
||||
eIdx, eOK, err := pickPageElement(ui, cfg.Page.Elements, "Select element to delete")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if eOK {
|
||||
cfg.Page.Elements = append(cfg.Page.Elements[:eIdx], cfg.Page.Elements[eIdx+1:]...)
|
||||
ui.Ok("Deleted page element.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pickPageElement(ui *UI, elems []config.PageElement, title string) (int, bool, error) {
|
||||
opts := make([]Option, len(elems))
|
||||
for i, el := range elems {
|
||||
opts[i] = Option{
|
||||
Label: fmt.Sprintf("[%d] %s", i+1, el.Type),
|
||||
Description: elementDescription(el),
|
||||
}
|
||||
}
|
||||
return ui.Select(title, "", opts, -1)
|
||||
}
|
||||
|
||||
func reorderPageElements(ui *UI, page *config.PageConfig) error {
|
||||
for {
|
||||
if len(page.Elements) < 2 {
|
||||
ui.Info("Need at least 2 elements to reorder.")
|
||||
return nil
|
||||
}
|
||||
eIdx, ok, err := pickPageElement(ui, page.Elements, "Pick element to move (Esc/0 when done)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
dirOpts := []Option{{Label: "Move up"}, {Label: "Move down"}, {Label: "Cancel"}}
|
||||
dIdx, dOK, err := ui.Select("Move "+page.Elements[eIdx].Type, "", dirOpts, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !dOK || dIdx == 2 {
|
||||
continue
|
||||
}
|
||||
if dIdx == 0 && eIdx > 0 {
|
||||
page.Elements[eIdx-1], page.Elements[eIdx] = page.Elements[eIdx], page.Elements[eIdx-1]
|
||||
} else if dIdx == 1 && eIdx < len(page.Elements)-1 {
|
||||
page.Elements[eIdx+1], page.Elements[eIdx] = page.Elements[eIdx], page.Elements[eIdx+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addPageElementFlow(ui *UI, cfg *config.Config) error {
|
||||
typeOpts := []Option{
|
||||
{Label: "header", Description: "Page heading, subtitle, live indicator & updated timestamp"},
|
||||
{Label: "status_banner", Description: "Overall status bar colored by system state"},
|
||||
{Label: "summary_cards", Description: "Compact metric grid (total, up, degraded, down, uptime, latency)"},
|
||||
{Label: "monitor_group", Description: "List or grid of monitors with history bars & toggles"},
|
||||
{Label: "custom_block", Description: "Static notice, maintenance note, or informational banner"},
|
||||
{Label: "divider", Description: "Horizontal separator rule"},
|
||||
{Label: "Cancel"},
|
||||
}
|
||||
idx, ok, err := ui.Select("Add Page Element", "", typeOpts, 3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok || idx == len(typeOpts)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var el config.PageElement
|
||||
switch typeOpts[idx].Label {
|
||||
case "header":
|
||||
el = config.PageElement{
|
||||
Type: "header",
|
||||
Title: cfg.Page.Title,
|
||||
Subtitle: "System status",
|
||||
Align: "split",
|
||||
ShowLastUpdated: true,
|
||||
ShowLiveIndicator: true,
|
||||
}
|
||||
case "status_banner":
|
||||
el = config.PageElement{
|
||||
Type: "status_banner",
|
||||
Messages: map[string]string{
|
||||
"up": "All systems operational",
|
||||
"degraded": "Some systems degraded",
|
||||
"down": "One or more systems down",
|
||||
"pending": "Checking systems...",
|
||||
},
|
||||
ShowOverallUptime: true,
|
||||
ShowCounts: true,
|
||||
}
|
||||
case "summary_cards":
|
||||
el = config.PageElement{
|
||||
Type: "summary_cards",
|
||||
Metrics: []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"},
|
||||
}
|
||||
case "monitor_group":
|
||||
el = config.PageElement{
|
||||
Type: "monitor_group",
|
||||
Title: "Services",
|
||||
Monitors: []string{"*"},
|
||||
Layout: "list",
|
||||
Display: &config.MonitorDisplayConfig{
|
||||
ShowBar: config.BoolPtr(true),
|
||||
BarTicks: 40,
|
||||
ShowUptime: config.BoolPtr(true),
|
||||
ShowLatency: config.BoolPtr(true),
|
||||
ShowStatusBadge: config.BoolPtr(true),
|
||||
ShowMethod: config.BoolPtr(true),
|
||||
ShowDescription: config.BoolPtr(true),
|
||||
},
|
||||
}
|
||||
case "custom_block":
|
||||
el = config.PageElement{
|
||||
Type: "custom_block",
|
||||
Title: "Notice",
|
||||
Style: "info",
|
||||
}
|
||||
case "divider":
|
||||
cfg.Page.Elements = append(cfg.Page.Elements, config.PageElement{Type: "divider"})
|
||||
ui.Ok("Added divider element.")
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := editSinglePageElement(ui, cfg, &el); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Page.Elements = append(cfg.Page.Elements, el)
|
||||
ui.Ok("Added " + el.Type + " element.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func editSinglePageElement(ui *UI, cfg *config.Config, el *config.PageElement) error {
|
||||
switch strings.ToLower(strings.TrimSpace(el.Type)) {
|
||||
case "header":
|
||||
var err error
|
||||
if el.Title, err = ui.PromptString("Header title", el.Title, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.Subtitle, err = ui.PromptString("Header subtitle", el.Subtitle, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
alignOpts := []Option{{Label: "split"}, {Label: "left"}, {Label: "center"}}
|
||||
defA := 0
|
||||
for i, o := range alignOpts {
|
||||
if strings.EqualFold(o.Label, el.Align) {
|
||||
defA = i
|
||||
break
|
||||
}
|
||||
}
|
||||
aIdx, aOK, err := ui.Select("Header Alignment", "", alignOpts, defA)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if aOK {
|
||||
el.Align = alignOpts[aIdx].Label
|
||||
}
|
||||
if el.ShowLastUpdated, err = ui.Confirm("Show last-updated timestamp?", el.ShowLastUpdated); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.ShowLiveIndicator, err = ui.Confirm("Show live indicator dot?", el.ShowLiveIndicator); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "status_banner":
|
||||
if el.Messages == nil {
|
||||
el.Messages = map[string]string{}
|
||||
}
|
||||
for _, st := range []struct{ key, def string }{
|
||||
{"up", "All systems operational"},
|
||||
{"degraded", "Some systems are degraded"},
|
||||
{"down", "One or more systems are down"},
|
||||
{"pending", "Checking systems..."},
|
||||
} {
|
||||
cur := el.Messages[st.key]
|
||||
if cur == "" {
|
||||
cur = st.def
|
||||
}
|
||||
val, err := ui.PromptString("Banner message when "+st.key, cur, "", false, requireNonEmpty(st.key+" message"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
el.Messages[st.key] = val
|
||||
}
|
||||
var err error
|
||||
if el.ShowOverallUptime, err = ui.Confirm("Show overall uptime percentage?", el.ShowOverallUptime); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.ShowCounts, err = ui.Confirm("Show up/total monitor counts?", el.ShowCounts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "summary_cards", "summary":
|
||||
t, err := ui.PromptString("Section title (optional)", el.Title, "", true, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
el.Title = t
|
||||
|
||||
allMetrics := []Option{
|
||||
{Label: "total", Description: "Total monitor count"},
|
||||
{Label: "up", Description: "Healthy monitor count"},
|
||||
{Label: "degraded", Description: "Degraded monitor count"},
|
||||
{Label: "down", Description: "Down monitor count"},
|
||||
{Label: "overall_uptime", Description: "Average uptime percentage"},
|
||||
{Label: "avg_latency", Description: "Average check latency"},
|
||||
}
|
||||
curSet := make(map[string]bool)
|
||||
for _, m := range el.Metrics {
|
||||
curSet[strings.ToLower(strings.TrimSpace(m))] = true
|
||||
}
|
||||
pre := make(map[int]bool)
|
||||
for i, o := range allMetrics {
|
||||
if len(curSet) == 0 || curSet[o.Label] {
|
||||
pre[i] = true
|
||||
}
|
||||
}
|
||||
indices, mOK, err := ui.MultiSelect("Summary Card Metrics", "", allMetrics, pre)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK && len(indices) > 0 {
|
||||
selected := make([]string, 0, len(indices))
|
||||
for _, idx := range indices {
|
||||
selected = append(selected, allMetrics[idx].Label)
|
||||
}
|
||||
el.Metrics = selected
|
||||
}
|
||||
|
||||
case "monitor_group", "monitors":
|
||||
var err error
|
||||
if el.Title, err = ui.PromptString("Group title", el.Title, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.Description, err = ui.PromptString("Group description", el.Description, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Monitor multi-select
|
||||
mons, mOK, err := selectConditionMonitors(ui, cfg, el.Monitors)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mOK {
|
||||
el.Monitors = mons
|
||||
}
|
||||
|
||||
layoutOpts := []Option{{Label: "list", Description: "Vertical stack"}, {Label: "grid", Description: "Responsive multi-column grid"}}
|
||||
defL := 0
|
||||
if strings.EqualFold(el.Layout, "grid") {
|
||||
defL = 1
|
||||
}
|
||||
lIdx, lOK, err := ui.Select("Monitor Group Layout", "", layoutOpts, defL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lOK {
|
||||
el.Layout = layoutOpts[lIdx].Label
|
||||
}
|
||||
|
||||
if el.Display == nil {
|
||||
el.Display = &config.MonitorDisplayConfig{}
|
||||
}
|
||||
if err := editMonitorDisplayConfig(ui, el.Display); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case "custom_block", "text":
|
||||
var err error
|
||||
if el.Title, err = ui.PromptString("Block title", el.Title, "", true, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if el.Content, err = ui.PromptString("Block content", el.Content, "", false, requireNonEmpty("content")); err != nil {
|
||||
return err
|
||||
}
|
||||
styleOpts := []Option{{Label: "neutral"}, {Label: "info"}, {Label: "warning"}, {Label: "danger"}}
|
||||
defS := 0
|
||||
for i, o := range styleOpts {
|
||||
if strings.EqualFold(o.Label, el.Style) {
|
||||
defS = i
|
||||
break
|
||||
}
|
||||
}
|
||||
sIdx, sOK, err := ui.Select("Block Style", "", styleOpts, defS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if sOK {
|
||||
el.Style = styleOpts[sIdx].Label
|
||||
}
|
||||
|
||||
case "divider":
|
||||
ui.Info("Divider elements have no configurable fields.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func editMonitorDisplayConfig(ui *UI, d *config.MonitorDisplayConfig) error {
|
||||
toggleDefs := []struct {
|
||||
label string
|
||||
desc string
|
||||
ptr **bool
|
||||
def bool
|
||||
}{
|
||||
{"show_bar", "History status bar", &d.ShowBar, true},
|
||||
{"show_uptime", "Uptime percentage", &d.ShowUptime, true},
|
||||
{"show_latency", "Latest latency ms", &d.ShowLatency, true},
|
||||
{"show_status_badge", "Status badge pill", &d.ShowStatusBadge, true},
|
||||
{"show_method", "Check method tag (HTTP/TCP/etc.)", &d.ShowMethod, true},
|
||||
{"show_target", "Monitor target URL/host", &d.ShowTarget, false},
|
||||
{"show_description", "Monitor description line", &d.ShowDescription, true},
|
||||
{"show_message", "Latest check result/error message", &d.ShowMessage, false},
|
||||
{"show_last_checked", "Last checked UTC timestamp", &d.ShowLastChecked, false},
|
||||
}
|
||||
|
||||
opts := make([]Option, len(toggleDefs))
|
||||
pre := make(map[int]bool, len(toggleDefs))
|
||||
for i, td := range toggleDefs {
|
||||
opts[i] = Option{Label: td.label, Description: td.desc}
|
||||
val := td.def
|
||||
if *td.ptr != nil {
|
||||
val = **td.ptr
|
||||
}
|
||||
if val {
|
||||
pre[i] = true
|
||||
}
|
||||
}
|
||||
|
||||
indices, ok, err := ui.MultiSelect("Monitor Display Flags", "Toggle which data points are visible in this group", opts, pre)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
selected := make(map[int]bool, len(indices))
|
||||
for _, idx := range indices {
|
||||
selected[idx] = true
|
||||
}
|
||||
for i, td := range toggleDefs {
|
||||
*td.ptr = config.BoolPtr(selected[i])
|
||||
}
|
||||
}
|
||||
|
||||
if d.ShowBar == nil || *d.ShowBar {
|
||||
curTicks := d.BarTicks
|
||||
if curTicks <= 0 {
|
||||
curTicks = 40
|
||||
}
|
||||
ticks, err := ui.PromptInt("History bar ticks", curTicks, 1, 200)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.BarTicks = ticks
|
||||
}
|
||||
|
||||
editLabels, err := ui.Confirm("Customize status badge labels (up/degraded/down/pending)?", len(d.CustomLabels) > 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if editLabels {
|
||||
lbls, err := ui.EditStringMap("Custom Status Labels", d.CustomLabels)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.CustomLabels = lbls
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func summarizeElements(elems []config.PageElement) string {
|
||||
if len(elems) == 0 {
|
||||
return "none"
|
||||
}
|
||||
parts := make([]string, len(elems))
|
||||
for i, el := range elems {
|
||||
parts[i] = el.Type
|
||||
}
|
||||
return strings.Join(parts, " -> ")
|
||||
}
|
||||
|
||||
func elementDescription(el config.PageElement) string {
|
||||
switch strings.ToLower(el.Type) {
|
||||
case "header":
|
||||
return fmt.Sprintf("title=%q align=%s", el.Title, el.Align)
|
||||
case "monitor_group", "monitors":
|
||||
return fmt.Sprintf("title=%q monitors=%v layout=%s", el.Title, el.Monitors, el.Layout)
|
||||
case "summary_cards", "summary":
|
||||
return strings.Join(el.Metrics, ", ")
|
||||
case "custom_block", "text":
|
||||
return fmt.Sprintf("title=%q style=%s", el.Title, el.Style)
|
||||
case "status_banner":
|
||||
return fmt.Sprintf("counts=%v uptime=%v", el.ShowCounts, el.ShowOverallUptime)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func clonePageElement(el config.PageElement) config.PageElement {
|
||||
cp := el
|
||||
if el.Messages != nil {
|
||||
cp.Messages = make(map[string]string, len(el.Messages))
|
||||
for k, v := range el.Messages {
|
||||
cp.Messages[k] = v
|
||||
}
|
||||
}
|
||||
if el.Metrics != nil {
|
||||
cp.Metrics = append([]string(nil), el.Metrics...)
|
||||
}
|
||||
if el.Monitors != nil {
|
||||
cp.Monitors = append([]string(nil), el.Monitors...)
|
||||
}
|
||||
if el.Display != nil {
|
||||
d := *el.Display
|
||||
if d.ShowBar != nil {
|
||||
d.ShowBar = config.BoolPtr(*d.ShowBar)
|
||||
}
|
||||
if d.ShowUptime != nil {
|
||||
d.ShowUptime = config.BoolPtr(*d.ShowUptime)
|
||||
}
|
||||
if d.ShowLatency != nil {
|
||||
d.ShowLatency = config.BoolPtr(*d.ShowLatency)
|
||||
}
|
||||
if d.ShowStatusBadge != nil {
|
||||
d.ShowStatusBadge = config.BoolPtr(*d.ShowStatusBadge)
|
||||
}
|
||||
if d.ShowMethod != nil {
|
||||
d.ShowMethod = config.BoolPtr(*d.ShowMethod)
|
||||
}
|
||||
if d.ShowTarget != nil {
|
||||
d.ShowTarget = config.BoolPtr(*d.ShowTarget)
|
||||
}
|
||||
if d.ShowDescription != nil {
|
||||
d.ShowDescription = config.BoolPtr(*d.ShowDescription)
|
||||
}
|
||||
if d.ShowMessage != nil {
|
||||
d.ShowMessage = config.BoolPtr(*d.ShowMessage)
|
||||
}
|
||||
if d.ShowLastChecked != nil {
|
||||
d.ShowLastChecked = config.BoolPtr(*d.ShowLastChecked)
|
||||
}
|
||||
if el.Display.CustomLabels != nil {
|
||||
d.CustomLabels = make(map[string]string, len(el.Display.CustomLabels))
|
||||
for k, v := range el.Display.CustomLabels {
|
||||
d.CustomLabels[k] = v
|
||||
}
|
||||
}
|
||||
cp.Display = &d
|
||||
}
|
||||
return cp
|
||||
}
|
||||
366
internal/builder/presets.go
Normal file
366
internal/builder/presets.go
Normal file
|
|
@ -0,0 +1,366 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
// ThemePreset defines a named visual theme for the status page.
|
||||
type ThemePreset struct {
|
||||
Name string
|
||||
Description string
|
||||
Theme config.ThemeConfig
|
||||
}
|
||||
|
||||
// ThemePresets lists the built-in color/typography presets for page.theme.
|
||||
func ThemePresets() []ThemePreset {
|
||||
def := config.DefaultConfig().Page.Theme
|
||||
return []ThemePreset{
|
||||
{
|
||||
Name: "Dark Minimal (Default)",
|
||||
Description: "Charcoal dark monospace theme",
|
||||
Theme: def,
|
||||
},
|
||||
{
|
||||
Name: "Clean Light",
|
||||
Description: "Crisp light background with high-readability ink",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#f8fafc",
|
||||
CardBgColor: "#ffffff",
|
||||
TextColor: "#0f172a",
|
||||
MutedTextColor: "#64748b",
|
||||
BorderColor: "#e2e8f0",
|
||||
AccentColor: "#2563eb",
|
||||
UpColor: "#16a34a",
|
||||
DegradedColor: "#d97706",
|
||||
DownColor: "#dc2626",
|
||||
PendingColor: "#94a3b8",
|
||||
FontFamily: "ui-sans-serif, system-ui, -apple-system, sans-serif",
|
||||
MaxWidth: "860px",
|
||||
BorderRadius: "6px",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "Terminal Green",
|
||||
Description: "Classic phosphor green-on-black terminal style",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#050a05",
|
||||
CardBgColor: "#0a140a",
|
||||
TextColor: "#7dff7d",
|
||||
MutedTextColor: "#3b8a3b",
|
||||
BorderColor: "#1b3b1b",
|
||||
AccentColor: "#9aff9a",
|
||||
UpColor: "#00ff66",
|
||||
DegradedColor: "#ffd000",
|
||||
DownColor: "#ff3b3b",
|
||||
PendingColor: "#4a6b4a",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "820px",
|
||||
BorderRadius: "0px",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "Nord",
|
||||
Description: "Arctic bluish-slate palette",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#2e3440",
|
||||
CardBgColor: "#3b4252",
|
||||
TextColor: "#eceff4",
|
||||
MutedTextColor: "#d8dee9",
|
||||
BorderColor: "#4c566a",
|
||||
AccentColor: "#88c0d0",
|
||||
UpColor: "#a3be8c",
|
||||
DegradedColor: "#ebcb8b",
|
||||
DownColor: "#bf616a",
|
||||
PendingColor: "#81a1c1",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "840px",
|
||||
BorderRadius: "4px",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "High Contrast",
|
||||
Description: "Pure black/white high-contrast accessibility palette",
|
||||
Theme: config.ThemeConfig{
|
||||
BgColor: "#000000",
|
||||
CardBgColor: "#0a0a0a",
|
||||
TextColor: "#ffffff",
|
||||
MutedTextColor: "#d4d4d4",
|
||||
BorderColor: "#ffffff",
|
||||
AccentColor: "#00ffff",
|
||||
UpColor: "#00ff00",
|
||||
DegradedColor: "#ffff00",
|
||||
DownColor: "#ff3333",
|
||||
PendingColor: "#a3a3a3",
|
||||
FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
|
||||
MaxWidth: "860px",
|
||||
BorderRadius: "2px",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// BlankMinimalConfig returns a clean minimal config ready for custom monitors.
|
||||
func BlankMinimalConfig() config.Config {
|
||||
def := config.DefaultConfig()
|
||||
return config.Config{
|
||||
Server: def.Server,
|
||||
Storage: def.Storage,
|
||||
Defaults: def.Defaults,
|
||||
Monitors: []config.MonitorConfig{},
|
||||
Events: []config.EventConfig{},
|
||||
Page: config.PageConfig{
|
||||
Title: "Service Status",
|
||||
Theme: def.Page.Theme,
|
||||
Elements: []config.PageElement{
|
||||
{
|
||||
Type: "header",
|
||||
Title: "Service Status",
|
||||
Subtitle: "System health & uptime",
|
||||
Align: "split",
|
||||
ShowLastUpdated: true,
|
||||
ShowLiveIndicator: true,
|
||||
},
|
||||
{
|
||||
Type: "status_banner",
|
||||
Messages: map[string]string{
|
||||
"up": "All systems operational",
|
||||
"degraded": "Some systems experiencing degraded performance",
|
||||
"down": "One or more systems are down",
|
||||
"pending": "Checking system status...",
|
||||
},
|
||||
ShowOverallUptime: true,
|
||||
ShowCounts: true,
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "Services",
|
||||
Monitors: []string{"*"},
|
||||
Layout: "list",
|
||||
Display: &config.MonitorDisplayConfig{
|
||||
ShowBar: config.BoolPtr(true),
|
||||
BarTicks: 40,
|
||||
ShowUptime: config.BoolPtr(true),
|
||||
ShowLatency: config.BoolPtr(true),
|
||||
ShowStatusBadge: config.BoolPtr(true),
|
||||
ShowMethod: config.BoolPtr(true),
|
||||
ShowDescription: config.BoolPtr(true),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// WebAPIStarterConfig returns a starter configuration tailored for public web/API endpoints.
|
||||
func WebAPIStarterConfig() config.Config {
|
||||
cfg := BlankMinimalConfig()
|
||||
cfg.Page.Title = "API & Web Status"
|
||||
cfg.Page.Elements[0].Title = "API & Web Status"
|
||||
cfg.Page.Elements[0].Subtitle = "Public website and API availability"
|
||||
cfg.Monitors = []config.MonitorConfig{
|
||||
{
|
||||
ID: "main-web",
|
||||
Name: "Main Website",
|
||||
Description: "Primary HTTPS landing page",
|
||||
Method: "https",
|
||||
URL: "https://example.com/",
|
||||
HTTPMethod: "GET",
|
||||
ExpectedStatus: []int{200},
|
||||
},
|
||||
{
|
||||
ID: "api-health",
|
||||
Name: "Core API Health",
|
||||
Description: "JSON health endpoint",
|
||||
Method: "https",
|
||||
URL: "https://api.example.com/health",
|
||||
HTTPMethod: "GET",
|
||||
ExpectedStatus: []int{200},
|
||||
BodyRegex: `"ok":\s*true`,
|
||||
},
|
||||
{
|
||||
ID: "domain-dns",
|
||||
Name: "Domain DNS (A)",
|
||||
Method: "dns",
|
||||
Host: "example.com",
|
||||
RecordType: "A",
|
||||
},
|
||||
}
|
||||
cfg.Events = []config.EventConfig{
|
||||
{
|
||||
ID: "web-outage",
|
||||
Name: "Website or API Outage",
|
||||
Cooldown: config.NewDuration(15 * time.Minute),
|
||||
TriggerOnRecovery: true,
|
||||
Condition: config.EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"main-web", "api-health"},
|
||||
Match: "any",
|
||||
State: "down",
|
||||
For: config.NewDuration(1 * time.Minute),
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{
|
||||
Type: "command",
|
||||
Command: `echo "[RUD ALERT] {{.EventName}}: {{.Status}} ({{.TriggeredMonitors}})"`,
|
||||
Shell: true,
|
||||
Timeout: config.NewDuration(5 * time.Second),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
cfg.Page.Elements = []config.PageElement{
|
||||
cfg.Page.Elements[0],
|
||||
cfg.Page.Elements[1],
|
||||
{
|
||||
Type: "summary_cards",
|
||||
Metrics: []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"},
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "Web & APIs",
|
||||
Monitors: []string{"main-web", "api-health"},
|
||||
Layout: "list",
|
||||
Display: cfg.Page.Elements[2].Display,
|
||||
},
|
||||
{
|
||||
Type: "monitor_group",
|
||||
Title: "DNS",
|
||||
Monitors: []string{"domain-dns"},
|
||||
Layout: "list",
|
||||
Display: cfg.Page.Elements[2].Display,
|
||||
},
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// HomelabStarterConfig returns a starter configuration tailored for homelab / self-hosted services.
|
||||
func HomelabStarterConfig() config.Config {
|
||||
cfg := BlankMinimalConfig()
|
||||
cfg.Page.Title = "Homelab Status"
|
||||
cfg.Page.Elements[0].Title = "Homelab Status"
|
||||
cfg.Page.Elements[0].Subtitle = "Internal nodes, databases & services"
|
||||
cfg.Monitors = []config.MonitorConfig{
|
||||
{
|
||||
ID: "gateway-ping",
|
||||
Name: "Router / Gateway",
|
||||
Description: "Local network gateway",
|
||||
Method: "ping",
|
||||
Host: "127.0.0.1",
|
||||
Count: 1,
|
||||
},
|
||||
{
|
||||
ID: "db-tcp",
|
||||
Name: "Database TCP",
|
||||
Description: "Database port handshake",
|
||||
Method: "tcp",
|
||||
Target: "127.0.0.1:5432",
|
||||
},
|
||||
{
|
||||
ID: "reverse-proxy",
|
||||
Name: "Reverse Proxy",
|
||||
Description: "Local HTTP ingress",
|
||||
Method: "http",
|
||||
URL: "http://127.0.0.1:80/",
|
||||
},
|
||||
{
|
||||
ID: "root-disk",
|
||||
Name: "Root Disk Free",
|
||||
Description: "Fails if root filesystem exceeds 90% usage",
|
||||
Method: "cmd",
|
||||
Command: "df -P / | awk 'NR==2 {print $5}'",
|
||||
Shell: true,
|
||||
ExpectedExitCode: config.IntPtr(0),
|
||||
OutputRegex: `^([0-8]?[0-9])%$`,
|
||||
},
|
||||
}
|
||||
cfg.Events = []config.EventConfig{
|
||||
{
|
||||
ID: "node-down",
|
||||
Name: "Homelab Service Down",
|
||||
Cooldown: config.NewDuration(30 * time.Minute),
|
||||
TriggerOnRecovery: true,
|
||||
Condition: config.EventCondition{
|
||||
Type: "state",
|
||||
Monitors: []string{"*"},
|
||||
Match: "any",
|
||||
State: "down",
|
||||
For: config.NewDuration(2 * time.Minute),
|
||||
},
|
||||
Actions: []config.EventAction{
|
||||
{
|
||||
Type: "command",
|
||||
Command: `echo "[HOMELAB] {{.EventName}}: {{.Status}} monitors={{.TriggeredMonitors}}"`,
|
||||
Shell: true,
|
||||
Timeout: config.NewDuration(5 * time.Second),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// WebhookPreset describes a pre-configured webhook payload template.
|
||||
type WebhookPreset struct {
|
||||
Name string
|
||||
Description string
|
||||
URLHint string
|
||||
HTTPMethod string
|
||||
Headers map[string]string
|
||||
Template string
|
||||
}
|
||||
|
||||
// WebhookPresets lists ready-to-use templates for common alerting targets.
|
||||
func WebhookPresets() []WebhookPreset {
|
||||
return []WebhookPreset{
|
||||
{
|
||||
Name: "Discord Webhook",
|
||||
Description: "Posts a formatted message to a Discord channel webhook",
|
||||
URLHint: "https://discord.com/api/webhooks/<id>/<token>",
|
||||
HTTPMethod: "POST",
|
||||
Template: `{"content":"**[{{jsonStr .Status}}] {{jsonStr .EventName}}** — State: ` + "`{{jsonStr .OverallState}}`" + ` | Monitors: {{jsonStr .TriggeredMonitors}} | Uptime: {{.OverallUptimePct}}%"}`,
|
||||
},
|
||||
{
|
||||
Name: "Slack Incoming Webhook",
|
||||
Description: "Posts a clean text alert to a Slack webhook",
|
||||
URLHint: "https://hooks.slack.com/services/T.../B.../...",
|
||||
HTTPMethod: "POST",
|
||||
Template: `{"text":"*[{{jsonStr .Status}}] {{jsonStr .EventName}}*\nState: {{jsonStr .OverallState}} | Monitors: {{jsonStr .TriggeredMonitors}} | Time: {{jsonStr .Timestamp}}"}`,
|
||||
},
|
||||
{
|
||||
Name: "ntfy (ntfy.sh or self-hosted)",
|
||||
Description: "Push notification via ntfy HTTP POST",
|
||||
URLHint: "https://ntfy.sh/<your-topic>",
|
||||
HTTPMethod: "POST",
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Title": "RUD Alert",
|
||||
"Priority": "high",
|
||||
},
|
||||
Template: `[{{.Status}}] {{.EventName}} — State: {{.OverallState}} | Monitors: {{.TriggeredMonitors}} | Uptime: {{.OverallUptimePct}}%`,
|
||||
},
|
||||
{
|
||||
Name: "Gotify",
|
||||
Description: "Push notification to a Gotify server (/message?token=...)",
|
||||
URLHint: "https://gotify.example.com/message?token=<app-token>",
|
||||
HTTPMethod: "POST",
|
||||
Template: `{"title":"[{{jsonStr .Status}}] {{jsonStr .EventName}}","message":"Overall: {{jsonStr .OverallState}}\nMonitors: {{jsonStr .TriggeredMonitors}}\nTime: {{jsonStr .Timestamp}}","priority":5}`,
|
||||
},
|
||||
{
|
||||
Name: "Generic JSON Payload",
|
||||
Description: "Sends RUD's full native EventPayload JSON (empty body_template)",
|
||||
URLHint: "https://hooks.example.com/rud",
|
||||
HTTPMethod: "POST",
|
||||
Template: "",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const templateCheatsheet = `Template variables:
|
||||
{{.EventID}}, {{.EventName}}, {{.Status}} ("TRIGGERED"/"RESOLVED"),
|
||||
{{.OverallState}}, {{.OverallUptimePct}}, {{.TriggeredMonitors}},
|
||||
{{.MonitorsJSON}}, {{.Timestamp}}, {{json .Field}}, {{jsonStr .Field}}
|
||||
Command env vars:
|
||||
RUD_EVENT_ID, RUD_EVENT_NAME, RUD_EVENT_STATUS,
|
||||
RUD_OVERALL_STATE, RUD_TRIGGERED_MONITORS, RUD_TIMESTAMP`
|
||||
41
internal/builder/term_bsd.go
Normal file
41
internal/builder/term_bsd.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
//go:build darwin || freebsd || netbsd || openbsd
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func isTerminal(f *os.File) bool {
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
var termios syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCGETA, uintptr(unsafe.Pointer(&termios)))
|
||||
return errno == 0
|
||||
}
|
||||
|
||||
func enableRawMode(f *os.File) (func(), error) {
|
||||
if f == nil {
|
||||
return func() {}, syscall.EINVAL
|
||||
}
|
||||
var orig syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCGETA, uintptr(unsafe.Pointer(&orig)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
raw := orig
|
||||
raw.Lflag &^= syscall.ICANON | syscall.ECHO | syscall.ISIG
|
||||
raw.Cc[syscall.VMIN] = 1
|
||||
raw.Cc[syscall.VTIME] = 0
|
||||
|
||||
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCSETA, uintptr(unsafe.Pointer(&raw)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
return func() {
|
||||
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCSETA, uintptr(unsafe.Pointer(&orig)))
|
||||
}, nil
|
||||
}
|
||||
41
internal/builder/term_linux.go
Normal file
41
internal/builder/term_linux.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
//go:build linux
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func isTerminal(f *os.File) bool {
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
var termios syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCGETS, uintptr(unsafe.Pointer(&termios)))
|
||||
return errno == 0
|
||||
}
|
||||
|
||||
func enableRawMode(f *os.File) (func(), error) {
|
||||
if f == nil {
|
||||
return func() {}, syscall.EINVAL
|
||||
}
|
||||
var orig syscall.Termios
|
||||
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCGETS, uintptr(unsafe.Pointer(&orig)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
raw := orig
|
||||
raw.Lflag &^= syscall.ICANON | syscall.ECHO | syscall.ISIG
|
||||
raw.Cc[syscall.VMIN] = 1
|
||||
raw.Cc[syscall.VTIME] = 0
|
||||
|
||||
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCSETS, uintptr(unsafe.Pointer(&raw)))
|
||||
if errno != 0 {
|
||||
return func() {}, errno
|
||||
}
|
||||
return func() {
|
||||
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCSETS, uintptr(unsafe.Pointer(&orig)))
|
||||
}, nil
|
||||
}
|
||||
16
internal/builder/term_other.go
Normal file
16
internal/builder/term_other.go
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
//go:build !linux && !darwin && !freebsd && !netbsd && !openbsd
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func isTerminal(f *os.File) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func enableRawMode(f *os.File) (func(), error) {
|
||||
return func() {}, errors.New("raw terminal mode not supported on this platform")
|
||||
}
|
||||
827
internal/builder/ui.go
Normal file
827
internal/builder/ui.go
Normal file
|
|
@ -0,0 +1,827 @@
|
|||
package builder
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.gsdistance.org/tyuXX/RUD/internal/config"
|
||||
)
|
||||
|
||||
// ErrAborted is returned when the user cancels the builder via Ctrl-C or reaches EOF.
|
||||
var ErrAborted = errors.New("aborted by user")
|
||||
|
||||
// Option represents a selectable item in interactive menus.
|
||||
type Option struct {
|
||||
Label string
|
||||
Description string
|
||||
}
|
||||
|
||||
// UI provides interactive terminal prompts with raw arrow-key support on TTYs
|
||||
// and clean numbered-prompt fallback for plain terminals and tests.
|
||||
type UI struct {
|
||||
in io.Reader
|
||||
reader *bufio.Reader
|
||||
out io.Writer
|
||||
inFile *os.File
|
||||
rawTTY bool
|
||||
color bool
|
||||
}
|
||||
|
||||
// NewUI constructs a UI bound to in/out. If plain is true or in/out are not TTYs,
|
||||
// it uses numbered line-based prompts.
|
||||
func NewUI(in io.Reader, out io.Writer, plain, noColor bool) *UI {
|
||||
if in == nil {
|
||||
in = os.Stdin
|
||||
}
|
||||
if out == nil {
|
||||
out = os.Stdout
|
||||
}
|
||||
inFile, inIsFile := in.(*os.File)
|
||||
outFile, outIsFile := out.(*os.File)
|
||||
|
||||
inTTY := inIsFile && isTerminal(inFile)
|
||||
outTTY := outIsFile && isTerminal(outFile)
|
||||
|
||||
useColor := !noColor && outTTY && os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb"
|
||||
useRaw := !plain && inTTY && outTTY && os.Getenv("TERM") != "dumb"
|
||||
|
||||
return &UI{
|
||||
in: in,
|
||||
reader: bufio.NewReader(in),
|
||||
out: out,
|
||||
inFile: inFile,
|
||||
rawTTY: useRaw,
|
||||
color: useColor,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) style(code, s string) string {
|
||||
if !u.color || s == "" {
|
||||
return s
|
||||
}
|
||||
return "\x1b[" + code + "m" + s + "\x1b[0m"
|
||||
}
|
||||
|
||||
func (u *UI) Bold(s string) string { return u.style("1", s) }
|
||||
func (u *UI) Dim(s string) string { return u.style("2", s) }
|
||||
func (u *UI) Cyan(s string) string { return u.style("36", s) }
|
||||
func (u *UI) Green(s string) string { return u.style("32", s) }
|
||||
func (u *UI) Yellow(s string) string { return u.style("33", s) }
|
||||
func (u *UI) Red(s string) string { return u.style("31", s) }
|
||||
|
||||
func (u *UI) Println(a ...any) {
|
||||
_, _ = fmt.Fprintln(u.out, a...)
|
||||
}
|
||||
|
||||
func (u *UI) Printf(format string, a ...any) {
|
||||
_, _ = fmt.Fprintf(u.out, format, a...)
|
||||
}
|
||||
|
||||
func (u *UI) Header(title, subtitle string) {
|
||||
u.Println()
|
||||
u.Println(u.Bold(u.Cyan("━━ " + title + " ━━")))
|
||||
if subtitle != "" {
|
||||
u.Println(u.Dim(subtitle))
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) Info(msg string) { u.Println(u.Cyan("• ") + msg) }
|
||||
func (u *UI) Ok(msg string) { u.Println(u.Green("✓ ") + msg) }
|
||||
func (u *UI) Warn(msg string) { u.Println(u.Yellow("! ") + msg) }
|
||||
func (u *UI) Error(msg string) { u.Println(u.Red("✗ ") + msg) }
|
||||
|
||||
func (u *UI) readLine() (string, error) {
|
||||
line, err := u.reader.ReadString('\n')
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
if line != "" {
|
||||
return strings.TrimSpace(line), nil
|
||||
}
|
||||
return "", ErrAborted
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(line), nil
|
||||
}
|
||||
|
||||
type keyCode int
|
||||
|
||||
const (
|
||||
keyNone keyCode = iota
|
||||
keyUp
|
||||
keyDown
|
||||
keyEnter
|
||||
keySpace
|
||||
keyEsc
|
||||
keyBack
|
||||
keyAll
|
||||
keyAbort
|
||||
keyDigit
|
||||
)
|
||||
|
||||
func (u *UI) readKey() (keyCode, int, error) {
|
||||
buf := make([]byte, 8)
|
||||
var n int
|
||||
var err error
|
||||
|
||||
if u.reader.Buffered() > 0 {
|
||||
n, err = u.reader.Read(buf)
|
||||
} else {
|
||||
n, err = u.inFile.Read(buf)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return keyAbort, 0, ErrAborted
|
||||
}
|
||||
return keyNone, 0, err
|
||||
}
|
||||
if n == 0 {
|
||||
return keyNone, 0, nil
|
||||
}
|
||||
|
||||
b := buf[:n]
|
||||
if n >= 3 && b[0] == 0x1b && b[1] == '[' {
|
||||
switch b[2] {
|
||||
case 'A':
|
||||
return keyUp, 0, nil
|
||||
case 'B':
|
||||
return keyDown, 0, nil
|
||||
}
|
||||
return keyNone, 0, nil
|
||||
}
|
||||
if n == 1 {
|
||||
switch b[0] {
|
||||
case 0x03: // Ctrl-C
|
||||
return keyAbort, 0, ErrAborted
|
||||
case '\r', '\n':
|
||||
return keyEnter, 0, nil
|
||||
case ' ':
|
||||
return keySpace, 0, nil
|
||||
case 0x1b:
|
||||
return keyEsc, 0, nil
|
||||
case 'k', 'K':
|
||||
return keyUp, 0, nil
|
||||
case 'j', 'J':
|
||||
return keyDown, 0, nil
|
||||
case 'q', 'Q', '0':
|
||||
return keyBack, 0, nil
|
||||
case 'a', 'A':
|
||||
return keyAll, 0, nil
|
||||
}
|
||||
if b[0] >= '1' && b[0] <= '9' {
|
||||
return keyDigit, int(b[0] - '1'), nil
|
||||
}
|
||||
}
|
||||
return keyNone, 0, nil
|
||||
}
|
||||
|
||||
func truncateDesc(s string, maxLen int) string {
|
||||
s = strings.ReplaceAll(s, "\n", " ")
|
||||
r := []rune(s)
|
||||
if len(r) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return string(r[:maxLen-3]) + "..."
|
||||
}
|
||||
|
||||
// Select displays a single-choice menu. Returns (selectedIndex, ok, error).
|
||||
// ok is false when the user selects Back/Cancel.
|
||||
func (u *UI) Select(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
|
||||
if len(opts) == 0 {
|
||||
return -1, false, nil
|
||||
}
|
||||
if u.rawTTY {
|
||||
return u.selectTTY(title, subtitle, opts, defaultIdx)
|
||||
}
|
||||
return u.selectPlain(title, subtitle, opts, defaultIdx)
|
||||
}
|
||||
|
||||
func (u *UI) selectTTY(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
|
||||
restore, err := enableRawMode(u.inFile)
|
||||
if err != nil {
|
||||
return u.selectPlain(title, subtitle, opts, defaultIdx)
|
||||
}
|
||||
defer restore()
|
||||
|
||||
cursor := 0
|
||||
if defaultIdx >= 0 && defaultIdx < len(opts) {
|
||||
cursor = defaultIdx
|
||||
}
|
||||
|
||||
u.Header(title, subtitle)
|
||||
printedLines := 0
|
||||
render := func() {
|
||||
if printedLines > 0 {
|
||||
u.Printf("\r\x1b[%dA", printedLines)
|
||||
}
|
||||
lines := 0
|
||||
for i, opt := range opts {
|
||||
prefix := " "
|
||||
lbl := opt.Label
|
||||
if i == cursor {
|
||||
prefix = u.Cyan("❯ ")
|
||||
lbl = u.Bold(u.Cyan(opt.Label))
|
||||
}
|
||||
desc := ""
|
||||
if opt.Description != "" {
|
||||
desc = " " + u.Dim(truncateDesc(opt.Description, 56))
|
||||
}
|
||||
u.Printf("\x1b[2K%s%2d) %s%s\r\n", prefix, i+1, lbl, desc)
|
||||
lines++
|
||||
}
|
||||
u.Printf("\x1b[2K%s\r\n", u.Dim(" [↑/↓ move • 1-9 select • Enter confirm • Esc/q back]"))
|
||||
lines++
|
||||
printedLines = lines
|
||||
}
|
||||
|
||||
render()
|
||||
for {
|
||||
k, digit, err := u.readKey()
|
||||
if err != nil {
|
||||
return -1, false, err
|
||||
}
|
||||
switch k {
|
||||
case keyAbort:
|
||||
return -1, false, ErrAborted
|
||||
case keyUp:
|
||||
cursor = (cursor - 1 + len(opts)) % len(opts)
|
||||
render()
|
||||
case keyDown:
|
||||
cursor = (cursor + 1) % len(opts)
|
||||
render()
|
||||
case keyDigit:
|
||||
if digit < len(opts) {
|
||||
cursor = digit
|
||||
if len(opts) <= 9 {
|
||||
render()
|
||||
return cursor, true, nil
|
||||
}
|
||||
render()
|
||||
}
|
||||
case keyEnter:
|
||||
return cursor, true, nil
|
||||
case keyEsc, keyBack:
|
||||
return -1, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) selectPlain(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
|
||||
u.Header(title, subtitle)
|
||||
for i, opt := range opts {
|
||||
mark := " "
|
||||
if i == defaultIdx {
|
||||
mark = "*"
|
||||
}
|
||||
if opt.Description != "" {
|
||||
u.Printf(" %s%2d) %s — %s\n", mark, i+1, opt.Label, opt.Description)
|
||||
} else {
|
||||
u.Printf(" %s%2d) %s\n", mark, i+1, opt.Label)
|
||||
}
|
||||
}
|
||||
u.Println(" 0) Back / Cancel")
|
||||
|
||||
for {
|
||||
if defaultIdx >= 0 && defaultIdx < len(opts) {
|
||||
u.Printf("Choose [1-%d, 0=back, Enter=%d]: ", len(opts), defaultIdx+1)
|
||||
} else {
|
||||
u.Printf("Choose [1-%d, 0=back]: ", len(opts))
|
||||
}
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return -1, false, err
|
||||
}
|
||||
if line == "" && defaultIdx >= 0 && defaultIdx < len(opts) {
|
||||
return defaultIdx, true, nil
|
||||
}
|
||||
lower := strings.ToLower(line)
|
||||
if lower == "0" || lower == "q" || lower == "b" || lower == "back" || lower == "cancel" {
|
||||
return -1, false, nil
|
||||
}
|
||||
n, convErr := strconv.Atoi(line)
|
||||
if convErr == nil && n >= 1 && n <= len(opts) {
|
||||
return n - 1, true, nil
|
||||
}
|
||||
u.Error(fmt.Sprintf("Please enter a number between 1 and %d (or 0 to go back).", len(opts)))
|
||||
}
|
||||
}
|
||||
|
||||
// MultiSelect displays a checkbox menu. Returns (sortedSelectedIndices, ok, error).
|
||||
func (u *UI) MultiSelect(title, subtitle string, opts []Option, preselected map[int]bool) ([]int, bool, error) {
|
||||
if len(opts) == 0 {
|
||||
return nil, true, nil
|
||||
}
|
||||
selected := make(map[int]bool, len(opts))
|
||||
for k, v := range preselected {
|
||||
if k >= 0 && k < len(opts) && v {
|
||||
selected[k] = true
|
||||
}
|
||||
}
|
||||
if u.rawTTY {
|
||||
return u.multiSelectTTY(title, subtitle, opts, selected)
|
||||
}
|
||||
return u.multiSelectPlain(title, subtitle, opts, selected)
|
||||
}
|
||||
|
||||
func sortedSelectedIndices(selected map[int]bool, n int) []int {
|
||||
var out []int
|
||||
for i := 0; i < n; i++ {
|
||||
if selected[i] {
|
||||
out = append(out, i)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (u *UI) multiSelectTTY(title, subtitle string, opts []Option, selected map[int]bool) ([]int, bool, error) {
|
||||
restore, err := enableRawMode(u.inFile)
|
||||
if err != nil {
|
||||
return u.multiSelectPlain(title, subtitle, opts, selected)
|
||||
}
|
||||
defer restore()
|
||||
|
||||
cursor := 0
|
||||
u.Header(title, subtitle)
|
||||
printedLines := 0
|
||||
render := func() {
|
||||
if printedLines > 0 {
|
||||
u.Printf("\r\x1b[%dA", printedLines)
|
||||
}
|
||||
lines := 0
|
||||
for i, opt := range opts {
|
||||
prefix := " "
|
||||
if i == cursor {
|
||||
prefix = u.Cyan("❯ ")
|
||||
}
|
||||
box := "[ ]"
|
||||
if selected[i] {
|
||||
box = u.Green("[x]")
|
||||
}
|
||||
lbl := opt.Label
|
||||
if i == cursor {
|
||||
lbl = u.Bold(lbl)
|
||||
}
|
||||
desc := ""
|
||||
if opt.Description != "" {
|
||||
desc = " " + u.Dim(truncateDesc(opt.Description, 48))
|
||||
}
|
||||
u.Printf("\x1b[2K%s%s %2d) %s%s\r\n", prefix, box, i+1, lbl, desc)
|
||||
lines++
|
||||
}
|
||||
u.Printf("\x1b[2K%s\r\n", u.Dim(" [↑/↓ move • Space toggle • a all/none • Enter confirm • Esc/q cancel]"))
|
||||
lines++
|
||||
printedLines = lines
|
||||
}
|
||||
|
||||
render()
|
||||
for {
|
||||
k, digit, err := u.readKey()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
switch k {
|
||||
case keyAbort:
|
||||
return nil, false, ErrAborted
|
||||
case keyUp:
|
||||
cursor = (cursor - 1 + len(opts)) % len(opts)
|
||||
render()
|
||||
case keyDown:
|
||||
cursor = (cursor + 1) % len(opts)
|
||||
render()
|
||||
case keySpace:
|
||||
if selected[cursor] {
|
||||
delete(selected, cursor)
|
||||
} else {
|
||||
selected[cursor] = true
|
||||
}
|
||||
render()
|
||||
case keyDigit:
|
||||
if digit < len(opts) {
|
||||
cursor = digit
|
||||
if selected[digit] {
|
||||
delete(selected, digit)
|
||||
} else {
|
||||
selected[digit] = true
|
||||
}
|
||||
render()
|
||||
}
|
||||
case keyAll:
|
||||
allOn := len(sortedSelectedIndices(selected, len(opts))) == len(opts)
|
||||
if allOn {
|
||||
for _, k := range sortedSelectedIndices(selected, len(opts)) {
|
||||
delete(selected, k)
|
||||
}
|
||||
} else {
|
||||
for i := range opts {
|
||||
selected[i] = true
|
||||
}
|
||||
}
|
||||
render()
|
||||
case keyEnter:
|
||||
return sortedSelectedIndices(selected, len(opts)), true, nil
|
||||
case keyEsc, keyBack:
|
||||
return nil, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) multiSelectPlain(title, subtitle string, opts []Option, selected map[int]bool) ([]int, bool, error) {
|
||||
u.Header(title, subtitle)
|
||||
for i, opt := range opts {
|
||||
box := "[ ]"
|
||||
if selected[i] {
|
||||
box = "[x]"
|
||||
}
|
||||
if opt.Description != "" {
|
||||
u.Printf(" %2d) %s %s — %s\n", i+1, box, opt.Label, opt.Description)
|
||||
} else {
|
||||
u.Printf(" %2d) %s %s\n", i+1, box, opt.Label)
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
u.PrintMultiHint()
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSpace(line))
|
||||
switch lower {
|
||||
case "":
|
||||
return sortedSelectedIndices(selected, len(opts)), true, nil
|
||||
case "q", "cancel", "back":
|
||||
return nil, false, nil
|
||||
case "all":
|
||||
out := make([]int, len(opts))
|
||||
for i := range opts {
|
||||
out[i] = i
|
||||
}
|
||||
return out, true, nil
|
||||
case "none":
|
||||
return []int{}, true, nil
|
||||
}
|
||||
|
||||
normalized := strings.ReplaceAll(lower, ",", " ")
|
||||
parts := strings.Fields(normalized)
|
||||
if len(parts) == 0 {
|
||||
continue
|
||||
}
|
||||
next := make(map[int]bool, len(parts))
|
||||
valid := true
|
||||
for _, p := range parts {
|
||||
n, convErr := strconv.Atoi(p)
|
||||
if convErr != nil || n < 1 || n > len(opts) {
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
next[n-1] = true
|
||||
}
|
||||
if !valid {
|
||||
u.Error(fmt.Sprintf("Invalid selection. Enter numbers 1-%d (e.g. 1,3), 'all', 'none', or 'q'.", len(opts)))
|
||||
continue
|
||||
}
|
||||
return sortedSelectedIndices(next, len(opts)), true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UI) PrintMultiHint() {
|
||||
u.Printf("Enter numbers (e.g. 1,3), 'all', 'none', Enter to keep current, or 'q' to cancel: ")
|
||||
}
|
||||
|
||||
// Confirm prompts a yes/no question.
|
||||
func (u *UI) Confirm(prompt string, defaultYes bool) (bool, error) {
|
||||
suffix := "[y/N]"
|
||||
if defaultYes {
|
||||
suffix = "[Y/n]"
|
||||
}
|
||||
for {
|
||||
u.Printf("%s %s: ", prompt, suffix)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSpace(line))
|
||||
if lower == "" {
|
||||
return defaultYes, nil
|
||||
}
|
||||
if lower == "y" || lower == "yes" {
|
||||
return true, nil
|
||||
}
|
||||
if lower == "n" || lower == "no" {
|
||||
return false, nil
|
||||
}
|
||||
u.Error("Please answer 'y' or 'n'.")
|
||||
}
|
||||
}
|
||||
|
||||
// PromptString prompts for a string value. Pressing Enter keeps current (if valid).
|
||||
// When allowClear is true, typing "-" clears the value to "".
|
||||
func (u *UI) PromptString(label, current, hint string, allowClear bool, validate func(string) error) (string, error) {
|
||||
for {
|
||||
var meta []string
|
||||
if current != "" {
|
||||
meta = append(meta, "current: "+current)
|
||||
} else {
|
||||
meta = append(meta, "empty")
|
||||
}
|
||||
if hint != "" {
|
||||
meta = append(meta, hint)
|
||||
}
|
||||
if allowClear && current != "" {
|
||||
meta = append(meta, "'-' to clear")
|
||||
}
|
||||
u.Printf("%s [%s]: ", u.Bold(label), strings.Join(meta, "; "))
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
val := line
|
||||
if line == "" {
|
||||
val = current
|
||||
} else if allowClear && line == "-" {
|
||||
val = ""
|
||||
}
|
||||
if validate != nil {
|
||||
if err := validate(val); err != nil {
|
||||
u.Error(err.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptDuration prompts for a Go duration string (e.g. 15s, 5m, 1h).
|
||||
func (u *UI) PromptDuration(label string, current config.Duration, allowZero bool) (config.Duration, error) {
|
||||
curStr := current.Std().String()
|
||||
for {
|
||||
hint := "e.g. 500ms, 15s, 5m"
|
||||
if allowZero {
|
||||
hint += "; '0s' or '-' for 0"
|
||||
}
|
||||
u.Printf("%s [current: %s; %s]: ", u.Bold(label), curStr, hint)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if line == "" {
|
||||
if !allowZero && current <= 0 {
|
||||
u.Error("Duration must be greater than 0.")
|
||||
continue
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
if allowZero && (line == "-" || line == "0") {
|
||||
return 0, nil
|
||||
}
|
||||
d, parseErr := time.ParseDuration(line)
|
||||
if parseErr != nil {
|
||||
u.Error(fmt.Sprintf("Invalid duration %q (use Go syntax like 500ms, 10s, 5m, 1h).", line))
|
||||
continue
|
||||
}
|
||||
if d < 0 || (!allowZero && d == 0) {
|
||||
u.Error("Duration must be positive.")
|
||||
continue
|
||||
}
|
||||
return config.NewDuration(d), nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptInt prompts for an integer in [min, max].
|
||||
func (u *UI) PromptInt(label string, current, min, max int) (int, error) {
|
||||
for {
|
||||
u.Printf("%s [current: %d]: ", u.Bold(label), current)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
val := current
|
||||
if line != "" {
|
||||
parsed, convErr := strconv.Atoi(line)
|
||||
if convErr != nil {
|
||||
u.Error("Please enter a valid integer.")
|
||||
continue
|
||||
}
|
||||
val = parsed
|
||||
}
|
||||
if val < min || val > max {
|
||||
u.Error(fmt.Sprintf("Value must be between %d and %d.", min, max))
|
||||
continue
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptOptionalInt prompts for an optional *int; '-' clears to nil.
|
||||
func (u *UI) PromptOptionalInt(label string, current *int, min, max int) (*int, error) {
|
||||
curDesc := "inherit/unset"
|
||||
if current != nil {
|
||||
curDesc = strconv.Itoa(*current)
|
||||
}
|
||||
for {
|
||||
u.Printf("%s [current: %s; '-' to unset]: ", u.Bold(label), curDesc)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if line == "" {
|
||||
return current, nil
|
||||
}
|
||||
if line == "-" {
|
||||
return nil, nil
|
||||
}
|
||||
parsed, convErr := strconv.Atoi(line)
|
||||
if convErr != nil {
|
||||
u.Error("Please enter a valid integer or '-' to unset.")
|
||||
continue
|
||||
}
|
||||
if parsed < min || parsed > max {
|
||||
u.Error(fmt.Sprintf("Value must be between %d and %d.", min, max))
|
||||
continue
|
||||
}
|
||||
return config.IntPtr(parsed), nil
|
||||
}
|
||||
}
|
||||
|
||||
// PromptFloat prompts for a floating-point number.
|
||||
func (u *UI) PromptFloat(label string, current float64) (float64, error) {
|
||||
for {
|
||||
u.Printf("%s [current: %g]: ", u.Bold(label), current)
|
||||
line, err := u.readLine()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if line == "" {
|
||||
return current, nil
|
||||
}
|
||||
parsed, convErr := strconv.ParseFloat(line, 64)
|
||||
if convErr != nil {
|
||||
u.Error("Please enter a valid number.")
|
||||
continue
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
|
||||
// EditStringMap provides an interactive editor for key-value string maps.
|
||||
func (u *UI) EditStringMap(title string, existing map[string]string) (map[string]string, error) {
|
||||
work := make(map[string]string, len(existing))
|
||||
for k, v := range existing {
|
||||
work[k] = v
|
||||
}
|
||||
|
||||
for {
|
||||
keys := make([]string, 0, len(work))
|
||||
for k := range work {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
var sub string
|
||||
if len(keys) == 0 {
|
||||
sub = "Currently empty."
|
||||
} else {
|
||||
var parts []string
|
||||
for _, k := range keys {
|
||||
parts = append(parts, fmt.Sprintf("%s=%q", k, work[k]))
|
||||
}
|
||||
sub = strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
opts := []Option{
|
||||
{Label: "Add or update entry", Description: "Set a key=value pair"},
|
||||
}
|
||||
if len(keys) > 0 {
|
||||
opts = append(opts, Option{Label: "Remove entry", Description: "Delete an existing key"})
|
||||
opts = append(opts, Option{Label: "Clear all entries"})
|
||||
}
|
||||
opts = append(opts, Option{Label: "Done"})
|
||||
|
||||
idx, ok, err := u.Select(title, sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Done" {
|
||||
if len(work) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return work, nil
|
||||
}
|
||||
switch opts[idx].Label {
|
||||
case "Add or update entry":
|
||||
k, err := u.PromptString("Key", "", "non-empty key", false, requireNonEmpty("key"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := u.PromptString("Value for "+k, work[k], "", false, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work[k] = v
|
||||
case "Remove entry":
|
||||
delOpts := make([]Option, len(keys))
|
||||
for i, k := range keys {
|
||||
delOpts[i] = Option{Label: k, Description: work[k]}
|
||||
}
|
||||
dIdx, dOK, err := u.Select("Remove which key?", "", delOpts, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dOK {
|
||||
delete(work, keys[dIdx])
|
||||
}
|
||||
case "Clear all entries":
|
||||
work = map[string]string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EditStringSlice provides an interactive editor for ordered lists of strings.
|
||||
func (u *UI) EditStringSlice(title, itemLabel string, existing []string) ([]string, error) {
|
||||
work := append([]string(nil), existing...)
|
||||
|
||||
for {
|
||||
sub := "Currently empty."
|
||||
if len(work) > 0 {
|
||||
sub = fmt.Sprintf("%d item(s): %s", len(work), strings.Join(work, ", "))
|
||||
}
|
||||
opts := []Option{
|
||||
{Label: "Add " + itemLabel},
|
||||
}
|
||||
if len(work) > 0 {
|
||||
opts = append(opts,
|
||||
Option{Label: "Edit " + itemLabel},
|
||||
Option{Label: "Remove " + itemLabel},
|
||||
Option{Label: "Clear all"},
|
||||
)
|
||||
}
|
||||
opts = append(opts, Option{Label: "Done"})
|
||||
|
||||
idx, ok, err := u.Select(title, sub, opts, len(opts)-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok || opts[idx].Label == "Done" {
|
||||
if len(work) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return work, nil
|
||||
}
|
||||
|
||||
switch opts[idx].Label {
|
||||
case "Add " + itemLabel:
|
||||
val, err := u.PromptString("New "+itemLabel, "", "", false, requireNonEmpty(itemLabel))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work = append(work, val)
|
||||
case "Edit " + itemLabel:
|
||||
itemOpts := make([]Option, len(work))
|
||||
for i, item := range work {
|
||||
itemOpts[i] = Option{Label: item}
|
||||
}
|
||||
eIdx, eOK, err := u.Select("Edit which "+itemLabel+"?", "", itemOpts, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if eOK {
|
||||
val, err := u.PromptString(itemLabel, work[eIdx], "", false, requireNonEmpty(itemLabel))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work[eIdx] = val
|
||||
}
|
||||
case "Remove " + itemLabel:
|
||||
itemOpts := make([]Option, len(work))
|
||||
for i, item := range work {
|
||||
itemOpts[i] = Option{Label: item}
|
||||
}
|
||||
rIdx, rOK, err := u.Select("Remove which "+itemLabel+"?", "", itemOpts, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rOK {
|
||||
work = append(work[:rIdx], work[rIdx+1:]...)
|
||||
}
|
||||
case "Clear all":
|
||||
work = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func requireNonEmpty(field string) func(string) error {
|
||||
return func(v string) error {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
return fmt.Errorf("%s cannot be empty", field)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue