Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/pitot-docgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ func renderAlertEnv(vars []field) []byte {
b.WriteString("{/* Generated by cmd/pitot-docgen from internal/alert. Edit the generator, not this page. */}\n\n")

b.WriteString("An alert rule's `expression` is [CEL](https://cel.dev) evaluated\n")
b.WriteString("against one service's rollup for the current window. It can read the following variables.\n\n")
b.WriteString("against the current rollup for one namespace and service. It can read the following variables.\n\n")
b.WriteString("Nonempty expressions supplied when creating or replacing rules through the\n")
b.WriteString("API are type-checked against these declared variables. Unknown variables,\n")
b.WriteString("type mistakes, and non-boolean results are rejected before the rule is saved.\n\n")
Expand Down
57 changes: 33 additions & 24 deletions internal/alert/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,14 @@ func (e *Engine) saveAlert(rule Rule, a Alert, event string) (Alert, error) {
return e.store.UpsertAlert(a)
}
now := e.clock()
return e.store.UpsertAlertWithEmail(a, recipients, emailContent{
Rule: rule.Name,
Description: rule.Description,
Service: a.Service,
Event: event,
Value: a.Value,
Time: now,
}, now)
return e.store.upsertAlertWithEmail(a, recipients, newEmailContent(rule, a, event, now), now)
}

func newEmailContent(rule Rule, a Alert, event string, now time.Time) emailContent {
return emailContent{
Rule: rule.Name, Description: rule.Description, Namespace: a.Namespace, Service: a.Service,
Event: event, Value: a.Value, Time: now,
}
}

func (e *Engine) clock() time.Time {
Expand All @@ -145,24 +145,17 @@ func (e *Engine) clock() time.Time {
type emailContent struct {
Rule string `json:"rule"`
Description string `json:"description,omitempty"`
Namespace string `json:"namespace,omitempty"`
Service string `json:"service"`
Event string `json:"event"`
Value float64 `json:"value"`
Time time.Time `json:"time"`
}

// UpsertAlertWithEmail saves an alert and queues one delivery per recipient,
// upsertAlertWithEmail saves an alert and queues one delivery per recipient,
// atomically.
func (s *Store) UpsertAlertWithEmail(a Alert, recipients []string, content emailContent, now time.Time) (Alert, error) {
func (s *Store) upsertAlertWithEmail(a Alert, recipients []string, content emailContent, now time.Time) (Alert, error) {
ctx := context.Background()
payload, err := json.Marshal(content)
if err != nil {
return Alert{}, fmt.Errorf("store: encode email: %w", err)
}
notificationID, err := newID()
if err != nil {
return Alert{}, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Alert{}, fmt.Errorf("store: begin: %w", err)
Expand All @@ -173,11 +166,29 @@ func (s *Store) UpsertAlertWithEmail(a Alert, recipients []string, content email
if err != nil {
return Alert{}, err
}
if err := queueAlertEmail(ctx, q, saved, recipients, content, now); err != nil {
return Alert{}, err
}
if err := tx.Commit(); err != nil {
return Alert{}, fmt.Errorf("store: commit: %w", err)
}
return saved, nil
}

func queueAlertEmail(ctx context.Context, q *generated.Queries, saved Alert, recipients []string, content emailContent, now time.Time) error {
payload, err := json.Marshal(content)
if err != nil {
return fmt.Errorf("store: encode email: %w", err)
}
notificationID, err := newID()
if err != nil {
return err
}
at := formatStoredTime(now)
for _, recipient := range recipients {
id, err := newID()
if err != nil {
return Alert{}, err
return err
}
if err := q.InsertAlertEmailDelivery(ctx, generated.InsertAlertEmailDeliveryParams{
ID: id,
Expand All @@ -189,13 +200,10 @@ func (s *Store) UpsertAlertWithEmail(a Alert, recipients []string, content email
NextAttemptAt: at,
CreatedAt: at,
}); err != nil {
return Alert{}, fmt.Errorf("store: queue email: %w", err)
return fmt.Errorf("store: queue email: %w", err)
}
}
if err := tx.Commit(); err != nil {
return Alert{}, fmt.Errorf("store: commit: %w", err)
}
return saved, nil
return nil
}

func encodeRecipients(recipients []string) sql.NullString {
Expand Down Expand Up @@ -418,6 +426,7 @@ func (e *Engine) deliverEmail(ctx context.Context, row generated.AlertEmailDeliv
To: row.Recipient,
Rule: content.Rule,
Description: content.Description,
Namespace: content.Namespace,
Service: content.Service,
Event: content.Event,
Value: content.Value,
Expand Down
37 changes: 20 additions & 17 deletions internal/alert/email_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (h *mailHarness) rule(t *testing.T, name string, recipients ...string) Rule
}

func (h *mailHarness) fire(rule Rule) {
h.engine.transition(rule, "api", true, Env{Service: "api", ErrorRate: 0.5}, h.now)
h.engine.transition(rule, true, Env{Service: "api", ErrorRate: 0.5}, h.now)
}

func (h *mailHarness) drain() { h.engine.drainEmail(context.Background()) }
Expand All @@ -93,19 +93,19 @@ func (h *mailHarness) ruleStatus(t *testing.T, id string) Rule {
func TestEmailReachesEveryRecipientAndReportsSent(t *testing.T) {
h := newMailHarness(t, 30)
rule := h.rule(t, "errors", "a@example.com", "b@example.com")
h.fire(rule)
h.engine.transition(rule, true, Env{Namespace: "acme", Service: "api", ErrorRate: .5}, h.now)
h.drain()
if len(h.box.to("a@example.com")) != 1 || len(h.box.to("b@example.com")) != 1 {
t.Fatalf("mails = %+v", h.box.mails)
}
got := h.box.to("a@example.com")[0]
if got.Rule != "errors" || got.Service != "api" || got.Event != "firing" || got.Value != 0.5 {
if got.Namespace != "acme" || got.Rule != "errors" || got.Service != "api" || got.Event != "firing" || got.Value != 0.5 {
t.Fatalf("mail = %+v", got)
}
if status := h.ruleStatus(t, rule.ID).EmailStatus; status != "sent" {
t.Fatalf("rule status = %q", status)
}
alert, err := h.store.GetAlert(rule.ID, "api")
alert, err := h.store.GetAlert(rule.ID, "acme", "api")
if err != nil || alert.LastDeliveryStatus != "success" {
t.Fatalf("alert = %+v, %v", alert, err)
}
Expand Down Expand Up @@ -141,7 +141,7 @@ func TestOlderRuleWithoutEmailColumnsUsesDefaultDestination(t *testing.T) {
if rule.EmailRecipients != nil || rule.EmailStatus != "" {
t.Fatalf("older rule = %+v", rule)
}
h.engine.transition(rule, "api", true, Env{Service: "api"}, h.now)
h.engine.transition(rule, true, Env{Service: "api"}, h.now)
h.drain()
if got := h.box.to("oncall@example.com"); len(got) != 1 {
t.Fatalf("older rule mails = %+v", got)
Expand Down Expand Up @@ -202,7 +202,7 @@ func TestExhaustedRetriesShowFailureOnRule(t *testing.T) {
if stored.EmailStatus != "failed" || stored.EmailStatusDetail == "" || strings.Contains(stored.EmailStatusDetail, "connection refused") {
t.Fatalf("rule = %+v", stored)
}
alert, err := h.store.GetAlert(rule.ID, "api")
alert, err := h.store.GetAlert(rule.ID, "", "api")
if err != nil || alert.LastDeliveryStatus != "failed" {
t.Fatalf("alert = %+v, %v", alert, err)
}
Expand Down Expand Up @@ -286,11 +286,11 @@ func TestLimitSurvivesRestart(t *testing.T) {
h.fire(h.rule(t, "one", "a@example.com"))
h.drain()

restarted := &Engine{store: h.store, programs: map[string]Program{}, stopped: map[string]bool{}, now: h.engine.now}
restarted := &Engine{store: h.store, programs: map[string]Program{}, now: h.engine.now}
box := &outbox{}
restarted.EnableEmail(EmailConfig{Send: box.send, HourlyLimit: 1})
rule := h.rule(t, "two", "a@example.com")
restarted.transition(rule, "api", true, Env{Service: "api"}, h.now)
restarted.transition(rule, true, Env{Service: "api"}, h.now)
restarted.drainEmail(context.Background())
if len(box.mails) != 0 {
t.Fatalf("limit reset by restart: %+v", box.mails)
Expand Down Expand Up @@ -321,7 +321,7 @@ func TestDeletingAnAlertDoesNotResetTheHourlyLimit(t *testing.T) {
rule := h.rule(t, "errors", "a@example.com")
h.fire(rule)
h.drain()
alert, err := h.store.GetAlert(rule.ID, "api")
alert, err := h.store.GetAlert(rule.ID, "", "api")
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -571,7 +571,7 @@ func TestEmailWorkerKeepsRunningAfterAPanic(t *testing.T) {
}
return nil
}
h.engine.transition(rule, "api", true, Env{Service: "api"}, time.Now())
h.engine.transition(rule, true, Env{Service: "api"}, time.Now())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan struct{})
Expand Down Expand Up @@ -694,7 +694,7 @@ func TestRestartResumesQueuedMailAndDoesNotResendFinished(t *testing.T) {
queued := h.rule(t, "queued", "wait@example.com")
h.fire(queued)

restarted := &Engine{store: h.store, programs: map[string]Program{}, stopped: map[string]bool{}, now: h.engine.now}
restarted := &Engine{store: h.store, programs: map[string]Program{}, now: h.engine.now}
box := &outbox{}
restarted.EnableEmail(EmailConfig{Send: box.send, HourlyLimit: 30})
restarted.recoverEmail(context.Background())
Expand Down Expand Up @@ -753,7 +753,7 @@ func TestEmailQueuedAtomicallyWithTransition(t *testing.T) {
t.Fatal(err)
}
h.fire(rule)
if _, err := h.store.GetAlert(rule.ID, "api"); !errors.Is(err, ErrNotFound) {
if _, err := h.store.GetAlert(rule.ID, "", "api"); !errors.Is(err, ErrNotFound) {
t.Fatalf("alert saved without its email: %v", err)
}
}
Expand Down Expand Up @@ -782,7 +782,7 @@ func TestRepeatsFollowTheRulesNotificationBehaviour(t *testing.T) {

// notify_on_resolve is off, so the resolve is silent.
h.now = h.now.Add(time.Minute)
h.engine.transition(rule, "api", false, Env{Service: "api"}, h.now)
h.engine.transition(rule, false, Env{Service: "api"}, h.now)
h.drain()
if got := h.box.to("a@example.com"); len(got) != 2 {
t.Fatalf("resolve mailed with notify_on_resolve off: %+v", got)
Expand All @@ -792,7 +792,7 @@ func TestRepeatsFollowTheRulesNotificationBehaviour(t *testing.T) {
h.now = h.now.Add(time.Minute)
h.fire(rule)
h.now = h.now.Add(time.Minute)
h.engine.transition(rule, "api", false, Env{Service: "api"}, h.now)
h.engine.transition(rule, false, Env{Service: "api"}, h.now)
h.drain()
got = h.box.to("a@example.com")
if len(got) != 4 || got[3].Event != "resolved" {
Expand All @@ -807,7 +807,10 @@ func TestDisablingAFiringRuleMailsItsResolve(t *testing.T) {
t.Fatal(err)
}
h.fire(rule)
h.engine.DisableRule(rule)
rule.Enabled = false
if _, err := h.engine.ReplaceRule(rule); err != nil {
t.Fatal(err)
}
h.drain()
got := h.box.to("a@example.com")
if len(got) != 2 || got[1].Event != "resolved" {
Expand Down Expand Up @@ -835,7 +838,7 @@ func TestWebhookResultStaysOnAlertWhenRuleAlsoEmails(t *testing.T) {

deadline := time.Now().Add(5 * time.Second)
for {
alert, err := h.store.GetAlert(rule.ID, "api")
alert, err := h.store.GetAlert(rule.ID, "", "api")
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -879,7 +882,7 @@ func TestMailQueuedBeforeSMTPWasRemovedIsMarkedFailed(t *testing.T) {
rule := h.rule(t, "errors", "a@example.com")
h.fire(rule)

without := &Engine{store: h.store, programs: map[string]Program{}, stopped: map[string]bool{}}
without := &Engine{store: h.store, programs: map[string]Program{}}
without.failUndeliverableEmail(context.Background())
stored := h.ruleStatus(t, rule.ID)
if stored.EmailStatus != "failed" || !strings.Contains(stored.EmailStatusDetail, "SMTP") {
Expand Down
Loading
Loading