package events import ( "context" "encoding/json" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "testing" "time" "git.gsdistance.org/tyuXX/RUD/internal/config" "git.gsdistance.org/tyuXX/RUD/internal/store" ) func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) { var webhookMu sync.Mutex var webhookBodies []string ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b, _ := io.ReadAll(r.Body) webhookMu.Lock() webhookBodies = append(webhookBodies, string(b)) webhookMu.Unlock() w.WriteHeader(http.StatusOK) })) defer ts.Close() tmpFile := filepath.Join(t.TempDir(), "cmd_alert.txt") evCfg := []config.EventConfig{ { ID: "multi-or-sustained", Name: "Multi Monitor Down or 5h Outage", Cooldown: config.NewDuration(10 * time.Minute), TriggerOnRecovery: true, Condition: config.EventCondition{ Operator: "or", Conditions: []config.EventCondition{ // Monitors 1, 2, 3 are all down { Type: "state", Monitors: []string{"1", "2", "3"}, Match: "all", State: "down", }, // Any monitor down for >= 5 hours AND uptime_pct < 90 { Operator: "and", Conditions: []config.EventCondition{ { Type: "state", Monitors: []string{"*"}, Match: "any", State: "down", For: config.NewDuration(5 * time.Hour), }, { Type: "metric", Monitors: []string{"*"}, Match: "any", Metric: "uptime_pct", Comparator: "<", Value: 90.0, }, }, }, }, }, Actions: []config.EventAction{ { Type: "webhook", URL: ts.URL, BodyTemplate: `{"event":"{{.EventID}}","status":"{{.Status}}","monitors":"{{.TriggeredMonitors}}"}`, }, { Type: "command", Command: "printf '%s:%s' '{{.Status}}' '{{.TriggeredMonitors}}' > " + tmpFile, Shell: true, }, }, }, } eng := NewEngine(evCfg) now := time.Now().UTC() // Case 1: Only monitor 1 and 2 are down for 1 minute (should NOT trigger) snap1 := store.Snapshot{ OverallState: store.StateDown, UpdatedAt: now, Monitors: []store.MonitorState{ {ID: "1", State: store.StateDown, StateChangedAt: now.Add(-time.Minute), UptimePct: 95}, {ID: "2", State: store.StateDown, StateChangedAt: now.Add(-time.Minute), UptimePct: 95}, {ID: "3", State: store.StateUp, StateChangedAt: now.Add(-time.Hour), UptimePct: 100}, }, } snap1.MonitorsByID = map[string]store.MonitorState{ "1": snap1.Monitors[0], "2": snap1.Monitors[1], "3": snap1.Monitors[2], } eng.Evaluate(context.Background(), snap1) eng.Wait() webhookMu.Lock() if len(webhookBodies) != 0 { t.Fatalf("expected 0 webhook calls, got %d", len(webhookBodies)) } webhookMu.Unlock() // Case 2: Monitor 1 has been down for 5h10m and uptime_pct is 80% (SHOULD trigger!) snap2 := snap1 snap2.Monitors[0].StateChangedAt = now.Add(-5*time.Hour - 10*time.Minute) snap2.Monitors[0].UptimePct = 80.0 snap2.MonitorsByID["1"] = snap2.Monitors[0] eng.Evaluate(context.Background(), snap2) eng.Wait() webhookMu.Lock() if len(webhookBodies) != 1 { t.Fatalf("expected 1 webhook call on sustained 5h + metric trigger, got %d", len(webhookBodies)) } if !strings.Contains(webhookBodies[0], `"status":"TRIGGERED"`) { t.Fatalf("unexpected webhook body: %s", webhookBodies[0]) } webhookMu.Unlock() cmdData, err := os.ReadFile(tmpFile) if err != nil || !strings.HasPrefix(string(cmdData), "TRIGGERED:") { t.Fatalf("expected command action output TRIGGERED:..., got %q (err=%v)", string(cmdData), err) } // Case 3: All monitors recover -> should fire RESOLVED snap3 := snap1 for i := range snap3.Monitors { snap3.Monitors[i].State = store.StateUp snap3.Monitors[i].UptimePct = 99.9 snap3.MonitorsByID[snap3.Monitors[i].ID] = snap3.Monitors[i] } eng.Evaluate(context.Background(), snap3) eng.Wait() webhookMu.Lock() if len(webhookBodies) != 2 || !strings.Contains(webhookBodies[1], `"status":"RESOLVED"`) { t.Fatalf("expected recovery webhook call, got %v", webhookBodies) } if !strings.Contains(webhookBodies[1], `"monitors":"1"`) { t.Fatalf("expected recovery payload to preserve triggered monitors, got %s", webhookBodies[1]) } webhookMu.Unlock() } func TestCooldownFlapAndAndTimerResetAndJSONTemplate(t *testing.T) { var mu sync.Mutex var payloads []EventPayload ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) var decoded struct { Event string `json:"event"` Status string `json:"status"` } if err := json.Unmarshal(body, &decoded); err != nil { t.Errorf("invalid JSON produced by body_template: %v (body=%s)", err, string(body)) } w.WriteHeader(http.StatusOK) })) defer ts.Close() evCfg := []config.EventConfig{ { ID: "cooldown-rule", Name: `Quote "Test" Alert`, Cooldown: config.NewDuration(10 * time.Minute), TriggerOnRecovery: true, Condition: config.EventCondition{ Operator: "and", Conditions: []config.EventCondition{ { Type: "state", Monitors: []string{"m1"}, Match: "all", State: "down", }, { Type: "metric", Monitors: []string{"m1"}, Match: "all", Metric: "latency_ms", Comparator: ">", Value: 100, For: config.NewDuration(2 * time.Minute), }, }, }, Actions: []config.EventAction{ { Type: "webhook", URL: ts.URL, BodyTemplate: `{"event":{{json .EventName}},"status":"{{jsonStr .Status}}"}`, }, }, }, } eng := NewEngine(evCfg) eng.ActionHook = func(eventID, status, actionType string, payload EventPayload) { mu.Lock() payloads = append(payloads, payload) mu.Unlock() } mkSnap := func(ts time.Time, state string, latency float64) store.Snapshot { m := store.MonitorState{ID: "m1", State: state, StateChangedAt: ts, LatencyMs: latency} return store.Snapshot{ OverallState: state, UpdatedAt: ts, Monitors: []store.MonitorState{m}, MonitorsByID: map[string]store.MonitorState{"m1": m}, } } t0 := time.Now().UTC() // Start latency high while state=down -> starts metric 'for' timer at t0 eng.Evaluate(context.Background(), mkSnap(t0, store.StateDown, 250)) // At t0+3m condition holds (>= 2m) -> fires TRIGGERED eng.Evaluate(context.Background(), mkSnap(t0.Add(3*time.Minute), store.StateDown, 250)) eng.Wait() // Recover at t0+4m -> fires RESOLVED eng.Evaluate(context.Background(), mkSnap(t0.Add(4*time.Minute), store.StateUp, 10)) eng.Wait() // Within cooldown (t0+5m): state=up (first condition false!), latency=250 (second condition true) eng.Evaluate(context.Background(), mkSnap(t0.Add(5*time.Minute), store.StateUp, 250)) // At t0+6m: latency drops back to 20 -> 'and' must still evaluate child 1 to reset its 'for' timer! eng.Evaluate(context.Background(), mkSnap(t0.Add(6*time.Minute), store.StateUp, 20)) // At t0+7m: flap inside cooldown (down + latency 250) -> suppressed, and NO spurious RESOLVED on recovery at t0+8m eng.Evaluate(context.Background(), mkSnap(t0.Add(7*time.Minute), store.StateDown, 250)) eng.Evaluate(context.Background(), mkSnap(t0.Add(8*time.Minute), store.StateUp, 20)) eng.Wait() mu.Lock() if len(payloads) != 2 { t.Fatalf("expected 2 alerts (TRIGGERED, RESOLVED) before cooldown flap, got %d: %+v", len(payloads), payloads) } mu.Unlock() // At t0+14m (after 10m cooldown elapsed), start outage again: latency timer must require a full 2m (should NOT fire at t0+14m even though t0+5m was >2m ago!) eng.Evaluate(context.Background(), mkSnap(t0.Add(14*time.Minute), store.StateDown, 250)) eng.Wait() mu.Lock() if len(payloads) != 2 { t.Fatalf("expected stale metric timer to have been reset, got premature alert count=%d", len(payloads)) } mu.Unlock() // At t0+16m30s (held for 2m30s), should fire TRIGGERED eng.Evaluate(context.Background(), mkSnap(t0.Add(16*time.Minute+30*time.Second), store.StateDown, 250)) eng.Wait() mu.Lock() if len(payloads) != 3 || payloads[2].Status != "TRIGGERED" { t.Fatalf("expected 3rd alert TRIGGERED after cooldown + sustained 2m, got %+v", payloads) } mu.Unlock() // Recover at t0+17m -> fires RESOLVED (count=4) eng.Evaluate(context.Background(), mkSnap(t0.Add(17*time.Minute), store.StateUp, 10)) // Re-enter outage during cooldown at t0+18m -> suppressed initially, then persists past t0+26m30s -> should fire! eng.Evaluate(context.Background(), mkSnap(t0.Add(18*time.Minute), store.StateDown, 250)) eng.Evaluate(context.Background(), mkSnap(t0.Add(27*time.Minute), store.StateDown, 250)) eng.Wait() mu.Lock() if len(payloads) != 5 || payloads[4].Status != "TRIGGERED" { t.Fatalf("expected outage started during cooldown to fire once cooldown expires, got %+v", payloads) } mu.Unlock() }