diff --git a/README.md b/README.md index 8738a04..a9a923c 100644 --- a/README.md +++ b/README.md @@ -14,21 +14,10 @@ Compiles to a single static binary, checks `http`/`https`, `tcp`, `ping`, `dns`, ```bash go build -trimpath -ldflags="-s -w" -o rud . - -./rud config -config rud.json # interactive config builder (new or edit) -./rud validate -config rud.json # validate & lint configuration -./rud test -config rud.json # run one-shot live checks -./rud -config rud.json # run server (auto-generates rud.json if missing) +./rud -config rud.json # auto-generates rud.json if missing ``` -Then open `http://localhost:8080/` (HTML), `http://localhost:8080/monitor` (per-monitor history & charts), or `http://localhost:8080/?format=json` (JSON). - -#### CLI Subcommands - -- `./rud config [-config path] [-new] [-plain] [-no-color]`: Interactive configuration builder (arrow-key navigation on TTYs with automatic numbered fallback; `-new` forces the starter template / quick-start wizard). -- `./rud validate [-config path] [-strict]`: Validates schema, regexes, URLs, and alert templates, and reports lint warnings (unknown JSON fields, dangling monitor IDs). `-strict` treats lint warnings as errors. -- `./rud test [-config path] [-json] [-no-retry] [monitor-ids...]`: Executes live monitor checks once and prints results (exits non-zero if any tested monitor is `down`). -- `./rud -init -config rud.json`: Non-interactively writes a default `rud.json` and exits. +Then open `http://localhost:8080/` (HTML) or `http://localhost:8080/?format=json` (JSON). ### Docker Compose diff --git a/internal/builder/builder.go b/internal/builder/builder.go deleted file mode 100644 index 7736e00..0000000 --- a/internal/builder/builder.go +++ /dev/null @@ -1,449 +0,0 @@ -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 -} diff --git a/internal/builder/builder_test.go b/internal/builder/builder_test.go deleted file mode 100644 index d3f7d3b..0000000 --- a/internal/builder/builder_test.go +++ /dev/null @@ -1,355 +0,0 @@ -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) - } -} diff --git a/internal/builder/editors_core.go b/internal/builder/editors_core.go deleted file mode 100644 index ef26fe7..0000000 --- a/internal/builder/editors_core.go +++ /dev/null @@ -1,405 +0,0 @@ -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: "Daily history logs dir", Description: cfg.Storage.LogsDir}, - {Label: "Stats SQLite DB path", Description: cfg.Storage.StatsDB}, - {Label: "Stats retention days", Description: fmt.Sprintf("%d days", cfg.Storage.StatsRetentionDays)}, - {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 - case 7: - v, err := ui.PromptString("Daily history logs directory", cfg.Storage.LogsDir, "directory path, or 'off' to disable", true, nil) - if err != nil { - return err - } - cfg.Storage.LogsDir = v - case 8: - v, err := ui.PromptString("Stats SQLite DB path", cfg.Storage.StatsDB, "file path, or 'off' to disable", true, nil) - if err != nil { - return err - } - cfg.Storage.StatsDB = v - case 9: - curDays := cfg.Storage.StatsRetentionDays - if curDays <= 0 { - curDays = 90 - } - days, err := ui.PromptInt("Stats retention days", curDays, 1, 3650) - if err != nil { - return err - } - cfg.Storage.StatsRetentionDays = days - } - } -} - -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() -} diff --git a/internal/builder/editors_events.go b/internal/builder/editors_events.go deleted file mode 100644 index a18ffbb..0000000 --- a/internal/builder/editors_events.go +++ /dev/null @@ -1,1052 +0,0 @@ -package builder - -import ( - "fmt" - "strings" - "text/template" - "time" - - "git.gsdistance.org/tyuXX/RUD/internal/config" -) - -func editEvents(ui *UI, cfg *config.Config) error { - for { - sub := fmt.Sprintf("%d event rule(s) configured", len(cfg.Events)) - opts := []Option{ - {Label: "Add event rule", Description: "Use a quick recipe or build a custom AND/OR rule"}, - } - if len(cfg.Events) > 0 { - opts = append(opts, - Option{Label: "Edit event rule", Description: "Modify conditions, actions, cooldown, or recovery"}, - Option{Label: "Duplicate event rule"}, - Option{Label: "Delete event rule"}, - ) - } - opts = append(opts, Option{Label: "Back to main hub"}) - - idx, ok, err := ui.Select("Events & Alerts", 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 event rule": - if err := addEventFlow(ui, cfg); err != nil { - return err - } - case "Edit event rule": - eIdx, eOK, err := pickEvent(ui, cfg.Events, "Select event rule to edit") - if err != nil { - return err - } - if eOK { - if err := editSingleEvent(ui, cfg, eIdx); err != nil { - return err - } - } - case "Duplicate event rule": - eIdx, eOK, err := pickEvent(ui, cfg.Events, "Select event rule to duplicate") - if err != nil { - return err - } - if eOK { - cp := cloneEvent(cfg.Events[eIdx]) - defID := uniqueEventID(cfg, cp.ID+"-copy") - newID, err := ui.PromptString("New event ID", defID, "unique identifier", false, validateNewEventID(cfg, -1)) - if err != nil { - return err - } - cp.ID = newID - cp.Name = cp.Name + " (Copy)" - cfg.Events = append(cfg.Events, cp) - ui.Ok(fmt.Sprintf("Duplicated event %q as %q.", cfg.Events[eIdx].ID, cp.ID)) - } - case "Delete event rule": - eIdx, eOK, err := pickEvent(ui, cfg.Events, "Select event rule to delete") - if err != nil { - return err - } - if eOK { - target := cfg.Events[eIdx] - yes, err := ui.Confirm(fmt.Sprintf("Delete event %q (%s)?", target.ID, target.Name), false) - if err != nil { - return err - } - if yes { - cfg.Events = append(cfg.Events[:eIdx], cfg.Events[eIdx+1:]...) - ui.Ok(fmt.Sprintf("Deleted event %q.", target.ID)) - } - } - } - } -} - -func pickEvent(ui *UI, events []config.EventConfig, title string) (int, bool, error) { - opts := make([]Option, len(events)) - for i, ev := range events { - opts[i] = Option{ - Label: fmt.Sprintf("%s — %s", ev.ID, ev.Name), - Description: summarizeCondition(ev.Condition), - } - } - return ui.Select(title, "", opts, -1) -} - -func addEventFlow(ui *UI, cfg *config.Config) error { - recipeOpts := []Option{ - {Label: "Any monitor down for a sustained duration", Description: "e.g. any monitor down for 5m"}, - {Label: "All selected monitors down simultaneously", Description: "e.g. primary + backup both down"}, - {Label: "Uptime percentage drops below threshold", Description: "metric: uptime_pct < X%"}, - {Label: "High latency alert", Description: "metric: latency_ms > Xms"}, - {Label: "Consecutive failures threshold", Description: "metric: consecutive_failures >= N"}, - {Label: "Custom / Composite (AND / OR) rule", Description: "Build arbitrary nested conditions"}, - {Label: "Cancel"}, - } - - rIdx, rOK, err := ui.Select("New Event Rule — Choose Recipe", "Start from a common alerting pattern or build a custom tree", recipeOpts, 0) - if err != nil { - return err - } - if !rOK || rIdx == len(recipeOpts)-1 { - return nil - } - - defID := uniqueEventID(cfg, fmt.Sprintf("event-%d", len(cfg.Events)+1)) - id, err := ui.PromptString("Event ID", defID, "unique slug", false, validateNewEventID(cfg, -1)) - if err != nil { - return err - } - - var defaultName string - var cond config.EventCondition - - switch rIdx { - case 0: // Any down for duration - mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"}) - if err != nil { - return err - } - if !mOK { - return nil - } - forDur, err := ui.PromptDuration("Sustained outage duration (for)", config.NewDuration(5*time.Minute), true) - if err != nil { - return err - } - cond = config.EventCondition{Type: "state", Monitors: mons, Match: "any", State: "down", For: forDur} - defaultName = "Monitor Down Alert" - case 1: // All selected down - mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"}) - if err != nil { - return err - } - if !mOK { - return nil - } - forDur, err := ui.PromptDuration("Sustained duration (for)", 0, true) - if err != nil { - return err - } - cond = config.EventCondition{Type: "state", Monitors: mons, Match: "all", State: "down", For: forDur} - defaultName = "All Selected Monitors Down" - case 2: // Uptime < X% - mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"}) - if err != nil { - return err - } - if !mOK { - return nil - } - val, err := ui.PromptFloat("Uptime percentage threshold (<)", 99.0) - if err != nil { - return err - } - forDur, err := ui.PromptDuration("Sustained duration (for)", config.NewDuration(15*time.Minute), true) - if err != nil { - return err - } - cond = config.EventCondition{Type: "metric", Monitors: mons, Match: "any", Metric: "uptime_pct", Comparator: "<", Value: val, For: forDur} - defaultName = fmt.Sprintf("Uptime Below %.1f%%", val) - case 3: // High latency > Xms - mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"}) - if err != nil { - return err - } - if !mOK { - return nil - } - val, err := ui.PromptFloat("Latency threshold in ms (>)", 500.0) - if err != nil { - return err - } - forDur, err := ui.PromptDuration("Sustained duration (for)", config.NewDuration(2*time.Minute), true) - if err != nil { - return err - } - cond = config.EventCondition{Type: "metric", Monitors: mons, Match: "any", Metric: "latency_ms", Comparator: ">", Value: val, For: forDur} - defaultName = fmt.Sprintf("High Latency (> %.0fms)", val) - case 4: // Consecutive failures >= N - mons, mOK, err := selectConditionMonitors(ui, cfg, []string{"*"}) - if err != nil { - return err - } - if !mOK { - return nil - } - cnt, err := ui.PromptInt("Consecutive failures (>=)", 3, 1, 1000) - if err != nil { - return err - } - cond = config.EventCondition{Type: "metric", Monitors: mons, Match: "any", Metric: "consecutive_failures", Comparator: ">=", Value: float64(cnt)} - defaultName = fmt.Sprintf("Consecutive Failures (>= %d)", cnt) - case 5: // Custom composite rule - opOpts := []Option{ - {Label: "or", Description: "Trigger when ANY child condition matches"}, - {Label: "and", Description: "Trigger only when ALL child conditions match"}, - } - opIdx, opOK, err := ui.Select("Root Boolean Operator", "", opOpts, 0) - if err != nil { - return err - } - if !opOK { - return nil - } - cond = config.EventCondition{ - Operator: opOpts[opIdx].Label, - Conditions: []config.EventCondition{ - {Type: "state", Monitors: []string{"*"}, Match: "any", State: "down"}, - }, - } - defaultName = "Custom Alert Rule" - } - - name, err := ui.PromptString("Event name", defaultName, "human-readable title", false, requireNonEmpty("name")) - if err != nil { - return err - } - cooldown, err := ui.PromptDuration("Alert cooldown", config.NewDuration(30*time.Minute), true) - if err != nil { - return err - } - recovery, err := ui.Confirm("Send RESOLVED notification on recovery?", true) - if err != nil { - return err - } - - ev := config.EventConfig{ - ID: id, - Name: name, - Cooldown: cooldown, - TriggerOnRecovery: recovery, - Condition: cond, - Actions: []config.EventAction{}, - } - - if rIdx == 5 { - if err := editConditionTree(ui, cfg, &ev.Condition); err != nil { - return err - } - } - - ui.Info("Now add at least one notification action (webhook or command) for this event:") - if err := addActionFlow(ui, &ev.Actions); err != nil { - return err - } - - cfg.Events = append(cfg.Events, ev) - ui.Ok(fmt.Sprintf("Added event rule %q.", ev.ID)) - return nil -} - -func editSingleEvent(ui *UI, cfg *config.Config, evIdx int) error { - for { - ev := &cfg.Events[evIdx] - sub := fmt.Sprintf("Cooldown: %s | Recovery: %v | Actions: %d | Condition: %s", - ev.Cooldown.Std(), ev.TriggerOnRecovery, len(ev.Actions), summarizeCondition(ev.Condition)) - opts := []Option{ - {Label: "Edit basic settings", Description: fmt.Sprintf("id=%s, name=%q, cooldown=%s", ev.ID, ev.Name, ev.Cooldown.Std())}, - {Label: "Edit condition tree", Description: summarizeCondition(ev.Condition)}, - {Label: "Edit alert actions", Description: fmt.Sprintf("%d action(s)", len(ev.Actions))}, - {Label: "Edit recovery actions (optional)", Description: fmt.Sprintf("%d recovery action(s)", len(ev.RecoveryActions))}, - {Label: "Done"}, - } - - idx, ok, err := ui.Select("Edit Event: "+ev.ID, sub, opts, len(opts)-1) - if err != nil { - return err - } - if !ok || idx == len(opts)-1 { - return nil - } - - switch idx { - case 0: - newID, err := ui.PromptString("Event ID", ev.ID, "unique ID", false, validateNewEventID(cfg, evIdx)) - if err != nil { - return err - } - newName, err := ui.PromptString("Event name", ev.Name, "", false, requireNonEmpty("name")) - if err != nil { - return err - } - cd, err := ui.PromptDuration("Cooldown", ev.Cooldown, true) - if err != nil { - return err - } - rec, err := ui.Confirm("Trigger notification on recovery?", ev.TriggerOnRecovery) - if err != nil { - return err - } - ev.ID = newID - ev.Name = newName - ev.Cooldown = cd - ev.TriggerOnRecovery = rec - case 1: - if err := editConditionTree(ui, cfg, &ev.Condition); err != nil { - return err - } - case 2: - if err := editActionsList(ui, "Alert Actions: "+ev.ID, &ev.Actions); err != nil { - return err - } - case 3: - if err := editActionsList(ui, "Recovery Actions (empty = reuse alert actions): "+ev.ID, &ev.RecoveryActions); err != nil { - return err - } - } - } -} - -type flatCondNode struct { - ptr *config.EventCondition - parent *config.EventCondition - childIdx int - treeLabel string - summary string -} - -func flattenConditionTree(node, parent *config.EventCondition, childIdx int, indent string, isLast bool, isRoot bool, out *[]flatCondNode) { - connector := "" - nextIndent := indent - if !isRoot { - if isLast { - connector = indent + "└─ " - nextIndent = indent + " " - } else { - connector = indent + "├─ " - nextIndent = indent + "│ " - } - } - - var summary string - if len(node.Conditions) > 0 { - op := strings.ToUpper(strings.TrimSpace(node.Operator)) - if op == "" { - op = "AND" - } - summary = fmt.Sprintf("%s (%d child condition(s))", op, len(node.Conditions)) - } else { - summary = summarizeCondition(*node) - } - - *out = append(*out, flatCondNode{ - ptr: node, - parent: parent, - childIdx: childIdx, - treeLabel: connector + summary, - summary: summary, - }) - - for i := range node.Conditions { - flattenConditionTree(&node.Conditions[i], node, i, nextIndent, i == len(node.Conditions)-1, false, out) - } -} - -func editConditionTree(ui *UI, cfg *config.Config, root *config.EventCondition) error { - for { - var nodes []flatCondNode - flattenConditionTree(root, nil, -1, "", true, true, &nodes) - - opts := make([]Option, 0, len(nodes)+1) - for _, n := range nodes { - opts = append(opts, Option{Label: n.treeLabel}) - } - opts = append(opts, Option{Label: "Done editing condition tree"}) - - idx, ok, err := ui.Select("Condition Tree Editor", "Select any node to edit, wrap into AND/OR, add children, or delete", opts, len(opts)-1) - if err != nil { - return err - } - if !ok || idx == len(opts)-1 { - return nil - } - - node := nodes[idx] - if len(node.ptr.Conditions) > 0 { - if err := editGroupConditionNode(ui, cfg, node); err != nil { - return err - } - } else { - if err := editLeafConditionNode(ui, cfg, node); err != nil { - return err - } - } - } -} - -func editGroupConditionNode(ui *UI, cfg *config.Config, node flatCondNode) error { - curOp := strings.ToLower(strings.TrimSpace(node.ptr.Operator)) - if curOp == "" { - curOp = "and" - } - otherOp := "or" - if curOp == "or" { - otherOp = "and" - } - - opts := []Option{ - {Label: fmt.Sprintf("Switch operator (%s -> %s)", strings.ToUpper(curOp), strings.ToUpper(otherOp))}, - {Label: "Add child leaf condition (state or metric)"}, - {Label: "Add nested AND/OR group"}, - } - if node.parent != nil && len(node.parent.Conditions) > 1 { - opts = append(opts, Option{Label: "Delete this group"}) - } - opts = append(opts, Option{Label: "Back"}) - - idx, ok, err := ui.Select("Group Node: "+strings.ToUpper(curOp), "", opts, len(opts)-1) - if err != nil { - return err - } - if !ok || opts[idx].Label == "Back" { - return nil - } - - switch opts[idx].Label { - case fmt.Sprintf("Switch operator (%s -> %s)", strings.ToUpper(curOp), strings.ToUpper(otherOp)): - node.ptr.Operator = otherOp - ui.Ok("Switched group operator to " + strings.ToUpper(otherOp) + ".") - case "Add child leaf condition (state or metric)": - leaf := config.EventCondition{Type: "state", Monitors: []string{"*"}, Match: "any", State: "down"} - if saved, err := editLeafConditionForm(ui, cfg, &leaf); err != nil { - return err - } else if saved { - node.ptr.Conditions = append(node.ptr.Conditions, leaf) - } - case "Add nested AND/OR group": - opOpts := []Option{{Label: "or"}, {Label: "and"}} - oIdx, oOK, err := ui.Select("Nested Group Operator", "", opOpts, 0) - if err != nil { - return err - } - if oOK { - leaf := config.EventCondition{Type: "state", Monitors: []string{"*"}, Match: "any", State: "down"} - if saved, err := editLeafConditionForm(ui, cfg, &leaf); err != nil { - return err - } else if saved { - node.ptr.Conditions = append(node.ptr.Conditions, config.EventCondition{ - Operator: opOpts[oIdx].Label, - Conditions: []config.EventCondition{leaf}, - }) - } - } - case "Delete this group": - if node.parent != nil && node.childIdx >= 0 && node.childIdx < len(node.parent.Conditions) { - node.parent.Conditions = append(node.parent.Conditions[:node.childIdx], node.parent.Conditions[node.childIdx+1:]...) - } - } - return nil -} - -func editLeafConditionNode(ui *UI, cfg *config.Config, node flatCondNode) error { - opts := []Option{ - {Label: "Edit leaf parameters", Description: node.summary}, - {Label: "Wrap in new AND / OR group", Description: "Convert this leaf into a composite group containing it"}, - } - if node.parent != nil && len(node.parent.Conditions) > 1 { - opts = append(opts, Option{Label: "Delete this condition"}) - } - opts = append(opts, Option{Label: "Back"}) - - idx, ok, err := ui.Select("Leaf Node", node.summary, opts, 0) - if err != nil { - return err - } - if !ok || opts[idx].Label == "Back" { - return nil - } - - switch opts[idx].Label { - case "Edit leaf parameters": - _, err := editLeafConditionForm(ui, cfg, node.ptr) - return err - case "Wrap in new AND / OR group": - opOpts := []Option{ - {Label: "or", Description: "Group passes if ANY child passes"}, - {Label: "and", Description: "Group passes if ALL children pass"}, - } - oIdx, oOK, err := ui.Select("Group Operator", "", opOpts, 0) - if err != nil { - return err - } - if oOK { - oldLeaf := *node.ptr - *node.ptr = config.EventCondition{ - Operator: opOpts[oIdx].Label, - Conditions: []config.EventCondition{oldLeaf}, - } - ui.Ok("Wrapped leaf in " + strings.ToUpper(opOpts[oIdx].Label) + " group.") - } - case "Delete this condition": - if node.parent != nil && node.childIdx >= 0 && node.childIdx < len(node.parent.Conditions) { - node.parent.Conditions = append(node.parent.Conditions[:node.childIdx], node.parent.Conditions[node.childIdx+1:]...) - } - } - return nil -} - -func editLeafConditionForm(ui *UI, cfg *config.Config, cond *config.EventCondition) (bool, error) { - t := strings.ToLower(cond.Type) - if t == "" { - if cond.Metric != "" { - t = "metric" - } else { - t = "state" - } - } - typeOpts := []Option{ - {Label: "state", Description: "Monitor state equals up / degraded / down / pending"}, - {Label: "metric", Description: "Numeric metric threshold (uptime_pct, latency_ms, consecutive_failures)"}, - } - defT := 0 - if t == "metric" { - defT = 1 - } - tIdx, tOK, err := ui.Select("Condition Type", "", typeOpts, defT) - if err != nil { - return false, err - } - if !tOK { - return false, nil - } - - mons, mOK, err := selectConditionMonitors(ui, cfg, cond.Monitors) - if err != nil { - return false, err - } - if !mOK { - return false, nil - } - - matchOpts := []Option{ - {Label: "all", Description: "Every targeted monitor must match"}, - {Label: "any", Description: "At least one targeted monitor must match"}, - } - defMatch := 0 - if strings.EqualFold(cond.Match, "any") { - defMatch = 1 - } - maIdx, maOK, err := ui.Select("Match Mode", "", matchOpts, defMatch) - if err != nil { - return false, err - } - if !maOK { - return false, nil - } - - next := config.EventCondition{ - Type: typeOpts[tIdx].Label, - Monitors: mons, - Match: matchOpts[maIdx].Label, - } - - if next.Type == "state" { - stateOpts := []Option{{Label: "down"}, {Label: "degraded"}, {Label: "up"}, {Label: "pending"}} - defS := 0 - for i, o := range stateOpts { - if strings.EqualFold(o.Label, cond.State) { - defS = i - break - } - } - sIdx, sOK, err := ui.Select("Target State", "", stateOpts, defS) - if err != nil { - return false, err - } - if !sOK { - return false, nil - } - next.State = stateOpts[sIdx].Label - } else { - metricOpts := []Option{ - {Label: "uptime_pct", Description: "Monitor uptime percentage (0-100)"}, - {Label: "latency_ms", Description: "Latest latency in milliseconds"}, - {Label: "consecutive_failures", Description: "Consecutive failed checks"}, - } - defMet := 0 - for i, o := range metricOpts { - if strings.EqualFold(o.Label, cond.Metric) { - defMet = i - break - } - } - metIdx, metOK, err := ui.Select("Metric", "", metricOpts, defMet) - if err != nil { - return false, err - } - if !metOK { - return false, nil - } - next.Metric = metricOpts[metIdx].Label - - compOpts := []Option{ - {Label: "<"}, {Label: "<="}, {Label: ">"}, {Label: ">="}, {Label: "=="}, {Label: "!="}, - } - defC := 0 - for i, o := range compOpts { - if o.Label == cond.Comparator { - defC = i - break - } - } - cIdx, cOK, err := ui.Select("Comparator", "", compOpts, defC) - if err != nil { - return false, err - } - if !cOK { - return false, nil - } - next.Comparator = compOpts[cIdx].Label - - defVal := cond.Value - if cond.Metric == "" && next.Metric == "uptime_pct" { - defVal = 99.0 - } - val, err := ui.PromptFloat("Threshold value", defVal) - if err != nil { - return false, err - } - next.Value = val - } - - forDur, err := ui.PromptDuration("Sustained duration (for)", cond.For, true) - if err != nil { - return false, err - } - next.For = forDur - - *cond = next - return true, nil -} - -func selectConditionMonitors(ui *UI, cfg *config.Config, current []string) ([]string, bool, error) { - opts := []Option{{Label: "*", Description: "All monitors"}} - seenOpt := map[string]bool{"*": true} - for _, m := range cfg.Monitors { - opts = append(opts, Option{Label: m.ID, Description: m.Name}) - seenOpt[m.ID] = true - } - for _, id := range current { - if !seenOpt[id] { - opts = append(opts, Option{Label: id, Description: "(not currently defined in monitors)"}) - seenOpt[id] = true - } - } - - curSet := make(map[string]bool, len(current)) - for _, id := range current { - curSet[id] = true - } - if len(current) == 0 { - curSet["*"] = true - } - pre := make(map[int]bool) - for i, o := range opts { - if curSet[o.Label] { - pre[i] = true - } - } - - indices, ok, err := ui.MultiSelect("Target Monitors", "Choose '*' for all monitors or specific monitor IDs", opts, pre) - if err != nil || !ok { - return nil, ok, err - } - if len(indices) == 0 { - return []string{"*"}, true, nil - } - for _, idx := range indices { - if idx == 0 { - return []string{"*"}, true, nil - } - } - res := make([]string, 0, len(indices)) - for _, idx := range indices { - res = append(res, opts[idx].Label) - } - return res, true, nil -} - -func editActionsList(ui *UI, title string, actions *[]config.EventAction) error { - for { - sub := fmt.Sprintf("%d action(s)", len(*actions)) - opts := []Option{ - {Label: "Add action", Description: "Webhook preset, custom webhook, or shell command"}, - } - if len(*actions) > 0 { - opts = append(opts, - Option{Label: "Edit action"}, - Option{Label: "Delete action"}, - ) - } - opts = append(opts, Option{Label: "Done"}) - - idx, ok, err := ui.Select(title, sub, opts, len(opts)-1) - if err != nil { - return err - } - if !ok || opts[idx].Label == "Done" { - return nil - } - - switch opts[idx].Label { - case "Add action": - if err := addActionFlow(ui, actions); err != nil { - return err - } - case "Edit action": - aIdx, aOK, err := pickAction(ui, *actions, "Select action to edit") - if err != nil { - return err - } - if aOK { - if err := editActionForm(ui, &(*actions)[aIdx]); err != nil { - return err - } - } - case "Delete action": - aIdx, aOK, err := pickAction(ui, *actions, "Select action to delete") - if err != nil { - return err - } - if aOK { - *actions = append((*actions)[:aIdx], (*actions)[aIdx+1:]...) - } - } - } -} - -func pickAction(ui *UI, actions []config.EventAction, title string) (int, bool, error) { - opts := make([]Option, len(actions)) - for i, act := range actions { - desc := act.URL - if strings.EqualFold(act.Type, "command") || strings.EqualFold(act.Type, "cmd") || strings.EqualFold(act.Type, "script") { - desc = act.Command - } - opts[i] = Option{ - Label: fmt.Sprintf("[%d] %s", i+1, strings.ToUpper(act.Type)), - Description: desc, - } - } - return ui.Select(title, "", opts, -1) -} - -func addActionFlow(ui *UI, actions *[]config.EventAction) error { - opts := []Option{ - {Label: "Webhook from preset", Description: "Discord, Slack, ntfy, Gotify, or Generic JSON"}, - {Label: "Custom webhook", Description: "Configure URL, headers, and custom Go template manually"}, - {Label: "Shell command / script", Description: "Run a command with template placeholders & RUD_* env vars"}, - {Label: "Cancel"}, - } - idx, ok, err := ui.Select("Add Action", "", opts, 0) - if err != nil { - return err - } - if !ok || idx == 3 { - return nil - } - - switch idx { - case 0: - presets := WebhookPresets() - pOpts := make([]Option, len(presets)+1) - for i, p := range presets { - pOpts[i] = Option{Label: p.Name, Description: p.Description} - } - pOpts[len(presets)] = Option{Label: "Cancel"} - pIdx, pOK, err := ui.Select("Webhook Presets", "", pOpts, 0) - if err != nil { - return err - } - if !pOK || pIdx == len(presets) { - return nil - } - preset := presets[pIdx] - ui.Info("URL hint: " + preset.URLHint) - u, err := ui.PromptString("Webhook URL", "", "https://...", false, validateHTTPURL) - if err != nil { - return err - } - var hdrs map[string]string - if len(preset.Headers) > 0 { - hdrs = make(map[string]string, len(preset.Headers)) - for k, v := range preset.Headers { - hdrs[k] = v - } - } - act := config.EventAction{ - Type: "webhook", - URL: u, - HTTPMethod: preset.HTTPMethod, - Headers: hdrs, - BodyTemplate: preset.Template, - Timeout: config.NewDuration(10 * time.Second), - } - *actions = append(*actions, act) - ui.Ok("Added " + preset.Name + " action.") - case 1: - act := config.EventAction{ - Type: "webhook", - HTTPMethod: "POST", - Timeout: config.NewDuration(10 * time.Second), - } - if err := editActionForm(ui, &act); err != nil { - return err - } - if act.URL != "" { - *actions = append(*actions, act) - } - case 2: - act := config.EventAction{ - Type: "command", - Shell: true, - Timeout: config.NewDuration(10 * time.Second), - } - if err := editActionForm(ui, &act); err != nil { - return err - } - if act.Command != "" { - *actions = append(*actions, act) - } - } - return nil -} - -func editActionForm(ui *UI, act *config.EventAction) error { - ui.Header("Action Configuration", templateCheatsheet) - t := strings.ToLower(strings.TrimSpace(act.Type)) - if t == "webhook" { - u, err := ui.PromptString("Webhook URL", act.URL, "https://...", false, validateHTTPURL) - if err != nil { - return err - } - act.URL = u - - defM := act.HTTPMethod - if defM == "" { - defM = "POST" - } - hm, err := ui.PromptString("HTTP Method", defM, "POST, PUT, etc.", false, requireNonEmpty("http_method")) - if err != nil { - return err - } - act.HTTPMethod = strings.ToUpper(hm) - - tmpl, err := ui.PromptString("Body template (optional)", act.BodyTemplate, "empty sends default EventPayload JSON", true, validateActionTemplate) - if err != nil { - return err - } - act.BodyTemplate = tmpl - - editHdrs, err := ui.Confirm("Edit webhook headers?", len(act.Headers) > 0) - if err != nil { - return err - } - if editHdrs { - hdrs, err := ui.EditStringMap("Webhook Headers", act.Headers) - if err != nil { - return err - } - act.Headers = hdrs - } - - to, err := ui.PromptDuration("Action timeout", act.Timeout, true) - if err != nil { - return err - } - act.Timeout = to - return nil - } - - // Command action - cmdStr, err := ui.PromptString("Command", act.Command, "supports Go template placeholders", false, func(s string) error { - if strings.TrimSpace(s) == "" { - return fmt.Errorf("command cannot be empty") - } - return validateActionTemplate(s) - }) - if err != nil { - return err - } - act.Command = cmdStr - - sh, err := ui.Confirm("Execute via /bin/sh -c (shell)?", act.Shell) - if err != nil { - return err - } - act.Shell = sh - - if !sh { - editArgs, err := ui.Confirm("Edit command arguments?", len(act.Args) > 0) - if err != nil { - return err - } - if editArgs { - args, err := ui.EditStringSlice("Command Arguments", "argument", act.Args) - if err != nil { - return err - } - act.Args = args - } - } - - to, err := ui.PromptDuration("Action timeout", act.Timeout, true) - if err != nil { - return err - } - act.Timeout = to - return nil -} - -func validateActionTemplate(tmplStr string) error { - if tmplStr == "" { - return nil - } - _, err := template.New("action").Funcs(config.ActionTemplateFuncMap()).Parse(tmplStr) - return err -} - -func summarizeCondition(cond config.EventCondition) string { - if len(cond.Conditions) > 0 { - op := strings.ToUpper(strings.TrimSpace(cond.Operator)) - if op == "" { - op = "AND" - } - parts := make([]string, 0, len(cond.Conditions)) - for _, sub := range cond.Conditions { - parts = append(parts, summarizeCondition(sub)) - } - return "(" + strings.Join(parts, " "+op+" ") + ")" - } - mons := strings.Join(cond.Monitors, ",") - if mons == "" { - mons = "*" - } - match := strings.ToLower(strings.TrimSpace(cond.Match)) - if match == "" { - match = "all" - } - t := strings.ToLower(strings.TrimSpace(cond.Type)) - if t == "" { - if cond.Metric != "" { - t = "metric" - } else { - t = "state" - } - } - var base string - if t == "metric" { - base = fmt.Sprintf("METRIC: %s of [%s] %s %s %g", match, mons, cond.Metric, cond.Comparator, cond.Value) - } else { - base = fmt.Sprintf("STATE: %s of [%s] == %s", match, mons, cond.State) - } - if cond.For > 0 { - base += fmt.Sprintf(" (for %s)", cond.For.Std()) - } - return base -} - -func validateNewEventID(cfg *config.Config, excludeIdx int) func(string) error { - return func(id string) error { - trimmed := strings.TrimSpace(id) - if trimmed == "" { - return fmt.Errorf("event id cannot be empty") - } - if strings.ContainsAny(trimmed, " \t\r\n") { - return fmt.Errorf("event id cannot contain whitespace") - } - for i, ev := range cfg.Events { - if i != excludeIdx && ev.ID == trimmed { - return fmt.Errorf("event id %q already exists", trimmed) - } - } - return nil - } -} - -func uniqueEventID(cfg *config.Config, base string) string { - taken := make(map[string]bool, len(cfg.Events)) - for _, ev := range cfg.Events { - taken[ev.ID] = true - } - if !taken[base] { - return base - } - for n := 2; ; n++ { - cand := fmt.Sprintf("%s-%d", base, n) - if !taken[cand] { - return cand - } - } -} - -func cloneEvent(ev config.EventConfig) config.EventConfig { - cp := ev - cp.Condition = cloneCondition(ev.Condition) - cp.Actions = cloneActions(ev.Actions) - cp.RecoveryActions = cloneActions(ev.RecoveryActions) - return cp -} - -func cloneCondition(cond config.EventCondition) config.EventCondition { - cp := cond - if cond.Monitors != nil { - cp.Monitors = append([]string(nil), cond.Monitors...) - } - if cond.Conditions != nil { - cp.Conditions = make([]config.EventCondition, len(cond.Conditions)) - for i, sub := range cond.Conditions { - cp.Conditions[i] = cloneCondition(sub) - } - } - return cp -} - -func cloneActions(actions []config.EventAction) []config.EventAction { - if actions == nil { - return nil - } - out := make([]config.EventAction, len(actions)) - for i, a := range actions { - cp := a - if a.Args != nil { - cp.Args = append([]string(nil), a.Args...) - } - if a.Headers != nil { - cp.Headers = make(map[string]string, len(a.Headers)) - for k, v := range a.Headers { - cp.Headers[k] = v - } - } - if a.Env != nil { - cp.Env = make(map[string]string, len(a.Env)) - for k, v := range a.Env { - cp.Env[k] = v - } - } - out[i] = cp - } - return out -} diff --git a/internal/builder/editors_monitors.go b/internal/builder/editors_monitors.go deleted file mode 100644 index af24a30..0000000 --- a/internal/builder/editors_monitors.go +++ /dev/null @@ -1,841 +0,0 @@ -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 - } -} diff --git a/internal/builder/editors_page.go b/internal/builder/editors_page.go deleted file mode 100644 index 962ba56..0000000 --- a/internal/builder/editors_page.go +++ /dev/null @@ -1,651 +0,0 @@ -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