Harden core packages and add interactive CLI config builder (rud config/validate/test)

This commit is contained in:
tyuXX 2026-11-19 13:05:26 +00:00
parent d37503c863
commit 99e24be6c9
29 changed files with 6763 additions and 165 deletions

View file

@ -21,9 +21,11 @@ import (
)
type ruleState struct {
Active bool
ActiveSince time.Time
LastFiredAt time.Time
Active bool
Notified bool
ActiveSince time.Time
LastFiredAt time.Time
LastTriggeredIDs []string
}
// EventPayload is passed to webhook body templates and command templates when an event triggers or resolves.
@ -85,27 +87,35 @@ func (e *Engine) Evaluate(ctx context.Context, snap store.Snapshot) {
matched, matchedIDs := e.evalCondition(ev.ID, "root", ev.Condition, snap, now)
if matched {
cooldown := ev.Cooldown.Std()
canFire := !st.Active && (st.LastFiredAt.IsZero() || cooldown <= 0 || now.Sub(st.LastFiredAt) >= cooldown)
if !st.Active {
st.Active = true
st.ActiveSince = now
}
if canFire {
cooldownOK := st.LastFiredAt.IsZero() || cooldown <= 0 || now.Sub(st.LastFiredAt) >= cooldown
if !st.Notified && cooldownOK {
st.Notified = true
st.LastFiredAt = now
st.LastTriggeredIDs = append([]string(nil), matchedIDs...)
payload := buildPayload(ev, "TRIGGERED", matchedIDs, snap, now)
e.dispatchActions(ctx, ev.ID, payload, ev.Actions)
}
} else {
if st.Active {
st.Active = false
st.Active = false
if st.Notified {
st.Notified = false
if ev.TriggerOnRecovery {
actions := ev.RecoveryActions
if len(actions) == 0 {
actions = ev.Actions
}
payload := buildPayload(ev, "RESOLVED", matchedIDs, snap, now)
recoveryIDs := st.LastTriggeredIDs
if len(recoveryIDs) == 0 {
recoveryIDs = matchedIDs
}
payload := buildPayload(ev, "RESOLVED", recoveryIDs, snap, now)
e.dispatchActions(ctx, ev.ID, payload, actions)
}
st.LastTriggeredIDs = nil
}
}
}
@ -143,15 +153,14 @@ func (e *Engine) evalCondition(eventID, path string, cond config.EventCondition,
return anyMatched, collected
}
// Default: "and"
if len(cond.Conditions) == 0 {
return false, nil
}
// Default: "and" — evaluate all children so sibling metric 'for' timers reset when metrics recover
allMatched := true
for i, sub := range cond.Conditions {
subPath := fmt.Sprintf("%s.%d", path, i)
ok, ids := e.evalCondition(eventID, subPath, sub, snap, now)
if !ok {
return false, nil
allMatched = false
continue
}
for _, id := range ids {
if !seen[id] {
@ -160,6 +169,9 @@ func (e *Engine) evalCondition(eventID, path string, cond config.EventCondition,
}
}
}
if !allMatched {
return false, nil
}
return true, collected
}
@ -426,7 +438,7 @@ func executeCommand(ctx context.Context, act config.EventAction, payload EventPa
}
func renderTemplate(tmplStr string, data EventPayload) (string, error) {
t, err := template.New("action").Parse(tmplStr)
t, err := template.New("action").Funcs(config.ActionTemplateFuncMap()).Parse(tmplStr)
if err != nil {
return "", err
}

View file

@ -2,6 +2,7 @@ package events
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
@ -38,7 +39,7 @@ func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) {
TriggerOnRecovery: true,
Condition: config.EventCondition{
Operator: "or",
Conditions: [ ]config.EventCondition{
Conditions: []config.EventCondition{
// Monitors 1, 2, 3 are all down
{
Type: "state",
@ -148,5 +149,134 @@ func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) {
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()
}