routing

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: AGPL-3.0 Imports: 30 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

Overview

Package routing holds the Routes of C-08 and routes Alerts with them. A Route has a name, Matchers, the urgent mark, a Group key and every policy field, each in its typed column; the Default route exists from the first start, has no Matchers and is always last. Routes are evaluated `ORDER BY is_default, position, id` and the first one whose Matchers all match takes a newly firing Alert (Router). Reordering replaces the positions under the list ETag, organizations.route_order_version, which creating, deleting and reordering bump; deletion is soft. Every change is recorded in the Audit log and announced with the live hint route; the package also exports muster_route_info, serves the two Route profiles, On-call and Informational, from the built-in defaults, previews a Group key over the Stored Snapshots of a period with the Router's evaluation order, and computes the Route suggestions on each read.

Index

Constants

View Source
const (
	// PreviewPeriod is routing.group_key_preview_period, the period a request without one previews (P-12).
	PreviewPeriod = 24 * time.Hour
	// PreviewExamples is routing.group_key_preview_examples: how many of the largest Alert Groups each side shows.
	PreviewExamples = 5
	// PreviewMaxAlerts is routing.group_key_preview_max_alerts: the most Alerts a preview covers, the newest first.
	PreviewMaxAlerts = 10000
)

The values of the Group key preview (C-08.FR-5, defaults.md).

View Source
const (
	ProfileOnCall        = "on_call"
	ProfileInformational = "informational"
)

The ids of the Route profiles (C-08.FR-7).

View Source
const (
	LanguageEnglish = "en"
	LanguageRussian = "ru"
)

The languages of a Route (route.language).

View Source
const (
	ActionCreated   = "route.created"
	ActionUpdated   = "route.updated"
	ActionDeleted   = "route.deleted"
	ActionReordered = "route.reordered"
	ResourceRoute   = "route"
	Hint            = "route"
)

The Audit log actions and resource type, and the live hint, of Routes (C-03.FR-14).

View Source
const (
	CodeInvalidFormat    = "invalid_format"
	CodeTooLong          = "too_long"
	CodeOutOfRange       = "out_of_range"
	CodeUnsupported      = "unsupported"
	CodeDuplicate        = "duplicate"
	CodeUnknownID        = "unknown_id"
	CodeInvalidRegex     = "invalid_regex"
	CodeRouteSetMismatch = "route_set_mismatch"
	CodeOneOfRequired    = "one_of_required"
	CodeRequired         = "required"
)

The codes of FieldError.

View Source
const (
	TemplateRootMessage      = "root_message"
	TemplateLine             = "line"
	TemplateAckTimeoutNotice = "ack_timeout_notice"
)

The kinds of Route templates, as the API and the template error state name them.

View Source
const (
	SuggestionHeartbeatLost  = "heartbeat_lost"
	SuggestionInternalAlerts = "internal_alerts"
)

The ids of the Route suggestions (C-08.FR-11), in the order they are listed.

View Source
const (
	HeartbeatLostRouteName  = "Muster: Heartbeat lost"
	InternalAlertsRouteName = "Muster internal alerts"
)

The names of the Routes the suggestions create.

View Source
const DefaultName = "Default"

DefaultName is the name the Default route is created with.

Variables

View Source
var (
	// ErrNotFound is a Route that does not exist in the Organization or is deleted.
	ErrNotFound = errors.New("no such route")
	// ErrNameTaken is a name another Route that is not deleted has.
	ErrNameTaken = errors.New("another route has this name")
	// ErrVersionMismatch is an If-Match that names another version of the Route, or of the Route list.
	ErrVersionMismatch = errors.New("the route or the route order changed since it was read")
	// ErrDefaultImmutable is a deletion of the Default route, or a reorder that lists it.
	ErrDefaultImmutable = errors.New("the default route cannot be deleted or moved")
)
View Source
var (
	// ErrSuggestionNotFound is an id of no Route suggestion.
	ErrSuggestionNotFound = errors.New("no such route suggestion")
	// ErrSuggestionObsolete is a Route suggestion that no longer applies.
	ErrSuggestionObsolete = errors.New("the route suggestion no longer applies")
)

Functions

func EnsureDefault

func EnsureDefault(ctx context.Context, q Queries, orgID int64, now time.Time) error

EnsureDefault creates the Default route of the Organization once (C-08.FR-3), as a start-up ensure step: "Default", without Matchers, with the values of the On-call profile. It changes nothing when the Default route exists; a Route that is not deleted and already has its name stops the start with ErrNameTaken.

func RestampAlerts

func RestampAlerts(ctx context.Context, tx dbgen.DBTX, orgID int64, alertIDs []int64, routeID int64) error

RestampAlerts records routeID as the Route of the current firing of the Alerts, in the Snapshot's transaction tx: grouping puts Alerts whose Route was deleted while their Snapshot waited for it on the Default route.

Types

type AckTimeout

type AckTimeout struct {
	Enabled              bool  `json:"enabled"`
	FirstIntervalSeconds int64 `json:"first_interval_seconds"`
}

AckTimeout is route.ack_timeout.

type Config

type Config struct {
	OrgID int64
	Store Store
	Audit *audit.Writer
	// Business is the business clock, which dates the rows and the period of a Group key preview; Real measures how
	// long a preview took.
	Business clock.Clock
	Real     clock.Clock
	// Router is the Router of the Organization, whose evaluation order the Group key preview and the suggestions
	// use; a new one when nil.
	Router *Router
	// Snapshots reads the Stored Snapshots for the Group key preview.
	Snapshots Snapshots
	Log       *logging.Logger
}

Config is what a Service needs.

type FieldError

type FieldError struct {
	Pointer string
	Code    string
	Detail  string
	// Line and Column are the 1-based position of a template error, 0 when unknown.
	Line   int
	Column int
}

FieldError is a field of a request that is not valid, at a JSON pointer of the request body, with a stable code of the validation-failed problem.

func (*FieldError) Error

func (e *FieldError) Error() string

type Input

type Input struct {
	Name           string
	Description    *string
	Matchers       []Matcher
	Urgent         bool
	GroupKey       []string
	DestinationIDs []string
	Policy         Policy
	// Keep are the templates an update leaves as they are stored.
	Keep KeepTemplates
}

Input is what createRoute and updateRoute write. A nil Description keeps the stored value on an update and is empty on a creation; Matchers replace the stored ones as a whole.

type KeepTemplates

type KeepTemplates struct {
	RootMessage      bool
	Line             bool
	AckTimeoutNotice bool
}

KeepTemplates says, for updateRoute, which templates the request left out: those keep the stored template, while a template given as null resets it to the built-in one (C-08.FR-1). A creation ignores it: a template left out is the built-in one.

type List

type List struct {
	Routes  []Route
	Version int64
}

List is every Route that is not deleted in evaluation order, the Default route last, with the version of the list that its ETag carries.

type Matcher

type Matcher struct {
	Label string `json:"label"`
	Op    string `json:"op"`
	Value string `json:"value"`
}

Matcher is a Matcher of a Route as the API and the Audit log show it: a label, an operator and a value.

type Membership

type Membership func(ctx context.Context, tx dbgen.DBTX, routeID int64, added, removed []int64) error

Membership is the hook that delivery runs, in the transaction tx of a Route's change, when Destinations were added to or removed from the Route routeID, by internal id (C-11.FR-14).

type OpenAlertGroupsError

type OpenAlertGroupsError struct {
	Count int64
}

OpenAlertGroupsError is the refusal to delete a Route that still has open Alert Groups (C-09.FR-19); Count says how many.

func (*OpenAlertGroupsError) Error

func (e *OpenAlertGroupsError) Error() string

type Policy

type Policy struct {
	ReopenWindowSeconds         int64      `json:"reopen_window_seconds"`
	GracePeriodSeconds          int64      `json:"grace_period_seconds"`
	UrgentRiseRemovesAck        bool       `json:"urgent_rise_removes_ack"`
	SnoozeDurationsSeconds      []int64    `json:"snooze_durations_seconds"`
	ThreadBatchingWindowSeconds int64      `json:"thread_batching_window_seconds"`
	StormThreshold              int64      `json:"storm_threshold"`
	Language                    string     `json:"language"`
	Templates                   Templates  `json:"templates"`
	AckTimeout                  AckTimeout `json:"ack_timeout"`
	Reminders                   Reminders  `json:"reminders"`
	AutoUnacknowledge           bool       `json:"auto_unacknowledge"`
}

Policy is the policy fields of a Route; each capability brings the behaviour of its fields (C-08.FR-1).

type Preview

type Preview struct {
	PeriodSeconds int64
	Truncated     bool
	Current       *PreviewSide
	Proposed      PreviewSide
}

Preview is a Group key preview: how the Alerts the Route would take in the period group with its current Group key, absent for a Route that is not saved, and with the proposed one. Truncated says that the preview stopped at routing.group_key_preview_max_alerts with Stored Snapshots of the period left unread.

type PreviewExample

type PreviewExample struct {
	GroupKeyValues map[string]string
	AlertCount     int
}

PreviewExample is one group of a PreviewSide: its Group key values, a missing label being empty, and its Alerts.

type PreviewRequest

type PreviewRequest struct {
	RouteID          string
	Matchers         []Matcher
	ProposedGroupKey []string
	PeriodSeconds    *int64
}

PreviewRequest asks for a Group key preview: of the saved Route RouteID with its own Matchers, or with Matchers when they are not nil, or of Matchers alone for a Route that is not saved yet; with the proposed Group key, over the period PeriodSeconds or, when it is nil, routing.group_key_preview_period.

type PreviewSide

type PreviewSide struct {
	AlertGroupCount int
	Examples        []PreviewExample
}

PreviewSide is how the Alerts group by one Group key: the count of distinct key values, which is the count of Alert Groups when Reopen windows and Grace periods are left aside, and the largest groups.

type Profile

type Profile struct {
	ID       string
	Name     string
	Urgent   bool
	GroupKey []string
	Policy   Policy
}

Profile is a Route profile: a starting set of Route settings that only pre-fills a new Route and is never stored.

func Profiles

func Profiles() []Profile

Profiles are the Route profiles, On-call first, read from the built-in defaults; each call returns fresh copies.

type Queries

type Queries interface {
	ListRoutes(ctx context.Context, orgID int64) ([]dbgen.ListRoutesRow, error)
	GetRoute(ctx context.Context, arg dbgen.GetRouteParams) (dbgen.GetRouteRow, error)
	LockRoute(ctx context.Context, arg dbgen.LockRouteParams) (int64, error)
	ListRouteMatchers(ctx context.Context, arg dbgen.ListRouteMatchersParams) ([]dbgen.ListRouteMatchersRow, error)
	BumpRouteOrder(ctx context.Context, arg dbgen.BumpRouteOrderParams) (int64, error)
	GetRouteOrderVersion(ctx context.Context, orgID int64) (int64, error)
	InsertRoute(ctx context.Context, arg dbgen.InsertRouteParams) (int64, error)
	EnsureDefaultRoute(ctx context.Context, arg dbgen.EnsureDefaultRouteParams) (string, error)
	UpdateRoute(ctx context.Context, arg dbgen.UpdateRouteParams) error
	DeleteRouteMatchers(ctx context.Context, arg dbgen.DeleteRouteMatchersParams) error
	InsertRouteMatcher(ctx context.Context, arg dbgen.InsertRouteMatcherParams) error
	DeleteRoute(ctx context.Context, arg dbgen.DeleteRouteParams) error
	SetRoutePositions(ctx context.Context, arg dbgen.SetRoutePositionsParams) error
	ListRouteInfo(ctx context.Context, orgID int64) ([]dbgen.ListRouteInfoRow, error)
	ListHeartbeatIntegrations(ctx context.Context, orgID int64) ([]dbgen.ListHeartbeatIntegrationsRow, error)
	ListAlertingIntegrations(ctx context.Context, orgID int64) ([]dbgen.ListAlertingIntegrationsRow, error)
	ListAlertingDestinations(ctx context.Context, orgID int64) ([]dbgen.ListAlertingDestinationsRow, error)
	ListRouteSuggestionDismissals(ctx context.Context, arg dbgen.ListRouteSuggestionDismissalsParams) ([]string,
		error)
	DismissRouteSuggestion(ctx context.Context, arg dbgen.DismissRouteSuggestionParams) error
	CountOpenAlertGroups(ctx context.Context, arg dbgen.CountOpenAlertGroupsParams) (int64, error)
	ListOpenAlertGroupCounts(ctx context.Context, orgID int64) ([]dbgen.ListOpenAlertGroupCountsRow, error)
	ResolveDestinations(ctx context.Context, arg dbgen.ResolveDestinationsParams) ([]dbgen.ResolveDestinationsRow,
		error)
	ListRouteDestinationIDs(ctx context.Context, arg dbgen.ListRouteDestinationIDsParams) (
		[]dbgen.ListRouteDestinationIDsRow, error)
	InsertRouteDestinations(ctx context.Context, arg dbgen.InsertRouteDestinationsParams) error
	DeleteRouteDestinations(ctx context.Context, arg dbgen.DeleteRouteDestinationsParams) error
	LockRouteMembership(ctx context.Context, arg dbgen.LockRouteMembershipParams) error
	BumpRoutesOfDestination(ctx context.Context, arg dbgen.BumpRoutesOfDestinationParams) (
		[]dbgen.BumpRoutesOfDestinationRow, error)
	audit.Store
	Notify(ctx context.Context, h db.Hint) error
	// DB is the pool or the transaction the queries run on, which the membership hook writes through.
	DB() dbgen.DBTX
	// contains filtered or unexported methods
}

Queries are the queries of the package, with the insert of the Audit log and the live hint.

type Reminders

type Reminders struct {
	Enabled              bool  `json:"enabled"`
	FirstIntervalSeconds int64 `json:"first_interval_seconds"`
	CapSeconds           int64 `json:"cap_seconds"`
}

Reminders is route.reminders.

type Requester

type Requester struct {
	Actor     audit.Actor
	Transport audit.Transport
	Address   netip.Addr
}

Requester is who asks for a change and how: the actor and the Transport of the Audit log entry, and the client address.

type Route

type Route struct {
	ID             int64
	PublicID       string
	Name           string
	Description    string
	Position       int
	IsDefault      bool
	Urgent         bool
	Matchers       []Matcher
	GroupKey       []string
	Policy         Policy
	DestinationIDs []string
	Storm          *Storm
	TemplateError  *TemplateError
	CreatedAt      time.Time
	Version        int64
	// OpenAlertGroupCount is the number of its open Alert Groups, which block its deletion (C-09.FR-19).
	OpenAlertGroupCount int64
}

Route is a Route as the API reads it; Position is its zero-based place in evaluation order, DestinationIDs the public_ids of its Destinations that are not deleted, in order, and Storm its active Storm, nil when there is none.

type Router

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

Router routes newly firing Alerts (C-08.FR-3, FR-6, FR-13): it is the Sink of Snapshot processing. Each Alert of a fired change is taken by the first Route in evaluation order whose Matchers match its labels, Static labels applied, and gets its Severity level; both are recorded on the Alert, which keeps them until it fires again, so an edit or a reorder applies to the next Alerts only. The order with its compiled Matchers is cached per replica: a route hint drops it, and every Snapshot compares the stamp of the Routes in its own transaction, so that a change made on any replica applies at once.

func NewRouter

func NewRouter(orgID int64) *Router

NewRouter returns the Router of the Organization orgID.

func (*Router) AlertChanges

func (r *Router) AlertChanges(ctx context.Context, tx ingestdb.DBTX, changes []ingest.AlertChange) (ingest.Routed,
	error)

AlertChanges routes the Alerts of the fired changes in the Snapshot's transaction tx, and the listed Alerts that fire without a Route, such as one that fired before routing took it; other changes are not routed. It returns the Routes that took them, in evaluation order.

func (*Router) Invalidate

func (r *Router) Invalidate()

Invalidate drops the cached evaluation order: a hint said that a Route changed.

type Service

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

Service holds the Routes of the Organization.

func New

func New(cfg Config) *Service

New returns the Service of the Organization in cfg.

func (*Service) AcceptSuggestion

func (s *Service) AcceptSuggestion(ctx context.Context, r Requester, id string, destinationIDs []string) (Route,
	error)

AcceptSuggestion creates the Route of the suggestion id at the top of the evaluation order, with destinationIDs when they are given, and records route.created with the suggestion; the Route for Internal alerts needs destinationIDs and goes directly below the last Route other than the Default route that takes an Internal alert, when one does (D268). A suggestion that no longer applies, checked under the lock of the list, is ErrSuggestionObsolete.

func (*Service) Create

func (s *Service) Create(ctx context.Context, r Requester, in Input) (Route, error)

Create creates a Route at the last position before the Default route; a name another Route has is ErrNameTaken. Its templates are dry-run against the built-in example first (C-12.FR-5).

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, r Requester, publicID string, version *int64) error

Delete deletes the Route publicID; a non-nil version must be its current one. It leaves every list and the evaluation order at once; the row stays for the history that points at it. The Default route is ErrDefaultImmutable.

func (*Service) DestinationDeleted

func (s *Service) DestinationDeleted(ctx context.Context, tx dbgen.DBTX, destinationID int64) error

DestinationDeleted is the hook of the Destinations (C-11.FR-14), in the transaction tx that deletes the Destination destinationID, before it leaves its Routes: each Route that is not deleted and has it gets a new version — the Destination leaves its destination_ids — and its hint, and its membership lock is taken, so that no Enqueue on it runs until tx ends. The Routes are locked in id order before their membership locks; a transaction that renders Alert Groups of several Routes at once and holds the membership lock of one of them may still deadlock with it, which PostgreSQL detects and ends.

func (*Service) DismissSuggestion

func (s *Service) DismissSuggestion(ctx context.Context, userID int64, id string) error

DismissSuggestion hides the suggestion id from the User userID; a suggestion that no longer applies is ErrSuggestionObsolete. Dismissing it again changes nothing.

func (*Service) Get

func (s *Service) Get(ctx context.Context, publicID string) (Route, error)

Get reads the Route publicID; a deleted or unknown one is ErrNotFound.

func (*Service) InfoChanged

func (s *Service) InfoChanged()

InfoChanged asks RunInfo to refresh muster_route_info: a hint said a Route changed, maybe on another replica. It never blocks.

func (*Service) List

func (s *Service) List(ctx context.Context) (List, error)

List lists the Routes that are not deleted in evaluation order with the version of the list. The version is read first, so that the list is never older than its ETag.

func (*Service) Preview

func (s *Service) Preview(ctx context.Context, req PreviewRequest) (Preview, error)

Preview previews a Group key over the Stored Snapshots of the period (C-08.FR-5). Each distinct Alert reported firing, with its labels from the newest Snapshot listing it and its Integration's current Static labels, counts when the Route takes it in the current evaluation order as routing evaluates it: a saved Route at its place, with its own Matchers or with the given ones, and Matchers alone as a new Route just before the Default route, where createRoute puts it. It reads at most PreviewMaxAlerts such Alerts, from the newest Snapshot back.

func (*Service) RefreshInfo

func (s *Service) RefreshInfo(ctx context.Context) error

RefreshInfo makes muster_route_info list exactly the Routes that are not deleted, the Default route included, as the database has them, whichever replica changed them (C-08.FR-12), and gives each its series of muster_template_errors_total; a deleted Route loses them.

func (*Service) Reorder

func (s *Service) Reorder(ctx context.Context, r Requester, version *int64, ids []string) (List, error)

Reorder replaces the order of every Route except the Default route with ids, in one transaction; a non-nil version must be the current version of the list (the list ETag). A list that names the Default route is ErrDefaultImmutable; one whose Routes differ from the current set is a route_set_mismatch FieldError.

func (*Service) RunInfo

func (s *Service) RunInfo(ctx context.Context, ticks <-chan time.Time)

RunInfo keeps muster_route_info current until ctx ends: it refreshes it at once, after InfoChanged and at every tick, which also repairs a refresh that failed.

func (*Service) SetMembership

func (s *Service) SetMembership(m Membership)

SetMembership fills the hook of delivery for Destinations added to or removed from a Route, before any Route changes.

func (*Service) SetTemplates

func (s *Service) SetTemplates(h TemplateHooks)

SetTemplates fills the template checks of messages, before any Route is created or updated.

func (*Service) Suggestions

func (s *Service) Suggestions(ctx context.Context, userID *int64) ([]Suggestion, error)

Suggestions lists the Route suggestions that apply now and that the User userID, if any, has not dismissed; they are computed on each read.

func (*Service) Update

func (s *Service) Update(ctx context.Context, r Requester, publicID string, version *int64, in Input) (Route, error)

Update replaces the configured fields of the Route publicID; a non-nil version must be its current one (If-Match). The change applies at once to the next Alerts routed; an Alert already routed keeps its Route (C-08.FR-8). The Default route takes no Matchers. A template in.Keep names stays as stored; a new template is dry-run first, and saving one clears the Route's template error about it (C-12.FR-5, FR-6).

type Severities

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

Severities map the severity label of Alerts to Severity levels by the Organization's settings (organization.severity_label and organization.severity_mapping, C-08.FR-6).

func NewSeverities

func NewSeverities(label string, mapping []organization.SeverityMapping) Severities

NewSeverities returns the Severity levels by the label and its mapping; the first mapping of a value wins.

func (Severities) Of

func (s Severities) Of(labels map[string]string) Severity

Of is the Severity level of an Alert with the labels: the level its severity value maps to; warning, keeping the value as received, for a value without a mapping; info for an Alert without the label or with an empty value.

type Severity

type Severity struct {
	Level organization.SeverityLevel
	// Raw is the value of the severity label shown as received; empty when the value is mapped or missing.
	Raw string
}

Severity is the Severity level of an Alert and, when its value has no mapping, the value as received.

type Snapshots

type Snapshots interface {
	Retention(ctx context.Context) (time.Duration, error)
	Firing(ctx context.Context, since time.Time, visit func([]ingest.FiringAlert) bool) (ingest.FiringRead, error)
}

Snapshots reads the Stored Snapshots for the Group key preview (internal/ingest).

type Store

type Store interface {
	Queries
	InTx(ctx context.Context, f func(Queries) error) error
	On(tx dbgen.DBTX) Queries
}

Store runs the queries alone, in one transaction, or in a caller's transaction tx (On).

func NewStore

func NewStore(pool *pgxpool.Pool) Store

NewStore is the Store over the main pool.

type Storm

type Storm struct {
	Since           time.Time
	AlertGroupCount int64
}

Storm is the active Storm of a Route (C-11.FR-6): when it started and the new Alert Groups it counted, those of its Storm summary.

type Suggestion

type Suggestion struct {
	ID    string
	Route Input
}

Suggestion is a Route suggestion that applies, with the Route accepting it creates at the top of the list, or for internal_alerts directly below the last Route other than the Default route that takes an Internal alert.

type TemplateError

type TemplateError struct {
	Since time.Time
	Error string
}

TemplateError is the template error state of a Route (C-12.FR-6): since when a template of it keeps failing and what failed.

type TemplateHooks

type TemplateHooks struct {
	Check func(ctx context.Context, routeID int64, kind, source, language string) error
	Saved func(ctx context.Context, tx dbgen.DBTX, routeID int64, publicID string, kinds []string) error
}

TemplateHooks are the template checks of messages, wired in the runtime: Check dry-runs a template of the Route routeID, 0 for a new Route, and returns a *templates.Error for a template that fails; Saved clears the Route's template error, in the transaction tx that saved new templates of the kinds given.

type Templates

type Templates struct {
	RootMessage      *string `json:"root_message"`
	Line             *string `json:"line"`
	AckTimeoutNotice *string `json:"ack_timeout_notice"`
}

Templates are the message templates of a Route; nil uses the built-in template.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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