From 5f42e3e650be75290faf15b4773c95bb8c97824f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 01:23:37 +0100 Subject: [PATCH] feat(api): open incidents and notify channels when monitors go down Results are evaluated as they arrive. Transitions open or resolve the monitor's incident and queue a notification per enabled channel in the same transaction; every API replica delivers the outbox with leases and exponential retries. Organizations manage webhook and email channels, can send test notifications and list incidents. Email requires UPTIME_SMTP_URL. Closes #14 Closes #15 Closes #16 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- cmd/api/main.go | 5 + internal/api/agent.go | 22 ++- internal/api/alerting.go | 233 ++++++++++++++++++++++++++ internal/api/alerting_test.go | 198 ++++++++++++++++++++++ internal/api/channels.go | 299 ++++++++++++++++++++++++++++++++++ internal/api/monitors.go | 14 +- internal/api/server.go | 16 ++ internal/api/sso_test.go | 12 +- internal/config/config.go | 4 + internal/i18n/i18n_test.go | 12 ++ internal/i18n/locales/de.json | 10 ++ internal/i18n/locales/en.json | 10 ++ 12 files changed, 822 insertions(+), 13 deletions(-) create mode 100644 internal/api/alerting.go create mode 100644 internal/api/alerting_test.go create mode 100644 internal/api/channels.go diff --git a/cmd/api/main.go b/cmd/api/main.go index f3b33a1..cd73283 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -13,6 +13,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" + "git.zb-server.de/ZB-Server/uptimesebi/internal/notify" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" @@ -57,6 +58,9 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { if err != nil { return err } + if _, err := notify.ParseSMTP(cfg.SMTPURL); err != nil { + return err + } deps, err := platform.Connect(ctx, cfg.Storage, log) if err != nil { return err @@ -74,6 +78,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { r.StaticFS("/static", web.Static()) srv.Mount(r) go srv.RunScheduler(ctx) + go srv.RunNotifier(ctx) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) } diff --git a/internal/api/agent.go b/internal/api/agent.go index 15ca8a1..90ad3a9 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -187,18 +187,20 @@ func (s *Server) agentResults(c *gin.Context) { ids[i] = r.MonitorID } now := time.Now() + monitors := map[uuid.UUID]store.MonitorsForResultsRow{} + var accepted []agentapi.Result err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { - monitors, err := q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: region, Ids: ids}) + rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{Region: region, Ids: ids}) if err != nil { return err } - orgOf := make(map[uuid.UUID]uuid.UUID, len(monitors)) - for _, m := range monitors { - orgOf[m.ID] = m.OrgID + for _, m := range rows { + monitors[m.ID] = m } - rows := make([]store.InsertCheckResultsParams, 0, len(req.Results)) + params := make([]store.InsertCheckResultsParams, 0, len(req.Results)) for _, r := range req.Results { - org, ok := orgOf[r.MonitorID] + m, ok := monitors[r.MonitorID] + org := m.OrgID // A checker may only report monitors of its own region, and // timestamps far from now are rejected rather than skewing // history. @@ -215,18 +217,20 @@ func (s *Server) agentResults(c *gin.Context) { if r.Error != "" { row.Error = ptr(truncateValid(r.Error, 500)) } - rows = append(rows, row) + params = append(params, row) + accepted = append(accepted, r) } - if len(rows) == 0 { + if len(params) == 0 { return nil } - _, err = q.InsertCheckResults(ctx, rows) + _, err = q.InsertCheckResults(ctx, params) return err }) if err != nil { internalError(c, err) return } + s.evaluateResults(ctx, region, accepted, monitors) c.Status(http.StatusNoContent) } diff --git a/internal/api/alerting.go b/internal/api/alerting.go new file mode 100644 index 0000000..49af148 --- /dev/null +++ b/internal/api/alerting.go @@ -0,0 +1,233 @@ +package api + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate" + "git.zb-server.de/ZB-Server/uptimesebi/internal/notify" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const ( + maxNotifyAttempts = 10 + notifyBatch = 20 +) + +// evaluateResults feeds stored results to the evaluator in time order and +// acts on the resulting transitions. +func (s *Server) evaluateResults(ctx context.Context, region string, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) { + slices.SortFunc(results, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) }) + for _, r := range results { + m, ok := monitors[r.MonitorID] + if !ok { + continue + } + t, err := s.eval.Observe(ctx, evaluate.Observation{ + MonitorID: m.ID, Region: region, OK: r.OK, At: r.StartedAt, + Interval: time.Duration(m.IntervalSeconds) * time.Second, Confirmations: int(m.Confirmations), Regions: m.Regions, + }) + if err == nil && t != evaluate.None { + err = s.transition(ctx, m, t, r.StartedAt) + } + if err != nil { + // The next result re-evaluates; a missed transition only delays + // the alert by one interval. + s.log.ErrorContext(ctx, "evaluating result failed", "monitor", m.ID, "error", err) + } + } +} + +// transition opens or resolves the monitor's incident and queues a +// notification for every enabled channel of the org, in one transaction. +func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, t evaluate.Transition, at time.Time) error { + return s.db.Tx(ctx, tenant.Org(m.OrgID, uuid.Nil), func(q *store.Queries) error { + var ( + inc store.Incident + event string + err error + ) + switch t { + case evaluate.Down: + cause := map[string]string{} + latest, lerr := q.LatestResultsForMonitor(ctx, store.LatestResultsForMonitorParams{OrgID: m.OrgID, MonitorID: m.ID}) + if lerr != nil { + return lerr + } + for _, l := range latest { + if !l.Ok { + cause[l.Region] = deref(l.Error) + } + } + raw, _ := json.Marshal(cause) + inc, err = q.OpenIncident(ctx, store.OpenIncidentParams{OrgID: m.OrgID, MonitorID: m.ID, StartedAt: at, Cause: raw}) + event = notify.Opened + case evaluate.Up: + inc, err = q.ResolveIncident(ctx, store.ResolveIncidentParams{MonitorID: m.ID, ResolvedAt: &at}) + event = notify.Resolved + } + // No row means the incident already exists or is already resolved, + // e.g. after the evaluation state was lost; nothing to announce. + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return err + } + channels, err := q.ListEnabledChannelIDs(ctx, m.OrgID) + if err != nil { + return err + } + for _, ch := range channels { + if err := q.EnqueueNotification(ctx, store.EnqueueNotificationParams{OrgID: m.OrgID, ChannelID: ch, IncidentID: inc.ID, Event: event}); err != nil { + return err + } + } + s.log.InfoContext(ctx, "incident "+event, "monitor", m.ID, "incident", inc.ID, "channels", len(channels)) + return nil + }) +} + +// RunNotifier delivers queued notifications until ctx ends. Every API replica +// runs it; rows are leased so each is sent by one replica at a time. +func (s *Server) RunNotifier(ctx context.Context) { + tick := time.NewTicker(2 * time.Second) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil { + } + } + } +} + +func (s *Server) deliverBatch(ctx context.Context) int { + var rows []store.NotificationDetailsRow + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + ids, err := q.ClaimNotifications(ctx, notifyBatch) + if err != nil || len(ids) == 0 { + return err + } + rows, err = q.NotificationDetails(ctx, ids) + return err + }) + if err != nil { + if ctx.Err() == nil { + s.log.WarnContext(ctx, "claiming notifications failed", "error", err) + } + return 0 + } + for _, n := range rows { + sendErr := s.send(ctx, n.ChannelType, n.ChannelConfig, eventOf(n)) + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + if sendErr == nil { + return q.MarkNotificationSent(ctx, n.ID) + } + return q.MarkNotificationFailed(ctx, store.MarkNotificationFailedParams{ + ID: n.ID, LastError: ptr(truncateValid(sendErr.Error(), 500)), MaxAttempts: maxNotifyAttempts, + RetryInSeconds: int32(retryDelay(int(n.Attempts)).Seconds()), + }) + }) + if err != nil { + s.log.WarnContext(ctx, "recording notification result failed", "notification", n.ID, "error", err) + } + if sendErr != nil { + s.log.WarnContext(ctx, "notification failed", "notification", n.ID, "channel", n.ChannelID, "attempt", n.Attempts+1, "error", sendErr) + } + } + return len(rows) +} + +// retryDelay grows from 30 s to about four hours over ten attempts. +func retryDelay(attempts int) time.Duration { + return min(30*time.Second<.subject|body". +func TestEveryMailEventHasTexts(t *testing.T) { + en := catalogKeys(t)["en"] + for _, ev := range []string{"opened", "resolved", "test"} { + for _, part := range []string{"subject", "body"} { + if id := "email." + ev + "." + part; !en[id] { + t.Errorf("en.json is missing %q", id) + } + } + } +} + // The language switcher builds "lang." dynamically. func TestEveryLanguageHasAName(t *testing.T) { c, err := Load() diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index f4a1e12..9f6620f 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -32,9 +32,18 @@ "console.nav.tokens": "API-Tokens", "console.sso_required_action": "Mit SSO anmelden", "console.totp_missing_action": "Jetzt einrichten", + "email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.", + "email.opened.subject": "[DOWN] {{.Monitor}}", + "email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.", + "email.resolved.subject": "[UP] {{.Monitor}}", + "email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.", + "email.test.subject": "Testbenachrichtigung von uptimesebi", "error.agent_protocol_unsupported": "Diese Agent-Version wird von der API nicht unterstützt. Bitte den Agent aktualisieren.", "error.already_assigned": "Das Mitglied hat diese Rolle bereits.", "error.already_member": "Diese Person ist bereits Mitglied.", + "error.channel_test_failed": "Die Testbenachrichtigung konnte nicht zugestellt werden.", + "error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert werden.", + "error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.", "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.internal": "Interner Fehler.", @@ -56,6 +65,7 @@ "error.invalid_target": "Das Ziel passt nicht zu diesem Check-Typ.", "error.invalid_timeout": "Der Timeout muss zwischen 100 ms und 60 s liegen und kürzer als das Intervall sein.", "error.invalid_type": "Unbekannter Check-Typ.", + "error.invalid_webhook_url": "Die Webhook-URL muss eine https-URL ohne Zugangsdaten sein.", "error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.", "error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.", "error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 41979f2..3ff83ff 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -32,9 +32,18 @@ "console.nav.tokens": "API tokens", "console.sso_required_action": "Sign in with SSO", "console.totp_missing_action": "Set up now", + "email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.", + "email.opened.subject": "[DOWN] {{.Monitor}}", + "email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.", + "email.resolved.subject": "[UP] {{.Monitor}}", + "email.test.body": "This is a test. If you can read it, the channel works.", + "email.test.subject": "Test notification from uptimesebi", "error.agent_protocol_unsupported": "This agent version is not supported by the API. Please update the agent.", "error.already_assigned": "The member already has this role.", "error.already_member": "This person is already a member.", + "error.channel_test_failed": "The test notification could not be delivered.", + "error.channel_type_immutable": "The type of a channel cannot be changed.", + "error.email_not_configured": "Email is not available on this server.", "error.email_taken": "This email address is already registered.", "error.forbidden": "You are not allowed to do this.", "error.internal": "Internal error.", @@ -56,6 +65,7 @@ "error.invalid_target": "The target is not valid for this check type.", "error.invalid_timeout": "The timeout must be between 100 ms and 60 s and shorter than the interval.", "error.invalid_type": "Unknown check type.", + "error.invalid_webhook_url": "The webhook URL must be an https URL without credentials.", "error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.", "error.invitation_invalid": "This invitation is invalid, expired or was already used.", "error.keyword_needs_get": "Keyword checks need GET requests.",