alert

package
v0.0.0-...-0301fe8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const EmailUnavailableMessage = "" /* 144-byte string literal not displayed */

EmailUnavailableMessage explains why email cannot be chosen or delivered.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when a requested record does not exist.

Functions

func CheckHeaders

func CheckHeaders(headers string) error

CheckHeaders reports whether headers is empty or a JSON object of valid HTTP header names and string values, naming the first header that is not. A value is never echoed, since it may hold a credential.

func EvalExpression

func EvalExpression(prog Program, env Env) (bool, error)

EvalExpression runs a compiled program with the given environment.

func FireWebhook

func FireWebhook(rule Rule, ctx ActionContext) (string, error)

FireWebhook sends the webhook for the given rule. Returns "skipped" if no URL is configured, "success" on 2xx, or "failed" after exhausting retries.

Custom headers are parsed from rule.WebhookHeaders as a JSON object (e.g. {"Authorization":"Bearer token"}).

Retries: up to 3 attempts with linear backoff (0s, 2s, 4s) for 5xx responses. 4xx responses are not retried.

func RenderTemplate

func RenderTemplate(tmplStr string, ctx ActionContext) (string, error)

RenderTemplate renders tmplStr against ctx using Go text/template. If tmplStr is empty, the defaultTemplate is used.

func SafeEval

func SafeEval(prog Program, env Env) (result bool, err error)

SafeEval wraps EvalExpression with panic recovery, logging unexpected panics via slog. Returns false on panic.

Types

type ActionContext

type ActionContext struct {
	Rule  Rule      `json:"rule"`
	Alert Alert     `json:"alert"`
	Env   Env       `json:"env"`
	Event string    `json:"event"`
	Time  time.Time `json:"time"`
}

ActionContext is passed to webhook templates and delivery logic.

type Alert

type Alert struct {
	ID                 string  `json:"id"`
	RuleID             string  `json:"rule_id"`
	Service            string  `json:"service"`
	State              string  `json:"state"`
	Value              float64 `json:"value"` // The first variable the rule reads, at the last evaluation
	FiredAt            string  `json:"fired_at,omitempty"`
	ResolvedAt         string  `json:"resolved_at,omitempty"`
	RepeatedAt         string  `json:"repeated_at,omitempty"`
	LastEvaluatedAt    string  `json:"last_evaluated_at,omitempty"`
	LastDeliveryStatus string  `json:"last_delivery_status,omitempty"`
	LastDeliveryAt     string  `json:"last_delivery_at,omitempty"`
	CreatedAt          string  `json:"created_at"`
}

Alert represents the current state of an alert instance for a (rule, service) pair.

type EmailConfig

type EmailConfig struct {
	Send        func(context.Context, auth.AlertMail) error
	Defaults    []string // Addresses for rules with no destination of their own.
	HourlyLimit int      // Emails per address per rolling hour, across all rules.
}

EmailConfig enables alert email on an Engine.

type EmailOptions

type EmailOptions struct {
	Available          bool   `json:"available"`
	Message            string `json:"message,omitempty"`
	DefaultDestination bool   `json:"default_destination"`
	MaxRecipients      int    `json:"max_recipients"`
	HourlyLimit        int    `json:"hourly_limit,omitempty"`
}

EmailOptions describes alert email on this instance to API clients.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine drives the alert evaluation loop.

func NewEngine

func NewEngine(
	store *Store,
	duck *engine.Duck,
	detector *intelligence.Detector,
	interval time.Duration,
	histDays int,
) *Engine

NewEngine creates an Engine ready to Run.

func (*Engine) DisableRule

func (e *Engine) DisableRule(rule Rule)

DisableRule stops evaluating a rule. Its firing alerts resolve, staying in history and notifying as a cleared condition would; pending ones never fired and are dropped. Holding the lock waits out a tick's transitions for the rule, and the tick skips it from then on.

func (*Engine) EmailOptions

func (e *Engine) EmailOptions() EmailOptions

EmailOptions reports whether email can be chosen. A nil engine means alerts are disabled.

func (*Engine) EnableEmail

func (e *Engine) EnableEmail(cfg EmailConfig)

EnableEmail turns on alert email. Call it before Run.

func (*Engine) RecompileRule

func (e *Engine) RecompileRule(ruleID, expression string) error

RecompileRule compiles an expression and replaces the rule used on future evaluation ticks.

func (*Engine) RemoveRule

func (e *Engine) RemoveRule(ruleID string)

RemoveRule removes a compiled program so it is not evaluated on future ticks.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context)

Run starts the evaluation ticker. It blocks until ctx is cancelled.

func (*Engine) Test

func (e *Engine) Test(ctx context.Context, rule Rule) ([]TestResult, error)

Test evaluates a rule against current data without changing any alert.

func (*Engine) WithEmailState

func (e *Engine) WithEmailState(rule Rule) Rule

WithEmailState adjusts a rule's reported email state for what this instance can do now: saved recipients without SMTP are a standing failure, and a rule with no email destination has no email state.

type Env

type Env struct {
	// Mean of minute-rollup span error proportions over the evaluation window,
	// from 0 to 1; not a request-weighted whole-window error rate.
	ErrorRate float64 `expr:"error_rate" json:"error_rate"`
	// Mean of approximate minute-rollup median span latencies in milliseconds.
	P50 float64 `expr:"p50" json:"p50"`
	// Mean of approximate minute-rollup 95th-percentile span latencies in
	// milliseconds; not the whole-window p95. Latency prefers served work,
	// falling back to outbound spans when no served work is available.
	P95 float64 `expr:"p95" json:"p95"`
	// Total span count over the current rollup window, not requests per second.
	// Pair it with an error threshold to avoid firing on very little traffic.
	Throughput float64 `expr:"throughput" json:"throughput"`
	// Log records recorded for the service over the window.
	LogCount float64 `expr:"log_count" json:"log_count"`
	// How far the service's current behaviour sits from its own recent baseline,
	// in standard deviations. Use it to catch a service that has changed without
	// committing to an absolute threshold that fits every service.
	ZScore float64 `expr:"z_score" json:"z_score"`
	// The detector's instance-wide composite 0-100 health score. Every service
	// receives the same score; it is not a per-service value.
	HealthScore float64 `expr:"health_score" json:"health_score"`
	// Relative change in error rate against the preceding rollup window, as a
	// percentage; zero when the baseline is missing or zero.
	ErrorRateDelta float64 `expr:"error_rate_delta" json:"error_rate_delta"`
	// Relative change in p95 latency against the preceding rollup window, as a
	// percentage; zero when the baseline is missing or zero.
	P95Delta float64 `expr:"p95_delta" json:"p95_delta"`
	// Relative change in span count against the preceding rollup window, as a
	// percentage. Negative when traffic drops; zero when the baseline is missing
	// or zero.
	ThroughputDelta float64 `expr:"throughput_delta" json:"throughput_delta"`
	// The service name being evaluated, as a string. Compare it when one rule
	// needs to behave differently for one service.
	Service string `expr:"service" json:"service"`
}

Env holds the metric values available to alert expressions.

The `expr` tag is the name a rule author writes, and each field's doc comment is published as that variable's description by cmd/pitot-docgen. Adding a field here adds a row to the reference; describe it in a sentence a rule author would find useful, not in terms of how it is computed.

type Program

type Program = cel.Program

Program is a compiled, ready-to-evaluate alert expression. Aliasing cel.Program keeps the expression engine an implementation detail of this file — the rest of the package (and callers) refer only to alert.Program.

func CompileExpression

func CompileExpression(expression string) (Program, error)

CompileExpression compiles a CEL expression against the alert environment and validates that it type-checks to a boolean.

type Rule

type Rule struct {
	ID              string `json:"id"`
	Name            string `json:"name"`
	Description     string `json:"description,omitempty"`
	Enabled         bool   `json:"enabled"`
	Service         string `json:"service,omitempty"`
	Namespace       string `json:"namespace,omitempty"`
	Expression      string `json:"expression"`
	ForSeconds      int    `json:"for_seconds"`
	CooldownS       int    `json:"cooldown_s"`
	RepeatIntervalS int    `json:"repeat_interval_s"`
	WebhookURL      string `json:"webhook_url,omitempty"`
	WebhookHeaders  string `json:"webhook_headers,omitempty"`
	WebhookTemplate string `json:"webhook_template,omitempty"`
	NotifyOnResolve bool   `json:"notify_on_resolve"`
	// EmailRecipients are this rule's own addresses. Empty means none: the
	// default destination then applies if the rule has no webhook either.
	EmailRecipients []string `json:"email_recipients,omitempty"`
	// EmailStatus reports the rule's latest email notification: sent, retrying,
	// failed, suppressed, or unavailable. The server owns these three fields.
	EmailStatus       string `json:"email_status,omitempty"`
	EmailStatusDetail string `json:"email_status_detail,omitempty"`
	EmailStatusAt     string `json:"email_status_at,omitempty"`
	CreatedAt         string `json:"created_at"`
	UpdatedAt         string `json:"updated_at"`
}

Rule defines an alert condition evaluated against the observability data.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store provides CRUD operations for alert rules and alert instances.

func NewStore

func NewStore(db *sql.DB) *Store

NewStore creates a Store backed by the given database connection.

func (*Store) AlertSummary

func (s *Store) AlertSummary() (Summary, error)

AlertSummary returns counts of alerts grouped by state.

func (*Store) CreateRule

func (s *Store) CreateRule(r Rule) (Rule, error)

CreateRule inserts a new alert rule and returns the persisted record.

func (*Store) DeleteAlert

func (s *Store) DeleteAlert(id string) error

DeleteAlert deletes an alert by ID.

func (*Store) DeleteRule

func (s *Store) DeleteRule(id string) error

DeleteRule deletes a rule by ID (cascades to alerts).

func (*Store) GetAlert

func (s *Store) GetAlert(ruleID, service string) (Alert, error)

GetAlert retrieves the latest episode of (rule_id, service): the open one when there is one, else the most recent resolved one.

func (*Store) GetRule

func (s *Store) GetRule(id string) (Rule, error)

GetRule retrieves a rule by ID.

func (*Store) ListAlerts

func (s *Store) ListAlerts(state, service, ruleID string) ([]Alert, error)

ListAlerts returns alerts with optional filters for state, service, and ruleID. For a single filter, a dedicated generated query is used. For combined filters or no filter, all alerts are fetched and filtered in Go (dataset is small).

func (*Store) ListEnabledRules

func (s *Store) ListEnabledRules() ([]Rule, error)

ListEnabledRules returns only enabled rules.

func (*Store) ListRules

func (s *Store) ListRules() ([]Rule, error)

ListRules returns all rules ordered by creation time descending.

func (*Store) PruneResolved

func (s *Store) PruneResolved(days int) (int64, error)

PruneResolved deletes resolved alerts older than days days. Returns the number of rows deleted.

func (*Store) ReplaceRule

func (s *Store) ReplaceRule(r Rule) (Rule, error)

ReplaceRule replaces a rule by ID and returns the persisted record.

func (*Store) UpdateDeliveryStatus

func (s *Store) UpdateDeliveryStatus(id, status, deliveredAt string) error

UpdateDeliveryStatus updates only the delivery status columns of one alert episode. This is used by fireWebhookAsync to avoid overwriting alert state that may have changed between when the goroutine was launched and when the webhook completed.

func (*Store) UpsertAlert

func (s *Store) UpsertAlert(a Alert) (Alert, error)

UpsertAlert inserts an alert episode, or updates the one with a.ID. Each episode is its own row; at most one per (rule_id, service) is open.

func (*Store) UpsertAlertWithEmail

func (s *Store) UpsertAlertWithEmail(a Alert, recipients []string, content emailContent, now time.Time) (Alert, error)

UpsertAlertWithEmail saves an alert and queues one delivery per recipient, atomically.

type Summary

type Summary struct {
	Firing   int `json:"firing"`
	Pending  int `json:"pending"`
	Resolved int `json:"resolved"`
}

Summary aggregates alert state counts.

type TestResult

type TestResult struct {
	Service   string `json:"service"`
	Triggered bool   `json:"triggered"`
	Error     string `json:"error,omitempty"`
	// NoData is set when the service has no recent telemetry, which usually
	// means its name is misspelled.
	NoData bool `json:"no_data,omitempty"`
	Env    Env  `json:"env"`
}

TestResult is one service's dry run of a rule.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL