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.", diff --git a/internal/migrations/sql/00015_alerting.sql b/internal/migrations/sql/00015_alerting.sql new file mode 100644 index 0000000..74e8dbb --- /dev/null +++ b/internal/migrations/sql/00015_alerting.sql @@ -0,0 +1,75 @@ +-- +goose Up +-- How many consecutive failures a region needs before it counts as down. +ALTER TABLE monitors ADD COLUMN confirmations integer NOT NULL DEFAULT 2 CHECK (confirmations BETWEEN 1 AND 10); + +CREATE TABLE incidents ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + monitor_id uuid NOT NULL REFERENCES monitors (id) ON DELETE CASCADE, + started_at timestamptz NOT NULL, + resolved_at timestamptz, + -- Last error per region when the incident opened. + cause jsonb NOT NULL DEFAULT '{}', + CHECK (resolved_at IS NULL OR resolved_at >= started_at) +); + +-- Guards against duplicate incidents even if two evaluations race. +CREATE UNIQUE INDEX incidents_one_open_idx ON incidents (monitor_id) WHERE resolved_at IS NULL; +CREATE INDEX incidents_org_idx ON incidents (org_id, started_at DESC); + +CREATE TABLE notification_channels ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + type text NOT NULL CHECK (type IN ('webhook', 'email')), + -- Type-specific settings; secrets inside are sealed by the application. + config jsonb NOT NULL, + enabled boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX notification_channels_org_idx ON notification_channels (org_id); + +-- Outbox: a row per channel and incident event, delivered with retries by +-- any API replica. +CREATE TABLE notifications ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + channel_id uuid NOT NULL REFERENCES notification_channels (id) ON DELETE CASCADE, + incident_id uuid NOT NULL REFERENCES incidents (id) ON DELETE CASCADE, + event text NOT NULL CHECK (event IN ('opened', 'resolved')), + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')), + attempts integer NOT NULL DEFAULT 0, + next_attempt_at timestamptz NOT NULL DEFAULT now(), + last_error text, + created_at timestamptz NOT NULL DEFAULT now(), + sent_at timestamptz, + UNIQUE (channel_id, incident_id, event) +); + +CREATE INDEX notifications_due_idx ON notifications (next_attempt_at) WHERE status = 'pending'; + +ALTER TABLE incidents ENABLE ROW LEVEL SECURITY; +ALTER TABLE incidents FORCE ROW LEVEL SECURITY; +CREATE POLICY incidents_tenant ON incidents FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +ALTER TABLE notification_channels ENABLE ROW LEVEL SECURITY; +ALTER TABLE notification_channels FORCE ROW LEVEL SECURITY; +CREATE POLICY notification_channels_tenant ON notification_channels FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +ALTER TABLE notifications ENABLE ROW LEVEL SECURITY; +ALTER TABLE notifications FORCE ROW LEVEL SECURITY; +CREATE POLICY notifications_tenant ON notifications FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- +goose Down +DROP TABLE notifications; +DROP TABLE notification_channels; +DROP TABLE incidents; +ALTER TABLE monitors DROP COLUMN confirmations; diff --git a/internal/notify/notify.go b/internal/notify/notify.go new file mode 100644 index 0000000..5f64ad6 --- /dev/null +++ b/internal/notify/notify.go @@ -0,0 +1,239 @@ +// Package notify delivers incident events to notification channels. +// +// Delivery is at least once: the API keeps an outbox and retries, so +// receivers should deduplicate by incident ID and event. +package notify + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "crypto/tls" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "net" + "net/http" + "net/smtp" + "net/url" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" +) + +// Event kinds. +const ( + Opened = "opened" + Resolved = "resolved" + // Test is sent when a user tries out a channel. + Test = "test" +) + +// Monitor identifies the affected monitor. +type Monitor struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Target string `json:"target"` +} + +// Event is one incident change, also the webhook payload. +type Event struct { + Kind string `json:"event"` + IncidentID uuid.UUID `json:"incident_id"` + StartedAt time.Time `json:"started_at"` + ResolvedAt *time.Time `json:"resolved_at,omitempty"` + Cause map[string]string `json:"cause,omitempty"` + Monitor Monitor `json:"monitor"` +} + +// Webhook signs requests so receivers can verify they came from us: the +// signature is HMAC-SHA256 over "." with the channel secret, +// sent as "sha256=". Receivers should reject old timestamps. +type Webhook struct { + URL string + Secret []byte + AllowPrivate bool +} + +// Headers set on webhook requests. +const ( + SignatureHeader = "X-Uptimesebi-Signature" + TimestampHeader = "X-Uptimesebi-Timestamp" + EventHeader = "X-Uptimesebi-Event" +) + +// Sign returns the signature header value for body at ts. +func Sign(secret, body []byte, ts int64) string { + mac := hmac.New(sha256.New, secret) + _, _ = fmt.Fprintf(mac, "%d.", ts) + _, _ = mac.Write(body) + return "sha256=" + hex.EncodeToString(mac.Sum(nil)) +} + +// Send posts ev as JSON. +func (w Webhook) Send(ctx context.Context, ev Event) error { + body, err := json.Marshal(ev) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.URL, bytes.NewReader(body)) + if err != nil { + return err + } + ts := time.Now().Unix() + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "uptimesebi-webhook") + req.Header.Set(EventHeader, ev.Kind) + req.Header.Set(TimestampHeader, strconv.FormatInt(ts, 10)) + req.Header.Set(SignatureHeader, Sign(w.Secret, body, ts)) + d := netguard.Dialer(w.AllowPrivate, 5*time.Second) + client := &http.Client{ + Transport: &http.Transport{DialContext: d.DialContext, DisableKeepAlives: true}, + // Redirects would bypass the URL the customer configured. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return fmt.Errorf("webhook answered %d", resp.StatusCode) + } + return nil +} + +// SMTP is the outgoing mail server, parsed from a URL like +// smtp://user:pass@host:587?from=alerts@example.com&tls=starttls. +// tls is starttls (default), tls for implicit TLS, or none. +type SMTP struct { + Host string + Port string + Username string + Password string + From string + TLS string +} + +// ParseSMTP parses an SMTP URL. An empty string yields nil: mail is off. +func ParseSMTP(raw string) (*SMTP, error) { + if raw == "" { + return nil, nil + } + u, err := url.Parse(raw) + if err != nil || u.Scheme != "smtp" || u.Hostname() == "" { + return nil, errors.New("notify: UPTIME_SMTP_URL must look like smtp://user:pass@host:587?from=alerts@example.com") + } + s := &SMTP{Host: u.Hostname(), Port: u.Port(), From: u.Query().Get("from"), TLS: u.Query().Get("tls")} + if s.Port == "" { + s.Port = "587" + } + if s.TLS == "" { + s.TLS = "starttls" + } + if u.User != nil { + s.Username = u.User.Username() + s.Password, _ = u.User.Password() + } + if s.From == "" || (s.TLS != "starttls" && s.TLS != "tls" && s.TLS != "none") { + return nil, errors.New("notify: UPTIME_SMTP_URL needs ?from= and tls=starttls|tls|none") + } + return s, nil +} + +// Mail is a plain-text message. +type Mail struct { + To []string + Subject string + Body string +} + +// Send delivers m. +func (s *SMTP) Send(ctx context.Context, m Mail) error { + addr := net.JoinHostPort(s.Host, s.Port) + d := &net.Dialer{Timeout: 10 * time.Second} + var conn net.Conn + var err error + if s.TLS == "tls" { + conn, err = (&tls.Dialer{NetDialer: d, Config: &tls.Config{ServerName: s.Host}}).DialContext(ctx, "tcp", addr) + } else { + conn, err = d.DialContext(ctx, "tcp", addr) + } + if err != nil { + return err + } + if dl, ok := ctx.Deadline(); ok { + _ = conn.SetDeadline(dl) + } else { + _ = conn.SetDeadline(time.Now().Add(30 * time.Second)) + } + c, err := smtp.NewClient(conn, s.Host) + if err != nil { + _ = conn.Close() + return err + } + defer func() { _ = c.Close() }() + if s.TLS == "starttls" { + if err := c.StartTLS(&tls.Config{ServerName: s.Host}); err != nil { + return err + } + } + if s.Username != "" { + if err := c.Auth(smtp.PlainAuth("", s.Username, s.Password, s.Host)); err != nil { + return err + } + } + if err := c.Mail(s.From); err != nil { + return err + } + for _, to := range m.To { + if err := c.Rcpt(to); err != nil { + return err + } + } + w, err := c.Data() + if err != nil { + return err + } + if _, err := w.Write(compose(s.From, m)); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + return c.Quit() +} + +func compose(from string, m Mail) []byte { + var b bytes.Buffer + fmt.Fprintf(&b, "From: %s\r\n", from) + fmt.Fprintf(&b, "To: %s\r\n", strings.Join(m.To, ", ")) + fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(m.Subject)) + fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z)) + fmt.Fprintf(&b, "Message-ID: <%s@uptimesebi>\r\n", uuid.NewString()) + b.WriteString("MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n") + b.WriteString(strings.ReplaceAll(m.Body, "\n", "\r\n")) + return b.Bytes() +} + +// encodeHeader applies RFC 2047 encoding when the subject is not ASCII. +func encodeHeader(s string) string { + for _, r := range s { + if r > 127 { + return mime.QEncoding.Encode("utf-8", s) + } + } + return s +} diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go new file mode 100644 index 0000000..a18f270 --- /dev/null +++ b/internal/notify/notify_test.go @@ -0,0 +1,86 @@ +package notify + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" + "git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest" +) + +func event() Event { + return Event{Kind: Opened, IncidentID: uuid.New(), StartedAt: time.Now(), Monitor: Monitor{ID: uuid.New(), Name: "Shop", Type: "http", Target: "https://shop.test"}} +} + +func TestWebhookSignature(t *testing.T) { + secret := []byte("s3cret") + var got Event + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + ts, _ := strconv.ParseInt(r.Header.Get(TimestampHeader), 10, 64) + if r.Header.Get(SignatureHeader) != Sign(secret, body, ts) || r.Header.Get(EventHeader) != Opened { + w.WriteHeader(http.StatusUnauthorized) + return + } + _ = json.Unmarshal(body, &got) + })) + defer srv.Close() + + ev := event() + if err := (Webhook{URL: srv.URL, Secret: secret, AllowPrivate: true}).Send(context.Background(), ev); err != nil { + t.Fatalf("Send() failed: %v", err) + } + if got.IncidentID != ev.IncidentID || got.Monitor.Name != "Shop" { + t.Errorf("received %+v, want %+v", got, ev) + } + if err := (Webhook{URL: srv.URL, Secret: []byte("wrong"), AllowPrivate: true}).Send(context.Background(), ev); err == nil { + t.Error("Send() with a receiver rejecting the signature succeeded") + } + if err := (Webhook{URL: srv.URL, Secret: secret}).Send(context.Background(), ev); !errors.Is(err, netguard.ErrForbiddenAddress) { + t.Errorf("Send() to loopback without AllowPrivate = %v, want %v", err, netguard.ErrForbiddenAddress) + } +} + +func TestSMTP(t *testing.T) { + srv := notifytest.NewSMTP(t) + s, err := ParseSMTP(srv.URL()) + if err != nil { + t.Fatal(err) + } + err = s.Send(context.Background(), Mail{To: []string{"ops@example.test"}, Subject: "[DOWN] Shöp", Body: "line 1\nline 2"}) + if err != nil { + t.Fatalf("Send() failed: %v", err) + } + msgs := srv.Messages() + if len(msgs) != 1 || msgs[0].To[0] != "ops@example.test" || msgs[0].From != "alerts@uptimesebi.test" { + t.Fatalf("received %+v", msgs) + } + if !strings.Contains(msgs[0].Data, "Subject: =?utf-8?q?[DOWN]_Sh=C3=B6p?=") || !strings.Contains(msgs[0].Data, "line 1\r\nline 2") { + t.Errorf("message data = %q", msgs[0].Data) + } +} + +func TestParseSMTP(t *testing.T) { + if s, err := ParseSMTP(""); s != nil || err != nil { + t.Errorf("ParseSMTP(\"\") = %v, %v; want nil, nil", s, err) + } + for _, bad := range []string{"http://x", "smtp://host", "smtp://host?from=a@b&tls=maybe"} { + if _, err := ParseSMTP(bad); err == nil { + t.Errorf("ParseSMTP(%q) accepted", bad) + } + } + s, err := ParseSMTP("smtp://u:p@mail.test?from=a@b.test") + if err != nil || s.Port != "587" || s.TLS != "starttls" || s.Password != "p" { + t.Errorf("ParseSMTP defaults = %+v, %v", s, err) + } +} diff --git a/internal/notify/notifytest/smtp.go b/internal/notify/notifytest/smtp.go new file mode 100644 index 0000000..c4c5f26 --- /dev/null +++ b/internal/notify/notifytest/smtp.go @@ -0,0 +1,104 @@ +// Package notifytest provides an in-memory SMTP server for tests. +package notifytest + +import ( + "bufio" + "net" + "strings" + "sync" + "testing" +) + +// Message is one received mail. +type Message struct { + From string + To []string + Data string +} + +// SMTP accepts mail without authentication or TLS. +type SMTP struct { + Addr string + + mu sync.Mutex + messages []Message +} + +// NewSMTP starts a server that stops when t ends. +func NewSMTP(t *testing.T) *SMTP { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := &SMTP{Addr: ln.Addr().String()} + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go s.serve(conn) + } + }() + return s +} + +// Messages returns what was received so far. +func (s *SMTP) Messages() []Message { + s.mu.Lock() + defer s.mu.Unlock() + return append([]Message(nil), s.messages...) +} + +// URL returns an UPTIME_SMTP_URL for this server. +func (s *SMTP) URL() string { return "smtp://" + s.Addr + "?from=alerts@uptimesebi.test&tls=none" } + +func (s *SMTP) serve(conn net.Conn) { + defer func() { _ = conn.Close() }() + r := bufio.NewReader(conn) + reply := func(line string) { _, _ = conn.Write([]byte(line + "\r\n")) } + reply("220 test") + var msg Message + for { + line, err := r.ReadString('\n') + if err != nil { + return + } + cmd := strings.ToUpper(strings.TrimSpace(line)) + switch { + case strings.HasPrefix(cmd, "EHLO"), strings.HasPrefix(cmd, "HELO"): + reply("250 test") + case strings.HasPrefix(cmd, "MAIL FROM:"): + msg = Message{From: strings.Trim(strings.TrimSpace(line)[10:], "<>")} + reply("250 ok") + case strings.HasPrefix(cmd, "RCPT TO:"): + msg.To = append(msg.To, strings.Trim(strings.TrimSpace(line)[8:], "<>")) + reply("250 ok") + case cmd == "DATA": + reply("354 go") + var b strings.Builder + for { + l, err := r.ReadString('\n') + if err != nil { + return + } + if l == ".\r\n" { + break + } + b.WriteString(l) + } + msg.Data = b.String() + s.mu.Lock() + s.messages = append(s.messages, msg) + s.mu.Unlock() + reply("250 queued") + case cmd == "QUIT": + reply("221 bye") + return + default: + reply("250 ok") + } + } +} diff --git a/internal/store/check_results.sql.go b/internal/store/check_results.sql.go index ffceffb..d3da23c 100644 --- a/internal/store/check_results.sql.go +++ b/internal/store/check_results.sql.go @@ -70,6 +70,44 @@ func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestR return items, nil } +const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many +SELECT DISTINCT ON (region) region, ok, error +FROM check_results +WHERE org_id = $1 AND monitor_id = $2 AND time > now() - interval '1 day' +ORDER BY region, time DESC +` + +type LatestResultsForMonitorParams struct { + OrgID uuid.UUID + MonitorID uuid.UUID +} + +type LatestResultsForMonitorRow struct { + Region string + Ok bool + Error *string +} + +func (q *Queries) LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error) { + rows, err := q.db.Query(ctx, latestResultsForMonitor, arg.OrgID, arg.MonitorID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []LatestResultsForMonitorRow{} + for rows.Next() { + var i LatestResultsForMonitorRow + if err := rows.Scan(&i.Region, &i.Ok, &i.Error); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const recentResults = `-- name: RecentResults :many SELECT time, region, ok, latency_ms, status_code, error FROM check_results diff --git a/internal/store/incidents.sql.go b/internal/store/incidents.sql.go new file mode 100644 index 0000000..edfbff9 --- /dev/null +++ b/internal/store/incidents.sql.go @@ -0,0 +1,434 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: incidents.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const claimNotifications = `-- name: ClaimNotifications :many +UPDATE notifications SET next_attempt_at = now() + interval '5 minutes' +WHERE id IN ( + SELECT id FROM notifications + WHERE status = 'pending' AND next_attempt_at <= now() + ORDER BY next_attempt_at + LIMIT $1 + FOR UPDATE SKIP LOCKED +) +RETURNING id +` + +// System scope. Leases due rows for five minutes so a crashed sender's rows +// come back; SKIP LOCKED lets every API replica work the outbox. +func (q *Queries) ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) { + rows, err := q.db.Query(ctx, claimNotifications, max) + if err != nil { + return nil, err + } + defer rows.Close() + items := []uuid.UUID{} + for rows.Next() { + var id uuid.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const createChannel = `-- name: CreateChannel :one +INSERT INTO notification_channels (org_id, name, type, config, enabled) +VALUES ($1, $2, $3, $4, $5) +RETURNING id, org_id, name, type, config, enabled, created_at, updated_at +` + +type CreateChannelParams struct { + OrgID uuid.UUID + Name string + Type string + Config []byte + Enabled bool +} + +func (q *Queries) CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error) { + row := q.db.QueryRow(ctx, createChannel, + arg.OrgID, + arg.Name, + arg.Type, + arg.Config, + arg.Enabled, + ) + var i NotificationChannel + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const deleteChannel = `-- name: DeleteChannel :execrows +DELETE FROM notification_channels WHERE id = $1 +` + +func (q *Queries) DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteChannel, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const enqueueNotification = `-- name: EnqueueNotification :exec +INSERT INTO notifications (org_id, channel_id, incident_id, event) +VALUES ($1, $2, $3, $4) +ON CONFLICT DO NOTHING +` + +type EnqueueNotificationParams struct { + OrgID uuid.UUID + ChannelID uuid.UUID + IncidentID uuid.UUID + Event string +} + +func (q *Queries) EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error { + _, err := q.db.Exec(ctx, enqueueNotification, + arg.OrgID, + arg.ChannelID, + arg.IncidentID, + arg.Event, + ) + return err +} + +const getChannel = `-- name: GetChannel :one +SELECT id, org_id, name, type, config, enabled, created_at, updated_at FROM notification_channels WHERE id = $1 +` + +func (q *Queries) GetChannel(ctx context.Context, id uuid.UUID) (NotificationChannel, error) { + row := q.db.QueryRow(ctx, getChannel, id) + var i NotificationChannel + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const listChannels = `-- name: ListChannels :many +SELECT id, org_id, name, type, config, enabled, created_at, updated_at FROM notification_channels ORDER BY name +` + +func (q *Queries) ListChannels(ctx context.Context) ([]NotificationChannel, error) { + rows, err := q.db.Query(ctx, listChannels) + if err != nil { + return nil, err + } + defer rows.Close() + items := []NotificationChannel{} + for rows.Next() { + var i NotificationChannel + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listEnabledChannelIDs = `-- name: ListEnabledChannelIDs :many +SELECT id FROM notification_channels WHERE org_id = $1 AND enabled +` + +func (q *Queries) ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) { + rows, err := q.db.Query(ctx, listEnabledChannelIDs, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []uuid.UUID{} + for rows.Next() { + var id uuid.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + items = append(items, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listIncidents = `-- name: ListIncidents :many +SELECT i.id, i.org_id, i.monitor_id, i.started_at, i.resolved_at, i.cause, m.name AS monitor_name +FROM incidents i +JOIN monitors m ON m.id = i.monitor_id +ORDER BY i.started_at DESC +LIMIT 200 +` + +type ListIncidentsRow struct { + ID uuid.UUID + OrgID uuid.UUID + MonitorID uuid.UUID + StartedAt time.Time + ResolvedAt *time.Time + Cause []byte + MonitorName string +} + +func (q *Queries) ListIncidents(ctx context.Context) ([]ListIncidentsRow, error) { + rows, err := q.db.Query(ctx, listIncidents) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListIncidentsRow{} + for rows.Next() { + var i ListIncidentsRow + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.MonitorID, + &i.StartedAt, + &i.ResolvedAt, + &i.Cause, + &i.MonitorName, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const markNotificationFailed = `-- name: MarkNotificationFailed :exec +UPDATE notifications SET attempts = attempts + 1, last_error = $1, + status = CASE WHEN attempts + 1 >= $2::int THEN 'failed' ELSE 'pending' END, + next_attempt_at = now() + make_interval(secs => $3::int) +WHERE id = $4 +` + +type MarkNotificationFailedParams struct { + LastError *string + MaxAttempts int32 + RetryInSeconds int32 + ID uuid.UUID +} + +func (q *Queries) MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error { + _, err := q.db.Exec(ctx, markNotificationFailed, + arg.LastError, + arg.MaxAttempts, + arg.RetryInSeconds, + arg.ID, + ) + return err +} + +const markNotificationSent = `-- name: MarkNotificationSent :exec +UPDATE notifications SET status = 'sent', sent_at = now(), attempts = attempts + 1, last_error = NULL +WHERE id = $1 +` + +func (q *Queries) MarkNotificationSent(ctx context.Context, id uuid.UUID) error { + _, err := q.db.Exec(ctx, markNotificationSent, id) + return err +} + +const notificationDetails = `-- name: NotificationDetails :many +SELECT n.id, n.org_id, n.event, n.attempts, + c.type AS channel_type, c.config AS channel_config, c.id AS channel_id, + i.id AS incident_id, i.started_at, i.resolved_at, i.cause, + m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type +FROM notifications n +JOIN notification_channels c ON c.id = n.channel_id +JOIN incidents i ON i.id = n.incident_id +JOIN monitors m ON m.id = i.monitor_id +WHERE n.id = ANY ($1::uuid[]) +` + +type NotificationDetailsRow struct { + ID uuid.UUID + OrgID uuid.UUID + Event string + Attempts int32 + ChannelType string + ChannelConfig []byte + ChannelID uuid.UUID + IncidentID uuid.UUID + StartedAt time.Time + ResolvedAt *time.Time + Cause []byte + MonitorID uuid.UUID + MonitorName string + MonitorTarget string + MonitorType string +} + +// System scope. +func (q *Queries) NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error) { + rows, err := q.db.Query(ctx, notificationDetails, ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []NotificationDetailsRow{} + for rows.Next() { + var i NotificationDetailsRow + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Event, + &i.Attempts, + &i.ChannelType, + &i.ChannelConfig, + &i.ChannelID, + &i.IncidentID, + &i.StartedAt, + &i.ResolvedAt, + &i.Cause, + &i.MonitorID, + &i.MonitorName, + &i.MonitorTarget, + &i.MonitorType, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const openIncident = `-- name: OpenIncident :one +INSERT INTO incidents (org_id, monitor_id, started_at, cause) +VALUES ($1, $2, $3, $4) +ON CONFLICT (monitor_id) WHERE resolved_at IS NULL DO NOTHING +RETURNING id, org_id, monitor_id, started_at, resolved_at, cause +` + +type OpenIncidentParams struct { + OrgID uuid.UUID + MonitorID uuid.UUID + StartedAt time.Time + Cause []byte +} + +func (q *Queries) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) { + row := q.db.QueryRow(ctx, openIncident, + arg.OrgID, + arg.MonitorID, + arg.StartedAt, + arg.Cause, + ) + var i Incident + err := row.Scan( + &i.ID, + &i.OrgID, + &i.MonitorID, + &i.StartedAt, + &i.ResolvedAt, + &i.Cause, + ) + return i, err +} + +const resolveIncident = `-- name: ResolveIncident :one +UPDATE incidents SET resolved_at = $1 +WHERE monitor_id = $2 AND resolved_at IS NULL +RETURNING id, org_id, monitor_id, started_at, resolved_at, cause +` + +type ResolveIncidentParams struct { + ResolvedAt *time.Time + MonitorID uuid.UUID +} + +func (q *Queries) ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error) { + row := q.db.QueryRow(ctx, resolveIncident, arg.ResolvedAt, arg.MonitorID) + var i Incident + err := row.Scan( + &i.ID, + &i.OrgID, + &i.MonitorID, + &i.StartedAt, + &i.ResolvedAt, + &i.Cause, + ) + return i, err +} + +const updateChannel = `-- name: UpdateChannel :one +UPDATE notification_channels SET name = $2, config = $3, enabled = $4, updated_at = now() +WHERE id = $1 +RETURNING id, org_id, name, type, config, enabled, created_at, updated_at +` + +type UpdateChannelParams struct { + ID uuid.UUID + Name string + Config []byte + Enabled bool +} + +func (q *Queries) UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) { + row := q.db.QueryRow(ctx, updateChannel, + arg.ID, + arg.Name, + arg.Config, + arg.Enabled, + ) + var i NotificationChannel + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/store/models.go b/internal/store/models.go index 23c7587..61049c5 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -70,6 +70,15 @@ type CheckResults1h struct { MaxLatencyMs interface{} } +type Incident struct { + ID uuid.UUID + OrgID uuid.UUID + MonitorID uuid.UUID + StartedAt time.Time + ResolvedAt *time.Time + Cause []byte +} + type Invitation struct { ID uuid.UUID OrgID uuid.UUID @@ -101,6 +110,7 @@ type Monitor struct { Enabled bool CreatedAt time.Time UpdatedAt time.Time + Confirmations int32 } type MonitorRegion struct { @@ -109,6 +119,31 @@ type MonitorRegion struct { Region string } +type Notification struct { + ID uuid.UUID + OrgID uuid.UUID + ChannelID uuid.UUID + IncidentID uuid.UUID + Event string + Status string + Attempts int32 + NextAttemptAt time.Time + LastError *string + CreatedAt time.Time + SentAt *time.Time +} + +type NotificationChannel struct { + ID uuid.UUID + OrgID uuid.UUID + Name string + Type string + Config []byte + Enabled bool + CreatedAt time.Time + UpdatedAt time.Time +} + type Org struct { ID uuid.UUID Slug string diff --git a/internal/store/monitors.sql.go b/internal/store/monitors.sql.go index 6161932..f41a228 100644 --- a/internal/store/monitors.sql.go +++ b/internal/store/monitors.sql.go @@ -56,9 +56,9 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow } const createMonitor = `-- name: CreateMonitor :one -INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8) -RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations ` type CreateMonitorParams struct { @@ -70,6 +70,7 @@ type CreateMonitorParams struct { TimeoutMs int32 Config []byte Enabled bool + Confirmations int32 } func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) { @@ -82,6 +83,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M arg.TimeoutMs, arg.Config, arg.Enabled, + arg.Confirmations, ) var i Monitor err := row.Scan( @@ -96,6 +98,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.Confirmations, ) return i, err } @@ -122,7 +125,7 @@ func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) } const getMonitor = `-- name: GetMonitor :one -SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors WHERE id = $1 +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations FROM monitors WHERE id = $1 ` func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) { @@ -140,6 +143,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.Confirmations, ) return i, err } @@ -181,7 +185,7 @@ func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEna } const listMonitors = `-- name: ListMonitors :many -SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors ORDER BY name +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations FROM monitors ORDER BY name ` func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { @@ -205,6 +209,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.Confirmations, ); err != nil { return nil, err } @@ -241,7 +246,7 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]st } const monitorsForJobs = `-- name: MonitorsForJobs :many -SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at FROM monitors m +SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations FROM monitors m JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1 WHERE m.id = ANY ($2::uuid[]) AND m.enabled ` @@ -274,6 +279,60 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.Confirmations, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const monitorsForResults = `-- name: MonitorsForResults :many +SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations, + (SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions +FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1 +WHERE m.id = ANY ($2::uuid[]) AND m.enabled +` + +type MonitorsForResultsParams struct { + Region string + Ids []uuid.UUID +} + +type MonitorsForResultsRow struct { + ID uuid.UUID + OrgID uuid.UUID + Name string + Target string + IntervalSeconds int32 + Confirmations int32 + Regions []string +} + +// System scope: monitors a checker of region may report, with every region +// they are assigned to, for evaluation. +func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResultsParams) ([]MonitorsForResultsRow, error) { + rows, err := q.db.Query(ctx, monitorsForResults, arg.Region, arg.Ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []MonitorsForResultsRow{} + for rows.Next() { + var i MonitorsForResultsRow + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Target, + &i.IntervalSeconds, + &i.Confirmations, + &i.Regions, ); err != nil { return nil, err } @@ -287,9 +346,9 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams const updateMonitor = `-- name: UpdateMonitor :one UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, - timeout_ms = $6, config = $7, enabled = $8, updated_at = now() + timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, updated_at = now() WHERE id = $1 -RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations ` type UpdateMonitorParams struct { @@ -301,6 +360,7 @@ type UpdateMonitorParams struct { TimeoutMs int32 Config []byte Enabled bool + Confirmations int32 } func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) { @@ -313,6 +373,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M arg.TimeoutMs, arg.Config, arg.Enabled, + arg.Confirmations, ) var i Monitor err := row.Scan( @@ -327,6 +388,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M &i.Enabled, &i.CreatedAt, &i.UpdatedAt, + &i.Confirmations, ) return i, err } diff --git a/internal/store/querier.go b/internal/store/querier.go index e885093..d8570f9 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -16,6 +16,9 @@ type Querier interface { AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AnyUserExists(ctx context.Context) (bool, error) + // System scope. Leases due rows for five minutes so a crashed sender's rows + // come back; SKIP LOCKED lets every API replica work the outbox. + ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) // Shortens tokens that would outlive a newly set maximum lifetime. ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error) CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error) @@ -23,6 +26,7 @@ type Querier interface { CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error) + CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) @@ -33,6 +37,7 @@ type Querier interface { DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error) DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error) + DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error) DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error) DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error @@ -43,10 +48,12 @@ type Querier interface { DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) DisableTOTP(ctx context.Context, id uuid.UUID) error EnableTOTP(ctx context.Context, arg EnableTOTPParams) error + EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error) GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error) GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error) + GetChannel(ctx context.Context, id uuid.UUID) (NotificationChannel, error) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error) GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error) @@ -66,13 +73,17 @@ type Querier interface { IsMember(ctx context.Context, arg IsMemberParams) (bool, error) // Newest result per monitor and region in the org. LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) + LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error) ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error) ListAgents(ctx context.Context) ([]Agent, error) ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) + ListChannels(ctx context.Context) ([]NotificationChannel, error) + ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) // System scope: every enabled monitor with its regions, for reconciling the // schedule. ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) + ListIncidents(ctx context.Context) ([]ListIncidentsRow, error) ListMonitors(ctx context.Context) ([]Monitor, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgs(ctx context.Context) ([]Org, error) @@ -83,20 +94,30 @@ type Querier interface { ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) + MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error + MarkNotificationSent(ctx context.Context, id uuid.UUID) error // Every role a member holds, with the scope it applies to. MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) // System scope: monitors to hand to a checker of region, skipping ones that // were disabled, deleted or moved out of the region since dispatch. MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) + // System scope: monitors a checker of region may report, with every region + // they are assigned to, for evaluation. + MonitorsForResults(ctx context.Context, arg MonitorsForResultsParams) ([]MonitorsForResultsRow, error) + // System scope. + NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error) + OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) + ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error TouchAPIToken(ctx context.Context, id uuid.UUID) error TouchAgent(ctx context.Context, arg TouchAgentParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error + UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) diff --git a/internal/store/queries/check_results.sql b/internal/store/queries/check_results.sql index 2c6c8da..261d5f9 100644 --- a/internal/store/queries/check_results.sql +++ b/internal/store/queries/check_results.sql @@ -26,3 +26,9 @@ SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_coun FROM check_results_1h WHERE org_id = $1 AND bucket >= $2 GROUP BY monitor_id; + +-- name: LatestResultsForMonitor :many +SELECT DISTINCT ON (region) region, ok, error +FROM check_results +WHERE org_id = $1 AND monitor_id = $2 AND time > now() - interval '1 day' +ORDER BY region, time DESC; diff --git a/internal/store/queries/incidents.sql b/internal/store/queries/incidents.sql new file mode 100644 index 0000000..b66b9ab --- /dev/null +++ b/internal/store/queries/incidents.sql @@ -0,0 +1,79 @@ +-- name: OpenIncident :one +INSERT INTO incidents (org_id, monitor_id, started_at, cause) +VALUES ($1, $2, $3, $4) +ON CONFLICT (monitor_id) WHERE resolved_at IS NULL DO NOTHING +RETURNING *; + +-- name: ResolveIncident :one +UPDATE incidents SET resolved_at = sqlc.arg(resolved_at) +WHERE monitor_id = sqlc.arg(monitor_id) AND resolved_at IS NULL +RETURNING *; + +-- name: ListIncidents :many +SELECT i.*, m.name AS monitor_name +FROM incidents i +JOIN monitors m ON m.id = i.monitor_id +ORDER BY i.started_at DESC +LIMIT 200; + +-- name: ListEnabledChannelIDs :many +SELECT id FROM notification_channels WHERE org_id = $1 AND enabled; + +-- name: EnqueueNotification :exec +INSERT INTO notifications (org_id, channel_id, incident_id, event) +VALUES ($1, $2, $3, $4) +ON CONFLICT DO NOTHING; + +-- name: ClaimNotifications :many +-- System scope. Leases due rows for five minutes so a crashed sender's rows +-- come back; SKIP LOCKED lets every API replica work the outbox. +UPDATE notifications SET next_attempt_at = now() + interval '5 minutes' +WHERE id IN ( + SELECT id FROM notifications + WHERE status = 'pending' AND next_attempt_at <= now() + ORDER BY next_attempt_at + LIMIT sqlc.arg(max) + FOR UPDATE SKIP LOCKED +) +RETURNING id; + +-- name: NotificationDetails :many +-- System scope. +SELECT n.id, n.org_id, n.event, n.attempts, + c.type AS channel_type, c.config AS channel_config, c.id AS channel_id, + i.id AS incident_id, i.started_at, i.resolved_at, i.cause, + m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type +FROM notifications n +JOIN notification_channels c ON c.id = n.channel_id +JOIN incidents i ON i.id = n.incident_id +JOIN monitors m ON m.id = i.monitor_id +WHERE n.id = ANY (sqlc.arg(ids)::uuid[]); + +-- name: MarkNotificationSent :exec +UPDATE notifications SET status = 'sent', sent_at = now(), attempts = attempts + 1, last_error = NULL +WHERE id = $1; + +-- name: MarkNotificationFailed :exec +UPDATE notifications SET attempts = attempts + 1, last_error = sqlc.arg(last_error), + status = CASE WHEN attempts + 1 >= sqlc.arg(max_attempts)::int THEN 'failed' ELSE 'pending' END, + next_attempt_at = now() + make_interval(secs => sqlc.arg(retry_in_seconds)::int) +WHERE id = sqlc.arg(id); + +-- name: CreateChannel :one +INSERT INTO notification_channels (org_id, name, type, config, enabled) +VALUES ($1, $2, $3, $4, $5) +RETURNING *; + +-- name: UpdateChannel :one +UPDATE notification_channels SET name = $2, config = $3, enabled = $4, updated_at = now() +WHERE id = $1 +RETURNING *; + +-- name: GetChannel :one +SELECT * FROM notification_channels WHERE id = $1; + +-- name: ListChannels :many +SELECT * FROM notification_channels ORDER BY name; + +-- name: DeleteChannel :execrows +DELETE FROM notification_channels WHERE id = $1; diff --git a/internal/store/queries/monitors.sql b/internal/store/queries/monitors.sql index 54d5fc5..c14bbab 100644 --- a/internal/store/queries/monitors.sql +++ b/internal/store/queries/monitors.sql @@ -1,11 +1,11 @@ -- name: CreateMonitor :one -INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *; -- name: UpdateMonitor :one UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, - timeout_ms = $6, config = $7, enabled = $8, updated_at = now() + timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, updated_at = now() WHERE id = $1 RETURNING *; @@ -45,3 +45,12 @@ GROUP BY m.id, m.interval_seconds; SELECT m.* FROM monitors m JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region) WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled; + +-- name: MonitorsForResults :many +-- System scope: monitors a checker of region may report, with every region +-- they are assigned to, for evaluation. +SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations, + (SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions +FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region) +WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled;