types

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 16 Imported by: 12 modules, 13 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.

README

slackmgr/types

Go Reference Go Report Card CI

A Go shared library package providing common interfaces and data structures for the Slack Manager system. This package defines contracts for database access, logging, metrics, and core domain types like alerts and issues.

Important: When to Use This Library

Most users don't need to import this library directly. When using the Slack Manager, this package is automatically pulled in as a dependency by other components in the ecosystem:

You only need to import this library directly if:

  • You're developing a custom database plugin (implementing the DB interface)
  • You're developing a custom queue/messaging plugin
  • You're building custom tooling that needs access to the core types

For sending alerts to Slack Manager, use the Go Client instead.

Overview

The types package serves as the foundation for the Slack Manager ecosystem, providing:

  • Dependency Injection Interfaces: Abstractions for database, logging, and metrics that allow implementations to be plugged in
  • Core Domain Types: Rich type definitions for alerts, issues, webhooks, and escalations
  • Validation & Cleaning: Built-in validation and normalization for all data structures
  • Type Safety: Strongly-typed enums for severities, access levels, button styles, and display modes

This library is used by the main Slack Manager application, infrastructure plugins, and the Go client.

Installation

go get github.com/slackmgr/types

Core Interfaces

These interfaces define the contracts that implementations must satisfy. They enable dependency injection and allow the Slack Manager to work with different storage backends, logging frameworks, and metrics systems.

DB Interface

The DB interface abstracts all database operations for the Slack Manager. Implementations must handle persistence for alerts, issues, move mappings, and channel processing state.

type DB interface {
    Init(ctx context.Context, skipSchemaValidation bool) error
    SaveAlert(ctx context.Context, alert *Alert) error
    SaveIssue(ctx context.Context, issue Issue) error
    SaveIssues(ctx context.Context, issues ...Issue) error
    MoveIssue(ctx context.Context, issue Issue, sourceChannelID, targetChannelID string) error
    FindOpenIssueByCorrelationID(ctx context.Context, channelID, correlationID string) (string, json.RawMessage, error)
    FindIssueBySlackPostID(ctx context.Context, channelID, postID string) (string, json.RawMessage, error)
    FindActiveChannels(ctx context.Context) ([]string, error)
    LoadOpenIssuesInChannel(ctx context.Context, channelID string) (map[string]json.RawMessage, error)
    SaveMoveMapping(ctx context.Context, moveMapping MoveMapping) error
    FindMoveMapping(ctx context.Context, channelID, correlationID string) (json.RawMessage, error)
    DeleteMoveMapping(ctx context.Context, channelID, correlationID string) error
    SaveChannelProcessingState(ctx context.Context, state *ChannelProcessingState) error
    FindChannelProcessingState(ctx context.Context, channelID string) (*ChannelProcessingState, error)
    DropAllData(ctx context.Context) error
}

Key Points:

  • Issues and move mappings are stored as opaque JSON (json.RawMessage) to allow implementation flexibility
  • Database implementations should never depend on the internal structure of issues or move mappings
  • Implementations available: DynamoDB plugin, PostgreSQL plugin
Logger Interface

The Logger interface provides structured logging with field support and multiple log levels.

type Logger interface {
    Debug(msg string)
    Debugf(format string, args ...any)
    Info(msg string)
    Infof(format string, args ...any)
    Error(msg string)
    Errorf(format string, args ...any)
    WithField(key string, value any) Logger
    WithFields(fields map[string]any) Logger
}

Key Points:

  • Supports Debug, Info, and Error levels
  • Allows chaining with WithField and WithFields for structured logging
  • A no-op implementation (NoopLogger) is provided for testing
Metrics Interface

The Metrics interface provides Prometheus-style metrics with support for counters, gauges, and histograms.

type Metrics interface {
    RegisterCounter(name, help string, labels ...string)
    RegisterGauge(name, help string, labels ...string)
    RegisterHistogram(name, help string, buckets []float64, labels ...string)
    Add(name string, value float64, labelValues ...string)
    Inc(name string, labelValues ...string)
    Set(name string, value float64, labelValues ...string)
    Observe(name string, value float64, labelValues ...string)
}

Key Points:

  • Supports standard Prometheus metric types
  • Labels can be defined at registration and specified at observation time
  • A no-op implementation (NoopMetrics) is provided for testing

Core Domain Types

Alert

The Alert struct is the central type representing an alert sent to the Slack Manager. It contains comprehensive information about the alert including severity, content, routing, escalations, and webhooks.

Constructor Functions:

func NewPanicAlert() *Alert     // Severity: panic
func NewErrorAlert() *Alert     // Severity: error
func NewWarningAlert() *Alert   // Severity: warning
func NewResolvedAlert() *Alert  // Severity: resolved
func NewInfoAlert() *Alert      // Severity: info

Key Fields:

Field Type Description
Timestamp time.Time When the alert was created (auto-replaced if > 7 days old)
CorrelationID string Groups related alerts into issues (auto-generated if not set)
Severity AlertSeverity Alert severity: panic, error, warning, resolved, or info
Header string Alert title (max 130 chars, auto-truncated)
Text string Alert body (max 10,000 chars, auto-truncated)
SlackChannelID string Target Slack channel ID or name
RouteKey string Alternative routing via configured routes
IssueFollowUpEnabled bool Whether to track this alert as an issue. If false (always for new info alerts), the alert is a fire-and-forget notification: a Slack post only, never counted as an issue
AutoResolveSeconds int Auto-resolve after N seconds (30 - 63,113,851)
Webhooks []*Webhook Interactive buttons (max 5)
Escalation []*Escalation Escalation points (max 3)
Fields []*Field Additional key-value fields (max 20)
Username string Slack bot username the alert is posted as (max 100 chars, auto-truncated)
Client string Optional, free-form identifier of the client (monitoring tool or integration) that produced the alert (max 100 chars, auto-truncated). Used only for grouping, filtering and reporting (insights and dashboards), never for routing or Slack rendering

Methods:

  • Clean(): Normalizes and truncates all fields to valid values
  • Validate(): Returns error if any field is invalid
  • UniqueID(): Returns a deterministic, base64-encoded unique ID
  • EffectiveClient(): Returns the client used for grouping and reporting: the trimmed Client, else the trimmed Username, else UnknownClient ("unknown"). Falling back to Username is permanent, supported behaviour, so setting Client is optional

Validation:

  • The package defines extensive constants for maximum lengths (e.g., MaxHeaderLength = 130)
  • All validation methods return descriptive errors
  • Validation includes: channel IDs, URLs, emoji format, severity values, escalation timing

Special Features:

  • Status Emoji Replacement: Use :status: in header or text, and it will be replaced with the appropriate emoji based on severity
  • Conditional Content: HeaderWhenResolved and TextWhenResolved allow different content for resolved states
  • Auto-correlation: If no CorrelationID is provided, one is generated by hashing key fields
  • Ignore Patterns: IgnoreIfTextContains allows filtering out known noise
AlertSeverity

Alert severity levels with associated emojis in Slack:

const (
    AlertPanic    AlertSeverity = "panic"    // Panic icon
    AlertError    AlertSeverity = "error"    // Red error icon
    AlertWarning  AlertSeverity = "warning"  // Yellow warning icon
    AlertResolved AlertSeverity = "resolved" // Green OK icon
    AlertInfo     AlertSeverity = "info"     // Blue info icon
)

Helper Functions:

  • SeverityIsValid(s AlertSeverity) bool
  • SeverityPriority(s AlertSeverity) int (3 = panic, 2 = error, 1 = warning, 0 = resolved/info)
  • ValidSeverities() []string
Escalation

Defines escalation points that trigger when an issue remains unresolved.

type Escalation struct {
    Severity      AlertSeverity  // New severity when escalation triggers
    DelaySeconds  int            // Delay since issue creation (min 30s)
    SlackMentions []string       // Mentions to add (e.g., "<!here>", "<@U12345678>")
    MoveToChannel string         // Move issue to different channel
}

Key Points:

  • Escalations are sorted by DelaySeconds and triggered in order
  • Minimum delay: 30 seconds, minimum diff between escalations: 30 seconds
  • Severity can only be panic, error, or warning (not resolved or info)
  • Maximum 3 escalation points per alert
Webhook

Interactive buttons that appear on Slack posts. When clicked, they trigger HTTP POST requests or custom handlers.

type Webhook struct {
    ID                     string                    // Unique within alert
    URL                    string                    // HTTP URL or handler identifier
    ButtonText             string                    // Button label (max 25 chars)
    ButtonStyle            WebhookButtonStyle        // "primary" or "danger"
    AccessLevel            WebhookAccessLevel        // Who can click: global_admins, channel_admins, channel_members
    DisplayMode            WebhookDisplayMode        // When to show: always, open_issue, resolved_issue
    ConfirmationText       string                    // Optional confirmation dialog text
    SkipConfirmationDialog bool                      // If true, post the webhook without showing a confirmation dialog (must be false when ButtonStyle is "danger" or when PlainTextInput/CheckboxInput is non-empty)
    Payload                map[string]any            // Data sent in POST body
    PlainTextInput         []*WebhookPlainTextInput  // Text input fields
    CheckboxInput          []*WebhookCheckboxInput   // Checkbox groups
    AfterClick             *WebhookAfterClick        // Optional post-click state, see below
}

Related Types:

  • WebhookPlainTextInput: Text input with min/max length, multiline support, initial value
  • WebhookCheckboxInput: Checkbox group with label and multiple options
  • WebhookCheckboxOption: Individual checkbox with value, text, and selected state
  • WebhookAfterClick: Post-click state (see below)

Enums:

  • WebhookButtonStyle: primary, danger
  • WebhookAccessLevel: global_admins, channel_admins, channel_members
  • WebhookDisplayMode: always, open_issue, resolved_issue
  • WebhookHideButtons: none, clicked, all

Post-click state (AfterClick):

Webhook receivers often take a while before they update the alert. AfterClick changes the Slack post as soon as the webhook is delivered, so everyone in the channel sees that the action is in progress, and duplicate clicks are avoided:

type WebhookAfterClick struct {
    HideButtons       WebhookHideButtons // "none" (default), "clicked" or "all"
    HideWebhookIDs    []string           // Additional webhooks (by ID) to hide; must exist in the alert
    StatusText        string             // Optional text shown on the post (max 200 chars)
    ResetAfterSeconds int                // 0 = default 300 (5 min), max 86400 (24h)
}
  • Applied only when the webhook was delivered. On failure, the post is unchanged and the clicking user is informed.
  • Cleared by the next alert for the issue, even if the alert is otherwise unchanged or ignored.
  • If no alert arrives within ResetAfterSeconds, the buttons are shown again with a note that no update was received.
  • Helpers: ResetAfter() (with the default applied) and HidesWebhook(clickedID, webhookID).
WebhookCallback

Represents data received when a webhook is triggered by a user clicking a button.

type WebhookCallback struct {
    ID            string              // Webhook ID
    UserID        string              // Slack user ID who clicked
    UserRealName  string              // User's display name
    ChannelID     string              // Channel where button was clicked
    MessageID     string              // Slack message ID
    Timestamp      time.Time           // When button was clicked
    PlainTextInput map[string]string   // Text input values
    CheckboxInput  map[string][]string // Checkbox selected values
    Payload        map[string]any      // Original webhook payload + metadata

    // Deprecated: legacy copy of PlainTextInput (JSON key "input"), only populated when
    // the manager runs with legacy features enabled
    Input map[string]string
}

Helper Methods:

  • GetPayloadValue(key string) any
  • GetPayloadString(key string) string
  • GetPayloadInt(key string, defaultValue int) int
  • GetPayloadBool(key string, defaultValue bool) bool
  • GetInputValue(key string) string
  • GetCheckboxInputSelectedValues(key string) []string
WebhookResult

Optional feedback from a synchronous webhook receiver (e.g. an HTTP endpoint) on a button click. The receiver responds with a JSON body wrapped in the slackManagerResult key (WebhookResultKey), so existing response bodies are never mistaken for results. Acceptance is signalled by the response itself (for HTTP: 2xx = accepted, 4xx = rejected), not by the body:

{"slackManagerResult": {"message": "3 pods will be restarted", "afterClick": {"hideButtons": "all", "statusText": "Restart in progress"}}}
type WebhookResponse struct {
    Result *WebhookResult // JSON key "slackManagerResult"; nil if missing
}

type WebhookResult struct {
    Message    string             // Optional message for the clicking user (plain text, max 1000 chars)
    AfterClick *WebhookAfterClick // Optional, overrides Webhook.AfterClick for this click; ignored when rejected
}
  • Clean() trims whitespace and applies defaults; Validate() checks the message length and the after-click settings. AfterClick.HideWebhookIDs can't be checked against the alert here, so each ID only needs to be non-empty and at most MaxWebhookIDLength chars.
  • Asynchronous handlers (e.g. queues) have no response; those receivers update the alert instead.
Issue

The Issue interface represents an issue in a Slack channel. Issues group related alerts together and track their resolution status.

type Issue interface {
    json.Marshaler
    ChannelID() string        // Slack channel ID
    UniqueID() string         // Base64-encoded unique ID for storage
    GetCorrelationID() string // Correlation ID for grouping alerts
    IsOpen() bool             // Whether issue is open (not archived)
    CurrentPostID() string    // Slack message ID (empty if no post yet)
}

Key Points:

  • The actual implementation is internal to the Slack Manager and may change
  • Database implementations must store issues as opaque JSON
  • Correlation IDs are not guaranteed to be unique and should not be used as database keys
MoveMapping

The MoveMapping interface tracks issues that have been moved from one channel to another.

type MoveMapping interface {
    json.Marshaler
    ChannelID() string        // Original channel ID
    UniqueID() string         // Base64-encoded unique ID for storage
    GetCorrelationID() string // Correlation ID that was moved
}

Key Points:

  • Ensures new alerts with the same correlation ID go to the new channel
  • Stored as opaque JSON in the database
  • Internal implementation may change without notice
ChannelProcessingState

Tracks per-channel processing state to prevent concurrent processing and ensure regular intervals.

type ChannelProcessingState struct {
    ChannelID           string    // Slack channel ID
    Created             time.Time // When processing state was created
    LastChannelActivity time.Time // Last activity in channel
    LastProcessed       time.Time // When channel was last processed
    OpenIssues          int       // Number of open issues (excluding fire-and-forget notifications)
}

Constructor:

func NewChannelProcessingState(channelID string) *ChannelProcessingState

Insights

Insights is an optional, queryable record of what the Slack Manager does: alert outcomes, issue lifecycle, user commands, Slack posts and periodic channel snapshots. It complements logs and metrics with a per-channel, per-issue, human-oriented view for dashboards.

InsightsEvent
type InsightsEvent struct {
    Time             time.Time
    Type             InsightsEventType  // e.g. "alert.grouped", "issue.archived", "command.executed"
    Reason           string             // sub-classification, depends on Type
    ChannelID        string
    RelatedChannelID string             // e.g. move target
    IssueID          string
    CorrelationID    string
    Severity         AlertSeverity
    PrevSeverity     AlertSeverity
    RouteKey, AlertType, Host, Author string
    Client           string             // effective client of the alert (Alert.EffectiveClient), max 100 chars
    ActorID, ActorName string           // Slack user (commands)
    Count            int
    Detail           string             // short free text, max 200 chars
    Values           map[string]float64 // numeric facts, e.g. "open_s", "time_to_resolve_s"
}

Events carry identifiers and classifications only, never alert content. They do include some personal data: the alert Host and Author, the Client (which falls back to the alert Username, and some integrations post as a person), and the Slack user ID and real name of users who run commands (ActorID, ActorName). Keep this in mind when choosing the storage retention. Every event type, reason and value key is defined as a documented constant (InsightsEvent*, InsightsReason*, InsightsValue*). Events are best-effort: they may be lost (e.g. buffer overflow), in which case an insights.gap event records how many were lost.

Interfaces

All insights interfaces are optional. DB is unchanged, and implementations without insights support keep working.

Interface Purpose
InsightsSink WriteInsightsEvents(ctx, []InsightsEvent): persists a batch of events. Must not share connection capacity or transactions with regular writes.
InsightsSinkProvider Optionally implemented by a DB. Returns the sink, or nil when recording is disabled.
InsightsReader Query primitives: CountInsightsEvents (grouped counts, time buckets, distinct counts, top-N), InsightsValueStats (sum/avg/min/max/percentiles of a value), ListInsightsEvents (cursor-paginated listing), LoadOpenIssues. Must only require read privileges.
InsightsReaderProvider Optionally implemented by a DB. Returns the reader, or nil.

ErrInsightsNotSupported is returned when insights are not available. Queries (InsightsCountQuery, InsightsStatsQuery, InsightsListQuery) have a Validate() method enforcing shared limits, e.g. a maximum time range of 366 days and at most 2000 time buckets.

Count and stats queries can group by the dimensions bucket, channel, related_channel, type, reason, severity, route_key, alert_type, host, author, client, actor, correlation_id and issue (InsightsDimension*). InsightsFilter filters on the time range (required), the list fields ChannelIDs, RelatedChannelIDs, Types, Reasons, Severities, RouteKeys and Clients (each at most MaxInsightsFilterValues values, matching any of them), and the single values IssueID, CorrelationID and ActorID. Events without a client (e.g. channel.stats, insights.gap) never match a Clients filter.

Count and stats queries return at most MaxInsightsRows (10,000) groups. With an explicit Limit (e.g. top-N), further groups are silently dropped. Without one, a query matching more groups fails with ErrInsightsTooManyRows rather than returning a truncated result.

Authentication

The REST API of slackmgr/core supports optional, pluggable authentication. This package defines the contract, so that authenticators (e.g. an OIDC plugin) can be implemented without depending on core.

type Principal struct {
    ID         string            // stable caller identity, e.g. "alertmanager-prod"
    Scopes     []string          // e.g. ScopeAlertsWrite
    Attributes map[string]string // authenticator specific, e.g. token claims
}

type Authenticator interface {
    Authenticate(r *http.Request) (*Principal, error)
}

type Authorizer interface {
    Authorize(ctx context.Context, principal *Principal, scope string) error
}
Scope Allows
ScopeAlertsWrite (alerts:write) Sending alerts and Prometheus webhooks
ScopeAlertsTest (alerts:test) Testing alerts (POST /alerts-test)
ScopeConfigRead (config:read) Reading routing rules and managed channels
ScopeAll (*) Everything

An Authenticator returns ErrNoCredentials when the request has no credentials it handles (HTTP 401, or anonymous in permissive mode), and ErrInvalidCredentials when they are invalid (HTTP 401). An Authorizer returns ErrForbidden to deny (HTTP 403). Any other error is an internal error (HTTP 500, fail closed). Errors may be wrapped.

An Authorizer that also implements ChannelAuthorizer (AuthorizeChannel(ctx, principal, channelID) error) decides which Slack channels a principal may send alerts to, including the channels escalations may move issues to. Without it, the API uses its built-in channel access rules.

ChainAuthenticators tries several authenticators in order and returns the first principal, or the most significant error (internal, then invalid, then no credentials). AuthenticatorFunc and AuthorizerFunc adapt plain functions. Principal.HasScope checks a scope, honouring ScopeAll.

Field Specifications

The Field struct is used for additional key-value pairs displayed in Slack:

type Field struct {
    Title string // Max 30 chars, auto-truncated
    Value string // Max 200 chars, auto-truncated
}

Maximum 20 fields per alert.

Testing Utilities

Database Testing

The dbtests package provides a shared test suite that can be run against any DB implementation:

import "github.com/slackmgr/types/dbtests"

// In your database implementation tests:
func TestDatabaseCompliance(t *testing.T) {
    db := NewYourDatabase()
    dbtests.RunAllTests(t, db)
}

This ensures your database implementation correctly satisfies the DB interface contract.

Implementations that support insights can also run the insights compliance suite:

dbtests.RunAllInsightsTests(t, db, sink, reader)
No-op Implementations

For testing purposes, no-op implementations are provided:

  • NoopLogger: Logger that does nothing
  • NoopMetrics: Metrics that do nothing
  • InMemoryFifoQueue: Simple in-memory FIFO queue (test-only, not for production)

Usage Example

package main

import (
    "github.com/slackmgr/types"
)

func main() {
    // Create an alert
    alert := types.NewErrorAlert()
    alert.Header = "Database Connection Failed"
    alert.Text = "Unable to connect to production database. Error: connection timeout"
    alert.SlackChannelID = "C12345678"
    alert.IssueFollowUpEnabled = true
    alert.AutoResolveSeconds = 300 // Auto-resolve after 5 minutes

    // Add fields
    alert.Fields = []*types.Field{
        {Title: "Host", Value: "db-prod-01"},
        {Title: "Port", Value: "5432"},
    }

    // Add escalation
    alert.Escalation = []*types.Escalation{
        {
            Severity:      types.AlertPanic,
            DelaySeconds:  300,
            SlackMentions: []string{"<!here>"},
        },
    }

    // Add webhook button
    alert.Webhooks = []*types.Webhook{
        {
            ID:               "restart",
            URL:              "https://example.com/webhook/restart",
            ButtonText:       "Restart DB",
            ButtonStyle:      types.WebhookButtonStyleDanger,
            AccessLevel:      types.WebhookAccessLevelChannelAdmins,
            ConfirmationText: "Are you sure you want to restart the database?",
            Payload: map[string]any{
                "action": "restart_database",
                "host":   "db-prod-01",
            },
        },
    }

    // Clean and validate
    alert.Clean()
    if err := alert.Validate(); err != nil {
        panic(err)
    }

    // Use with Slack Manager API or directly with the manager
}

Validation Constants

The package defines extensive validation constants. Key limits include:

Constant Value Description
MaxHeaderLength 130 Alert header length
MaxTextLength 10,000 Alert text length
MaxFieldCount 20 Fields per alert
MaxWebhookCount 5 Webhooks per alert
MaxWebhookAfterClickStatusTextLength 200 Webhook after-click status text length
DefaultWebhookAfterClickResetSeconds 300 Default webhook after-click reset delay
MaxWebhookAfterClickResetSeconds 86,400 Maximum webhook after-click reset delay (24h)
MaxWebhookResultMessageLength 1,000 Webhook result message length
MaxEscalationCount 3 Escalation points per alert
MinAutoResolveSeconds 30 Minimum auto-resolve time
MaxAutoResolveSeconds 63,113,851 Maximum auto-resolve time (~2 years)
MinEscalationDelaySeconds 30 Minimum first escalation delay
MinEscalationDelayDiffSeconds 30 Minimum time between escalations

See alert.go and webhook_after_click.go for the complete list of constants.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Copyright (c) 2026 Peter Aglen

Documentation

Overview

Package types provides shared interfaces and data structures for the Slack Manager system.

This package defines contracts for database access, logging, metrics, and core domain types like alerts and issues. It serves as the foundation for the Slack Manager ecosystem, enabling dependency injection and allowing different implementations to be plugged in.

Core Interfaces

DB - Database abstraction for persisting alerts, issues, move mappings, and channel processing state. Implementations must handle storage as opaque JSON to allow flexibility.

Logger - Structured logging interface with Debug/Info/Error levels and field support. Supports method chaining with WithField and WithFields.

Metrics - Prometheus-style metrics interface supporting counters, gauges, and histograms. Allows registration of metrics with labels and observation of values.

Core Domain Types

Alert - The central type representing an alert with comprehensive validation and cleaning. Contains severity, header, text, fields, webhooks, escalations, and routing information. Use constructor functions: NewPanicAlert(), NewErrorAlert(), NewWarningAlert(), NewResolvedAlert(), NewInfoAlert().

Issue - Interface for tracking issue state in channels. Issues group related alerts together using correlation IDs. The actual implementation is internal and stored as opaque JSON.

MoveMapping - Interface for tracking issues that have been moved between channels. Ensures new alerts with the same correlation ID go to the new channel.

ChannelProcessingState - Tracks per-channel processing timestamps and open issue counts to prevent concurrent processing and ensure regular intervals.

Authentication

Principal, Authenticator and Authorizer define optional, pluggable authentication and authorization for the REST API of the Slack Manager core library. Scopes (ScopeAlertsWrite, ScopeAlertsTest, ScopeConfigRead, ScopeAll) name the permissions of the API endpoints. ChannelAuthorizer optionally restricts the Slack channels a principal may send alerts to. ChainAuthenticators combines several authenticators.

Insights

InsightsEvent is a structured, queryable record of what the Slack Manager did (alert outcomes, issue lifecycle, commands, Slack posts, channel snapshots). DB implementations may optionally support recording and reading insights by implementing InsightsSinkProvider and InsightsReaderProvider. The InsightsSink and InsightsReader interfaces, and the InsightsCountQuery, InsightsStatsQuery and InsightsListQuery types, define the contract.

Webhook Support

The package provides rich webhook support with interactive buttons, input forms, and access control:

  • Webhook - Interactive button configuration with HTTP callbacks or custom handlers
  • WebhookCallback - Data received when a webhook is triggered
  • WebhookAccessLevel - Control who can click buttons (global_admins, channel_admins, channel_members)
  • WebhookButtonStyle - Visual style (primary, danger)
  • WebhookDisplayMode - When to show buttons (always, open_issue, resolved_issue)

Validation and Cleaning

Alert provides extensive validation and cleaning methods:

  • Clean() - Normalizes and truncates all fields to valid values
  • Validate() - Returns error if any field is invalid
  • Individual validation methods for specific fields (ValidateSlackChannelIDAndRouteKey, etc.)

The package defines comprehensive constants for maximum lengths and limits (e.g., MaxHeaderLength = 130).

Testing Utilities

The dbtests subpackage provides a shared test suite that can be run against any DB implementation to ensure compliance with the interface contract, and an insights suite (RunAllInsightsTests) for implementations that support insights.

No-op implementations (NoopLogger, NoopMetrics) are provided for testing purposes. InMemoryFifoQueue is provided for testing but should not be used in production.

Usage Example

// Initialize a new error-level notification
alert := types\.NewErrorAlert()
alert.Header = "Database Connection Failed"
alert.Text = "Unable to connect to production database"
alert.SlackChannelID = "C12345678"
alert.IssueFollowUpEnabled = true
alert.AutoResolveSeconds = 300

// Add fields
alert.Fields = []*types\.Field{
    {Title: "Host", Value: "db-prod-01"},
    {Title: "Port", Value: "5432"},
}

// Add escalation
alert.Escalation = []*types\.Escalation{
    {
        Severity:      types\.AlertPanic,
        DelaySeconds:  300,
        SlackMentions: []string{"<!here>"},
    },
}

// Add webhook button
alert.Webhooks = []*types\.Webhook{
    {
        ID:          "restart",
        URL:         "https://example.com/webhook/restart",
        ButtonText:  "Restart DB",
        ButtonStyle: types\.WebhookButtonStyleDanger,
        AccessLevel: types\.WebhookAccessLevelChannelAdmins,
    },
}

// Clean and validate
alert.Clean()
if err := alert.Validate(); err != nil {
    panic(err)
}

Index

Constants

View Source
const (
	// MaxTimestampAge is the maximum age of an alert timestamp.
	// If the timestamp is older than this, it will be replaced with the current time.
	MaxTimestampAge = 7 * 24 * time.Hour

	// MaxSlackChannelIDLength is the maximum length of a Slack channel ID or name.
	MaxSlackChannelIDLength = 80
	// MaxRouteKeyLength is the maximum length of a routing key for channel routing.
	MaxRouteKeyLength = 1000
	// MaxHeaderLength is the maximum length of the alert header (title).
	// Slack's header block limit is 150 characters; we reserve space for status emoji replacement.
	MaxHeaderLength = 130
	// MaxFallbackTextLength is the maximum length of the fallback notification text.
	MaxFallbackTextLength = 150
	// MaxTextLength is the maximum length of the alert text (body).
	MaxTextLength = 10000
	// MaxAuthorLength is the maximum length of the author field.
	MaxAuthorLength = 100
	// MaxHostLength is the maximum length of the host field.
	MaxHostLength = 100
	// MaxFooterLength is the maximum length of the footer field.
	MaxFooterLength = 300
	// MaxUsernameLength is the maximum length of the bot username.
	MaxUsernameLength = 100
	// MaxClientLength is the maximum length of the client identifier ([Alert.Client]).
	MaxClientLength = 100
	// MaxFieldTitleLength is the maximum length of a field title.
	MaxFieldTitleLength = 30
	// MaxFieldValueLength is the maximum length of a field value.
	MaxFieldValueLength = 200
	// MaxIconEmojiLength is the maximum length of the icon emoji (excluding colons).
	MaxIconEmojiLength = 50
	// MaxMentionLength is the maximum length of a Slack mention (excluding angle brackets).
	MaxMentionLength = 20
	// MaxCorrelationIDLength is the maximum length of the correlation ID.
	MaxCorrelationIDLength = 500

	// MinAutoResolveSeconds is the minimum seconds before auto-resolving an issue.
	MinAutoResolveSeconds = 30
	// MaxAutoResolveSeconds is the maximum seconds before auto-resolving an issue (approximately 2 years).
	MaxAutoResolveSeconds = 63113851

	// MaxIgnoreIfTextContainsLength is the maximum length of each ignore pattern.
	MaxIgnoreIfTextContainsLength = 1000
	// MaxIgnoreIfTextContainsCount is the maximum number of ignore patterns per alert.
	MaxIgnoreIfTextContainsCount = 20

	// MaxFieldCount is the maximum number of fields per alert.
	MaxFieldCount = 20

	// MaxWebhookCount is the maximum number of webhooks per alert.
	MaxWebhookCount = 5
	// MaxWebhookIDLength is the maximum length of a webhook ID.
	MaxWebhookIDLength = 100
	// MaxWebhookURLLength is the maximum length of a webhook URL.
	MaxWebhookURLLength = 1000
	// MaxWebhookButtonTextLength is the maximum length of button text (Slack limit: 25 characters).
	MaxWebhookButtonTextLength = 25
	// MaxWebhookConfirmationTextLength is the maximum length of confirmation dialog text.
	MaxWebhookConfirmationTextLength = 1000
	// MaxWebhookPayloadCount is the maximum number of key-value pairs in webhook payload.
	MaxWebhookPayloadCount = 50
	// MaxWebhookPlainTextInputCount is the maximum number of text inputs per webhook.
	MaxWebhookPlainTextInputCount = 10
	// MaxWebhookCheckboxInputCount is the maximum number of checkbox groups per webhook.
	MaxWebhookCheckboxInputCount = 10
	// MaxWebhookInputIDLength is the maximum length of an input field ID.
	MaxWebhookInputIDLength = 200
	// MaxWebhookInputDescriptionLength is the maximum length of an input field description (label).
	MaxWebhookInputDescriptionLength = 200
	// MaxWebhookInputLabelLength is the maximum length of a checkbox group label.
	MaxWebhookInputLabelLength = 200
	// MaxWebhookInputTextLength is the maximum length of text input content.
	MaxWebhookInputTextLength = 3000
	// MaxWebhookCheckboxOptionCount is the maximum number of options per checkbox group.
	MaxWebhookCheckboxOptionCount = 5
	// MaxWebhookCheckboxOptionTextLength is the maximum length of checkbox option text.
	MaxWebhookCheckboxOptionTextLength = 50
	// MaxCheckboxOptionValueLength is the maximum length of a checkbox option value.
	MaxCheckboxOptionValueLength = 100

	// MaxEscalationCount is the maximum number of escalation points per alert.
	MaxEscalationCount = 3
	// MinEscalationDelaySeconds is the minimum delay before the first escalation triggers.
	MinEscalationDelaySeconds = 30
	// MinEscalationDelayDiffSeconds is the minimum time between consecutive escalations.
	MinEscalationDelayDiffSeconds = 30
	// MaxEscalationSlackMentionCount is the maximum number of Slack mentions per escalation.
	MaxEscalationSlackMentionCount = 10
)
View Source
const (
	// ScopeAlertsWrite allows sending alerts: POST /alerts (and its deprecated aliases) and POST /prometheus-alert.
	ScopeAlertsWrite = "alerts:write"

	// ScopeAlertsTest allows testing alerts with POST /alerts-test. Nothing is sent to Slack.
	ScopeAlertsTest = "alerts:test"

	// ScopeConfigRead allows reading the routing rules (GET /mappings) and the managed channels (GET /channels).
	ScopeConfigRead = "config:read"

	// ScopeAll grants all scopes.
	ScopeAll = "*"
)

Authorization scopes of the Slack Manager REST API. Each protected endpoint requires one scope. See Principal.HasScope.

View Source
const (
	// InsightsReasonNotNewer means the alert timestamp was not newer than the last alert of the issue (including redeliveries).
	InsightsReasonNotNewer = "not_newer"

	// InsightsReasonAlreadyResolved means a resolved alert arrived for an issue that was already resolved.
	InsightsReasonAlreadyResolved = "already_resolved"

	// InsightsReasonFollowUpDisabled means the alert matched a recent fire-and-forget notification, so it was ignored.
	InsightsReasonFollowUpDisabled = "follow_up_disabled"

	// InsightsReasonResolvedWithoutIssue means a resolved alert arrived while no open issue existed.
	InsightsReasonResolvedWithoutIssue = "resolved_without_issue"
)

Reasons used by InsightsEventAlertIgnored.

View Source
const (
	// InsightsReasonInvalid means the alert failed validation in the manager.
	InsightsReasonInvalid = "invalid"

	// InsightsReasonMissingEncryptionKey means the alert has webhooks but no encryption key is configured.
	InsightsReasonMissingEncryptionKey = "missing_encryption_key"

	// InsightsReasonCorruptIssue means the matching issue in the database could not be read.
	InsightsReasonCorruptIssue = "corrupt_issue"

	// InsightsReasonUnreadable means the queue message could not be unmarshalled.
	InsightsReasonUnreadable = "unreadable"
)

Reasons used by InsightsEventAlertDropped.

View Source
const (
	// InsightsReasonLockTimeout means the channel lock could not be obtained in time.
	InsightsReasonLockTimeout = "lock_timeout"

	// InsightsReasonGateTimeout means processing was interrupted while waiting for the Slack rate limit gate.
	InsightsReasonGateTimeout = "gate_timeout"

	// InsightsReasonSlackError means a Slack API call failed.
	InsightsReasonSlackError = "slack_error"

	// InsightsReasonDBError means a database call failed.
	InsightsReasonDBError = "db_error"

	// InsightsReasonMoveRace means the alert was routed to the wrong channel due to a concurrent issue move.
	InsightsReasonMoveRace = "move_race"
)

Reasons used by InsightsEventAlertRetried.

View Source
const (
	// InsightsReasonAlert means the transition was caused by an alert.
	InsightsReasonAlert = "alert"

	// InsightsReasonUser means the transition was caused by a user command.
	InsightsReasonUser = "user"

	// InsightsReasonEscalation means the issue was moved by an escalation rule.
	InsightsReasonEscalation = "escalation"
)

Reasons used by InsightsEventIssueResolved, InsightsEventIssueReopened and InsightsEventIssueMoved.

View Source
const (
	// InsightsReasonUserResolved means the issue was resolved by a user.
	InsightsReasonUserResolved = "user_resolved"

	// InsightsReasonAlertResolved means the issue was resolved by a resolved alert.
	InsightsReasonAlertResolved = "alert_resolved"

	// InsightsReasonAutoResolved means the issue was resolved by the auto-resolve timeout.
	InsightsReasonAutoResolved = "auto_resolved"

	// InsightsReasonAutoResolvedInconclusive means the issue was auto-resolved and flagged as inconclusive.
	InsightsReasonAutoResolvedInconclusive = "auto_resolved_inconclusive"

	// InsightsReasonTerminated means the issue was terminated by a user.
	InsightsReasonTerminated = "terminated"

	// InsightsReasonFireAndForget means the issue had follow-up disabled and was archived after its archiving delay.
	//
	// Deprecated: fire-and-forget notifications are not issues, and are no longer archived with an
	// [InsightsEventIssueArchived] event (see [InsightsEventAlertFireAndForget]). The reason only appears in events
	// recorded by older versions.
	InsightsReasonFireAndForget = "fire_and_forget"
)

Reasons used by InsightsEventIssueArchived, describing how the issue ended.

View Source
const (
	// InsightsReasonChannelUnavailable means the Slack channel was not found or is archived.
	InsightsReasonChannelUnavailable = "channel_unavailable"

	// InsightsReasonInvalidBlocks means Slack rejected the message formatting.
	InsightsReasonInvalidBlocks = "invalid_blocks"

	// InsightsReasonNotInChannel means the Slack app is not a member of the channel.
	InsightsReasonNotInChannel = "not_in_channel"

	// InsightsReasonMessageNotFound means the Slack post to update no longer exists, or cannot be updated.
	InsightsReasonMessageNotFound = "message_not_found"

	// InsightsReasonAPIError means any other Slack API error.
	InsightsReasonAPIError = "api_error"
)

Reasons used by InsightsEventSlackPostFailed.

View Source
const (
	// InsightsValueOpenSeconds is the time from issue creation to archiving, in seconds ([InsightsEventIssueArchived]).
	InsightsValueOpenSeconds = "open_s"

	// InsightsValueTimeToResolveSeconds is the time from issue creation to (last) resolution, in seconds ([InsightsEventIssueArchived]).
	InsightsValueTimeToResolveSeconds = "time_to_resolve_s"

	// InsightsValueTimeToFirstInvestigationSeconds is the time from issue creation to the first investigate command,
	// in seconds ([InsightsEventIssueArchived]). Absent if the issue was never investigated.
	InsightsValueTimeToFirstInvestigationSeconds = "time_to_first_investigation_s"

	// InsightsValueAlertCount is the total number of alerts in the issue ([InsightsEventIssueArchived]).
	InsightsValueAlertCount = "alert_count"

	// InsightsValueReopenCount is the number of times the issue was reopened ([InsightsEventIssueArchived]).
	InsightsValueReopenCount = "reopen_count"

	// InsightsValueNotified is 1 if an alert Slack post was ever sent for the issue, otherwise 0 ([InsightsEventIssueArchived]).
	InsightsValueNotified = "notified"

	// InsightsValueNotificationDelaySeconds is the configured notification delay of a new issue, in seconds ([InsightsEventIssueCreated]).
	InsightsValueNotificationDelaySeconds = "notification_delay_s"

	// InsightsValueOpen is the number of open (non-archived) issues ([InsightsEventChannelStats]). Fire-and-forget
	// notifications are not issues, and are not counted here or in any other channel stats value.
	InsightsValueOpen = "open"

	// InsightsValueAlerting is the number of open issues that are neither resolved nor info ([InsightsEventChannelStats]).
	InsightsValueAlerting = "alerting"

	// InsightsValueResolved is the number of open issues that are resolved but not yet archived ([InsightsEventChannelStats]).
	InsightsValueResolved = "resolved"

	// InsightsValueMuted is the number of muted open issues ([InsightsEventChannelStats]).
	InsightsValueMuted = "muted"

	// InsightsValueInvestigated is the number of open issues under investigation ([InsightsEventChannelStats]).
	InsightsValueInvestigated = "investigated"

	// InsightsValueEscalated is the number of escalated open issues ([InsightsEventChannelStats]).
	InsightsValueEscalated = "escalated"

	// InsightsValueLostEvents is the number of events lost since the previous gap event ([InsightsEventGap]).
	InsightsValueLostEvents = "lost_events"
)

Value keys used in InsightsEvent.Values.

View Source
const (
	// MaxInsightsQueryRange is the maximum time range of an insights query.
	MaxInsightsQueryRange = 366 * 24 * time.Hour

	// MinInsightsBucket is the minimum time bucket size.
	MinInsightsBucket = time.Minute

	// MaxInsightsBuckets is the maximum number of time buckets in a single query.
	MaxInsightsBuckets = 2000

	// MaxInsightsRows is the maximum number of rows returned by a count or stats query.
	MaxInsightsRows = 10000

	// MaxInsightsPageSize is the maximum number of events in a single page.
	MaxInsightsPageSize = 1000

	// DefaultInsightsPageSize is the page size used when [InsightsListQuery.Limit] is zero.
	DefaultInsightsPageSize = 100

	// MaxInsightsFilterValues is the maximum number of values in each list filter of [InsightsFilter].
	MaxInsightsFilterValues = 1000
)

Limits enforced by the Validate methods of the insights query types.

View Source
const (
	// MaxWebhookAfterClickStatusTextLength is the maximum length of [WebhookAfterClick.StatusText].
	MaxWebhookAfterClickStatusTextLength = 200

	// DefaultWebhookAfterClickResetSeconds is the reset delay used when [WebhookAfterClick.ResetAfterSeconds] is 0.
	DefaultWebhookAfterClickResetSeconds = 300

	// MaxWebhookAfterClickResetSeconds is the maximum value of [WebhookAfterClick.ResetAfterSeconds] (24 hours).
	MaxWebhookAfterClickResetSeconds = 86400
)

Webhook after-click limits.

View Source
const (
	// WebhookResultKey is the top-level JSON key of a [WebhookResponse]. A webhook response body is only treated as
	// a [WebhookResult] if it is a JSON object with this key.
	WebhookResultKey = "slackManagerResult"

	// MaxWebhookResultMessageLength is the maximum length of [WebhookResult.Message].
	MaxWebhookResultMessageLength = 1000
)
View Source
const InsightsMaxClientLen = MaxClientLength

InsightsMaxClientLen is the maximum length (in characters) of InsightsEvent.Client. Longer values are truncated by InsightsEvent.Normalize. Cleaned alerts never exceed it, but alerts rejected before cleaning may.

View Source
const InsightsMaxDetailLen = 200

InsightsMaxDetailLen is the maximum length of InsightsEvent.Detail. Longer values are truncated by InsightsEvent.Normalize.

View Source
const (
	// InsightsReasonIgnoreTerm means the alert text contained one of the alert's ignoreIfTextContains terms.
	InsightsReasonIgnoreTerm = "ignore_term"
)

Reasons used by InsightsEventAlertFiltered.

View Source
const UnknownClient = "unknown"

UnknownClient is the effective client of an alert with neither Client nor Username set (see Alert.EffectiveClient).

Variables

View Source
var (
	// SlackChannelIDOrNameRegex matches valid Slack channel IDs and channel names.
	// Channel names are mapped to channel IDs by the API.
	SlackChannelIDOrNameRegex = regexp.MustCompile(fmt.Sprintf(`^[0-9a-zA-Z\-_]{1,%d}$`, MaxSlackChannelIDLength))

	// IconRegex matches valid Slack icon emojis, on the format ':emoji:'.
	IconRegex = regexp.MustCompile(fmt.Sprintf(`^:[^:]{1,%d}:$`, MaxIconEmojiLength))

	// SlackMentionRegex matches valid Slack mentions, such as <!here>, <!channel> and <@U12345678>.
	SlackMentionRegex = regexp.MustCompile(fmt.Sprintf(`^((<!here>)|(<!channel>)|(<@[^>\s]{1,%d}>))$`, MaxMentionLength))
)
View Source
var (
	// ErrNoCredentials means that the request has no credentials that the authenticator understands. The API
	// responds with HTTP 401, or lets the request through anonymously in permissive mode.
	// [ChainAuthenticators] tries the next authenticator.
	ErrNoCredentials = errors.New("no credentials")

	// ErrInvalidCredentials means that the request has credentials, but they are invalid (unknown, expired,
	// malformed). The API responds with HTTP 401, also in permissive mode.
	ErrInvalidCredentials = errors.New("invalid credentials")

	// ErrForbidden means that the principal is authenticated, but not allowed to perform the action. The API
	// responds with HTTP 403.
	ErrForbidden = errors.New("forbidden")
)

Errors returned by Authenticator and Authorizer implementations. Return them (or wrap them) so that the API responds with the matching status code. Any other error is an internal error (HTTP 500): the request is rejected (fail closed).

View Source
var ErrInsightsNotSupported = errors.New("insights not supported by the database implementation")

ErrInsightsNotSupported is returned by insights readers and services when the underlying storage does not support insights.

View Source
var ErrInsightsTooManyRows = errors.New("insights query matches too many rows")

ErrInsightsTooManyRows is returned by count and stats queries without an explicit InsightsGrouping.Limit when more than MaxInsightsRows groups match. Narrow the time range or filter, use a larger bucket, or group by fewer dimensions.

Functions

func IsKnownScope added in v0.14.0

func IsKnownScope(scope string) bool

IsKnownScope reports whether scope is one of KnownScopes.

func KnownScopes added in v0.14.0

func KnownScopes() []string

KnownScopes returns all scopes of the REST API, including ScopeAll.

func SeverityIsValid

func SeverityIsValid(s AlertSeverity) bool

func SeverityPriority

func SeverityPriority(s AlertSeverity) int

func ValidSeverities

func ValidSeverities() []string

func ValidWebhookAccessLevels

func ValidWebhookAccessLevels() []string

ValidWebhookAccessLevels returns a slice of valid WebhookAccessLevel values.

func ValidWebhookButtonStyles

func ValidWebhookButtonStyles() []string

ValidWebhookButtonStyles returns a slice of valid WebhookButtonStyle values.

func ValidWebhookDisplayModes

func ValidWebhookDisplayModes() []string

ValidWebhookDisplayModes returns a slice of valid WebhookDisplayMode values.

func ValidWebhookHideButtons added in v0.9.0

func ValidWebhookHideButtons() []string

ValidWebhookHideButtons returns a slice of valid WebhookHideButtons values.

func WebhookAccessLevelIsValid

func WebhookAccessLevelIsValid(s WebhookAccessLevel) bool

WebhookAccessLevelIsValid returns true if the provided WebhookAccessLevel is valid.

func WebhookButtonStyleIsValid

func WebhookButtonStyleIsValid(s WebhookButtonStyle) bool

WebhookButtonStyleIsValid returns true if the provided WebhookButtonStyle is valid.

func WebhookDisplayModeIsValid

func WebhookDisplayModeIsValid(s WebhookDisplayMode) bool

WebhookDisplayModeIsValid returns true if the provided WebhookDisplayMode is valid.

func WebhookHideButtonsIsValid added in v0.9.0

func WebhookHideButtonsIsValid(s WebhookHideButtons) bool

WebhookHideButtonsIsValid returns true if the provided WebhookHideButtons is valid.

Types

type Alert

type Alert struct {
	// Timestamp is the time when the alert was created. If the timestamp is empty (or older than 7 days), it will be replaced with the current time.
	Timestamp time.Time `json:"timestamp,omitzero"`

	// CorrelationID is an optional field used to group related alerts together in issues.
	// If unset, the correlation ID is constructed by hashing [Header, Author, Host, Text, SlackChannelID].
	// It is strongly recommended to set this to an explicit value, which makes sense in your context, rather than relying on the default hash value.
	// With a custom correlation ID, you can update both header and text without creating a new issue.
	CorrelationID string `json:"correlationId,omitzero"`

	// Type is the type of alert, such as 'compliance', 'security' or 'metrics'.
	// It is primarily used for routing, when the alert RouteKey field is used (rather than SlackChannelID).
	// This field is optional, and case-insensitive.
	Type string `json:"type,omitzero"`

	// Header is the main header (title) of the alert.
	// It is automatically truncated at MaxHeaderLength characters.
	// Include :status: in the header (or text) to have it replaced with the appropriate emoji for the issue severity.
	// This field is optional, but Header and Text cannot both be empty.
	Header string `json:"header,omitzero"`

	// HeaderWhenResolved is the main header (title) of the issue when in a resolved or info state.
	// It is automatically truncated at MaxHeaderLength characters.
	// This field is optional. If unset, the Header field is used for all issue states.
	HeaderWhenResolved string `json:"headerWhenResolved,omitzero"`

	// Text is the main text (body) of the alert.
	// It is automatically truncated at MaxTextLength characters.
	// Include :status: in the text (or header) to have it replaced with the appropriate emoji for the issue severity.
	// This field is optional, but Header and Text cannot both be empty.
	Text string `json:"text,omitzero"`

	// TextWhenResolved is the main text (body) of the alert when in a resolved or info state.
	// It is automatically truncated at MaxTextLength characters.
	// This field is optional. If unset, the Text field is used for all issue states.
	TextWhenResolved string `json:"textWhenResolved,omitzero"`

	// FallbackText is the text displayed in Slack notifications.
	// It should be a short, human-readable summary of the alert, without markdown or line breaks.
	// It is automatically truncated at MaxFallbackTextLength characters.
	// This field is optional. If unset, Slack decides what to display in notifications (which may not always be ideal).
	FallbackText string `json:"fallbackText,omitzero"`

	// Author is the 'author' of the alert (if relevant), displayed as a context block in the Slack post.
	// It is automatically truncated at MaxAuthorLength characters.
	// This field is optional.
	Author string `json:"author,omitzero"`

	// Host is the 'host' on which the alert originated (if any), displayed as a context block in the Slack post.
	// It is automatically truncated at MaxHostLength characters.
	// This field is optional.
	Host string `json:"host,omitzero"`

	// Footer is the 'footer' of the alert, displayed as a context block at the bottom of the Slack post.
	// It is automatically truncated at MaxFooterLength characters.
	// This field is optional.
	Footer string `json:"footer,omitzero"`

	// Link is an optional link (url) to more information about the alert, displayed as a context block in the Slack post.
	// This field is optional, but if set, it must be a valid absolute URL, starting with http:// or https://
	Link string `json:"link,omitzero"`

	// IssueFollowUpEnabled controls whether the issue is tracked after the initial Slack post.
	// If true, the issue will be automatically resolved after AutoResolveSeconds seconds (or immediately if severity is 'resolved').
	// Users can also manually resolve, investigate, or mute the issue via Slack reactions.
	// If false, the alert is a fire-and-forget notification: a Slack post is created, but no issue is tracked. The post
	// cannot be resolved or investigated, and repeated alerts with the same correlation ID are ignored for approximately
	// 30 seconds. Fire-and-forget notifications are never counted as open, alerting, resolved or archived issues.
	// Note: if true and severity is 'info', follow-up is silently disabled (info alerts are inherently fire-and-forget).
	IssueFollowUpEnabled bool `json:"issueFollowUpEnabled,omitzero"`

	// AutoResolveSeconds is the number of seconds after which the issue should be automatically resolved, if IssueFollowUpEnabled is true.
	// The value must be between MinAutoResolveSeconds and MaxAutoResolveSeconds.
	AutoResolveSeconds int `json:"autoResolveSeconds,omitzero"`

	// AutoResolveAsInconclusive is a flag that determines if the issue should be automatically resolved as 'inconclusive' instead of 'resolved'.
	// This affects which emoji is used in the Slack post when the issue is auto-resolved.
	// It has no effect if the issue was manually resolved via a Slack reaction, or if severity is 'resolved' or 'info'.
	// The default value is false, which means the issue is resolved with status 'resolved'.
	AutoResolveAsInconclusive bool `json:"autoResolveAsInconclusive,omitzero"`

	// Severity is the severity of the alert, such as 'panic', 'error', 'warning', 'resolved' or 'info'.
	// This value determines the emoji used in the Slack post (for the :status: placeholder in header or text).
	// The value must be one of the predefined AlertSeverity constants.
	// If unset, the severity is automatically set to 'error'.
	Severity AlertSeverity `json:"severity,omitzero"`

	// SlackChannelID is the ID of the Slack channel where the alert should be posted.
	// Slack channel names are also accepted, and are automatically converted to channel IDs by the API.
	// The value must be an existing channel ID or name, and the Slack Manager integration must have been added to the channel.
	// This field is optional.
	// If both SlackChannelID and RouteKey are set, SlackChannelID takes precedence.
	// If both SlackChannelID and RouteKey are empty, the API will still accept the alert IF a fallback mapping exists. Otherwise, it will return an error.
	SlackChannelID string `json:"slackChannelId,omitzero"`

	// RouteKey is the case-insensitive route key of the alert, used for routing to the correct Slack channel by the API.
	// The API will return an error if the route key does not match any configured route.
	// This field is optional.
	// If both SlackChannelID and RouteKey are set, SlackChannelID takes precedence.
	// If both SlackChannelID and RouteKey are empty, the API will still accept the alert IF a fallback mapping exists. Otherwise, it will return an error.
	RouteKey string `json:"routeKey,omitzero"`

	// Username is the username that the alert should be posted as in Slack.
	// This field is optional. If omitted, the alert is posted as the default bot user.
	Username string `json:"username,omitzero"`

	// Client is an OPTIONAL identifier of the client (monitoring tool or integration) that produced the alert,
	// such as 'prometheus', 'grafana' or 'my-batch-job'. The value is free form.
	// It is used only for grouping, filtering and reporting (insights and dashboards), and never for routing
	// or Slack rendering.
	// It is automatically trimmed and truncated at MaxClientLength characters.
	// When empty, the effective client is Username, and then [UnknownClient] (see [Alert.EffectiveClient]).
	Client string `json:"client,omitzero"`

	// IconEmoji is the emoji that the alert should be posted with in Slack, on the format ':emoji:'.
	IconEmoji string `json:"iconEmoji,omitzero"`

	// Fields are rendered in a compact format that allows for 2 columns of side-by-side text.
	Fields []*Field `json:"fields,omitzero"`

	// NotificationDelaySeconds is the number of seconds to wait before creating an actual Slack post.
	// If the issue is resolved before the delay is over, no Slack post is created for the issue.
	// This is useful for issues that may be resolved quickly, to avoid unnecessary notifications.
	// This field only takes effect when IssueFollowUpEnabled is true.
	NotificationDelaySeconds int `json:"notificationDelaySeconds,omitzero"`

	// ArchivingDelaySeconds is the number of seconds to wait before archiving the issue, after it is resolved.
	// A non-archived issue is re-opened if a new alert with the same CorrelationID is received, and the same Slack post is updated.
	// An archived issue can never be re-opened, and any new alerts with the same CorrelationID will generate a new issue and new Slack post.
	ArchivingDelaySeconds int `json:"archivingDelaySeconds,omitzero"`

	// Escalation defines a list of escalation points for this alert's issue.
	// Each escalation can increase severity, add Slack mentions, or move the issue to a different channel after a specified delay.
	// Escalations are sorted by DelaySeconds and triggered in order if the issue remains unresolved.
	// Maximum of MaxEscalationCount escalations allowed.
	Escalation []*Escalation `json:"escalation,omitzero"`

	// IgnoreIfTextContains is a list of substrings that, if found in the alert's Text field, will cause the alert to be dropped.
	// Matching is case-insensitive. Only the Text field is checked; Header and other fields are not.
	// This is useful for filtering out known noise or false positives.
	// Maximum of MaxIgnoreIfTextContainsCount items, each up to MaxIgnoreIfTextContainsLength characters.
	IgnoreIfTextContains []string `json:"ignoreIfTextContains,omitzero"`

	// Webhooks defines interactive buttons that appear on the Slack post.
	// Each webhook triggers an HTTP POST to the specified URL when clicked.
	// Webhooks can include confirmation dialogs, input forms, and access level restrictions.
	// Maximum of MaxWebhookCount webhooks allowed.
	Webhooks []*Webhook `json:"webhooks,omitzero"`

	// Metadata is an arbitrary key-value map for storing custom data with the alert.
	// The Slack Manager does not interpret this data.
	Metadata map[string]any `json:"metadata,omitzero"`

	// Deprecated: FailOnRateLimitError is no longer in use.
	FailOnRateLimitError bool `json:"failOnRateLimitError,omitzero"`

	// Deprecated: DeletionDelaySeconds is a legacy alias for ArchivingDelaySeconds, kept for
	// compatibility with older clients. It is ignored unless the manager runs with legacy
	// features enabled, in which case it is used when ArchivingDelaySeconds is not set.
	// Use ArchivingDelaySeconds instead.
	DeletionDelaySeconds int `json:"deletionDelaySeconds,omitzero"`
}

Alert represents a single alert that can be sent to the Slack Manager. Alerts with the same CorrelationID are grouped together in issues by the Slack Manager.

func NewAlert

func NewAlert(severity AlertSeverity) *Alert

NewAlert returns an alert with the specified severity

func NewErrorAlert

func NewErrorAlert() *Alert

NewErrorAlert returns an alert with the severity set to 'error'

func NewInfoAlert

func NewInfoAlert() *Alert

NewInfoAlert returns an alert with the severity set to 'info'

func NewPanicAlert

func NewPanicAlert() *Alert

NewPanicAlert returns an alert with the severity set to 'panic'

func NewResolvedAlert

func NewResolvedAlert() *Alert

NewResolvedAlert returns an alert with the severity set to 'resolved'

func NewWarningAlert

func NewWarningAlert() *Alert

NewWarningAlert returns an alert with the severity set to 'warning'

func (*Alert) Clean

func (a *Alert) Clean()

Clean normalizes and sanitizes all alert fields. It trims whitespace, normalizes case where appropriate, truncates certain fields that exceed maximum lengths, and applies default values for empty or invalid fields (e.g., sets Severity to 'error' if empty). This method should be called before validation to ensure consistent data.

func (*Alert) EffectiveClient added in v0.11.0

func (a *Alert) EffectiveClient() string

EffectiveClient returns the client that produced the alert, for grouping, filtering and reporting. It returns the first non-empty value, in this order:

  1. the trimmed Alert.Client
  2. the trimmed Alert.Username
  3. UnknownClient

func (*Alert) UniqueID

func (a *Alert) UniqueID() string

UniqueID returns a unique and deterministic ID for this alert, for database/storage purposes. The ID is based on certain fields of the alert, and is base64 encoded to ensure it is safe for use in URLs and as a database key.

func (*Alert) Validate

func (a *Alert) Validate() error

Validate returns an error if one or more of the required fields are empty or invalid

func (*Alert) ValidateAutoResolve

func (a *Alert) ValidateAutoResolve() error

ValidateAutoResolve validates that AutoResolveSeconds is within the allowed range when IssueFollowUpEnabled is true.

func (*Alert) ValidateCorrelationID

func (a *Alert) ValidateCorrelationID() error

ValidateCorrelationID validates that CorrelationID, if set, does not exceed MaxCorrelationIDLength.

func (*Alert) ValidateEscalation

func (a *Alert) ValidateEscalation() error

ValidateEscalation validates all escalation points in the alert. It checks that the escalation count is within limits, delays are properly spaced, severities are valid for escalation, and Slack mentions and channels are valid.

func (*Alert) ValidateFields

func (a *Alert) ValidateFields() error

ValidateFields validates that the number of fields does not exceed MaxFieldCount.

func (*Alert) ValidateHeaderAndText

func (a *Alert) ValidateHeaderAndText() error

ValidateHeaderAndText validates that at least one of Header or Text is non-empty. An alert must have either a header or text content to be meaningful.

func (*Alert) ValidateIcon

func (a *Alert) ValidateIcon() error

ValidateIcon validates that IconEmoji, if set, matches the expected Slack emoji format ':emoji:'.

func (*Alert) ValidateIgnoreIfTextContains

func (a *Alert) ValidateIgnoreIfTextContains() error

ValidateIgnoreIfTextContains validates that the IgnoreIfTextContains slice does not exceed the maximum count and that each item does not exceed the maximum length.

func (a *Alert) ValidateLink() error

ValidateLink validates that Link, if set, is a valid absolute URL with a scheme.

func (*Alert) ValidateSeverity

func (a *Alert) ValidateSeverity() error

ValidateSeverity validates that Severity is one of the allowed AlertSeverity values.

func (*Alert) ValidateSlackChannelIDAndRouteKey

func (a *Alert) ValidateSlackChannelIDAndRouteKey() error

ValidateSlackChannelIDAndRouteKey validates that SlackChannelID and RouteKey are valid, if set. Both values are allowed to be empty (in which case a fallback mapping must exist in the API).

func (*Alert) ValidateWebhooks

func (a *Alert) ValidateWebhooks() error

ValidateWebhooks validates all webhooks in the alert. It checks that the webhook count is within limits, all required fields are present, URLs are valid, IDs are unique, and all nested inputs are properly configured.

type AlertSeverity

type AlertSeverity string

AlertSeverity represents the severity for a given alert

const (
	// AlertPanic is used for panic situations (panic icon in Slack).
	AlertPanic AlertSeverity = "panic"

	// AlertError is used for error (critical) situations (red error icon in Slack).
	// Alerts with severity 'critical' are automatically converted to 'error'.
	AlertError AlertSeverity = "error"

	// AlertWarning is used for warning situations (yellow warning icon in Slack).
	AlertWarning AlertSeverity = "warning"

	// AlertResolved is used when a previous panic/error/warning situation has been resolved (and IssueFollowUpEnabled is true).
	// The previous icon is replaced with a green OK icon.
	// Not to be confused with an info alert!
	AlertResolved AlertSeverity = "resolved"

	// AlertInfo is used for pure info situations (blue info icon in Slack).
	// Typically used for fire-and-forget status messages, where IssueFollowUpEnabled is false.
	// Not to be confused with a resolved alert!
	AlertInfo AlertSeverity = "info"
)

type Authenticator added in v0.14.0

type Authenticator interface {
	Authenticate(r *http.Request) (*Principal, error)
}

Authenticator identifies the caller of an HTTP request.

Authenticate returns the Principal of the request, or an error: ErrNoCredentials if the request has no credentials of the kind the authenticator handles, ErrInvalidCredentials if they are invalid, or any other error for internal failures (e.g. an unreachable identity provider). It must not read the request body. It is called concurrently and must be safe for concurrent use.

type AuthenticatorFunc added in v0.14.0

type AuthenticatorFunc func(r *http.Request) (*Principal, error)

AuthenticatorFunc is a function that implements Authenticator.

func ChainAuthenticators added in v0.14.0

func ChainAuthenticators(authenticators ...Authenticator) AuthenticatorFunc

ChainAuthenticators returns an Authenticator (as an AuthenticatorFunc) that tries the given authenticators in order, and returns the first principal found. Nil authenticators are skipped.

If no authenticator succeeds, it returns the most significant error: an internal error (the first one) over ErrInvalidCredentials over ErrNoCredentials. This lets authenticators of different kinds (e.g. API keys and OIDC tokens, which are both bearer tokens) share a request header.

func (AuthenticatorFunc) Authenticate added in v0.14.0

func (f AuthenticatorFunc) Authenticate(r *http.Request) (*Principal, error)

Authenticate calls f(r).

type Authorizer added in v0.14.0

type Authorizer interface {
	Authorize(ctx context.Context, principal *Principal, scope string) error
}

Authorizer decides whether an authenticated Principal may perform an action that requires the given scope (e.g. ScopeAlertsWrite).

Authorize returns nil if the action is allowed, ErrForbidden if it is not, or any other error for internal failures (e.g. an unreachable policy service). It is called concurrently and must be safe for concurrent use.

type AuthorizerFunc added in v0.14.0

type AuthorizerFunc func(ctx context.Context, principal *Principal, scope string) error

AuthorizerFunc is a function that implements Authorizer.

func (AuthorizerFunc) Authorize added in v0.14.0

func (f AuthorizerFunc) Authorize(ctx context.Context, principal *Principal, scope string) error

Authorize calls f(ctx, principal, scope).

type ChannelAuthorizer added in v0.15.0

type ChannelAuthorizer interface {
	AuthorizeChannel(ctx context.Context, principal *Principal, channelID string) error
}

ChannelAuthorizer decides whether an authenticated Principal may send alerts to a Slack channel. It is an optional extension of Authorizer: when the configured authorizer also implements ChannelAuthorizer, the REST API calls it for the channel of each alert, and for the channels that escalations may move the issue to. Otherwise, the API uses its built-in channel access rules.

channelID is the upper-cased channel ID after routing (or an upper-cased channel name that could not be mapped to an ID). AuthorizeChannel returns nil if the channel is allowed, ErrForbidden if it is not, or any other error for internal failures. It is called concurrently and must be safe for concurrent use.

type ChannelAuthorizerFunc added in v0.15.0

type ChannelAuthorizerFunc func(ctx context.Context, principal *Principal, channelID string) error

ChannelAuthorizerFunc is a function that implements ChannelAuthorizer.

func (ChannelAuthorizerFunc) AuthorizeChannel added in v0.15.0

func (f ChannelAuthorizerFunc) AuthorizeChannel(ctx context.Context, principal *Principal, channelID string) error

AuthorizeChannel calls f(ctx, principal, channelID).

type ChannelProcessingState

type ChannelProcessingState struct {
	ChannelID           string    `json:"channelId"`
	Created             time.Time `json:"created"`
	LastChannelActivity time.Time `json:"lastChannelActivity"`
	LastProcessed       time.Time `json:"lastProcessed"`
	// OpenIssues is the number of open issues in the channel at the last processing run, before archiving.
	// Fire-and-forget notifications are not issues, and are not counted.
	OpenIssues int `json:"openIssues"`
}

ChannelProcessingState represents the state of processing for a specific Slack channel, used internally by the Slack Manager. It tracks when the processing started and when it was last processed. This is used to prevent multiple instances of the Slack Manager from processing the same channel at the same time, and to ensure that processing is done at regular intervals.

func NewChannelProcessingState

func NewChannelProcessingState(channelID string) *ChannelProcessingState

type DB

type DB interface {
	// Init initializes the database, for example by creating necessary tables or collections.
	// Set skipSchemaValidation to true to skip schema validation.
	Init(ctx context.Context, skipSchemaValidation bool) error

	// SaveAlert saves an alert to the database (for auditing purposes).
	// The same alert may be saved multiple times, in case of errors and retries.
	//
	// A database implementation can choose to skip saving the alerts, since they are never read by the manager.
	SaveAlert(ctx context.Context, alert *Alert) error

	// SaveIssue creates or updates a single issue in the database.
	SaveIssue(ctx context.Context, issue Issue) error

	// SaveIssues creates or updates multiple issues in the database.
	SaveIssues(ctx context.Context, issues ...Issue) error

	// MoveIssue moves an issue from one channel to another.
	// This channel ID in the issue must match the targetChannelID.
	// The sourceChannelID is used to find the existing issue in the database.
	MoveIssue(ctx context.Context, issue Issue, sourceChannelID, targetChannelID string) error

	// FindOpenIssueByCorrelationID finds a single open issue in the database, based on the provided channel ID and correlation ID.
	//
	// The database implementation should return an error if the query matches multiple issues, and [nil, nil] if no issue is found.
	FindOpenIssueByCorrelationID(ctx context.Context, channelID, correlationID string) (string, json.RawMessage, error)

	// FindIssueBySlackPostID finds a single issue in the database, based on the provided channel ID and Slack post ID.
	//
	// The database implementation should return an error if the query matches multiple issues, and [nil, nil] if no issue is found.
	FindIssueBySlackPostID(ctx context.Context, channelID, postID string) (string, json.RawMessage, error)

	// FindActiveChannels returns a list of all active channels in the database.
	// An active channel is one that has at least one open issue.
	// The returned list may be empty if no active channels are found.
	FindActiveChannels(ctx context.Context) ([]string, error)

	// LoadOpenIssuesInChannel loads all open (non-archived) issues from the database, for the specified channel ID.
	// The returned list may be empty if no open issues are found in the channel.
	LoadOpenIssuesInChannel(ctx context.Context, channelID string) (map[string]json.RawMessage, error)

	// SaveMoveMapping creates or updates a single move mapping in the database.
	SaveMoveMapping(ctx context.Context, moveMapping MoveMapping) error

	// FindMoveMapping finds a single move mapping in the database, for the specified channel ID and correlation ID.
	//
	// The database implementation should return an error if the query matches multiple mappings, and [nil, nil] if no mapping is found.
	FindMoveMapping(ctx context.Context, channelID, correlationID string) (json.RawMessage, error)

	// DeleteMoveMapping deletes a single move mapping from the database, for the specified channel ID and correlation ID.
	DeleteMoveMapping(ctx context.Context, channelID, correlationID string) error

	// SaveChannelProcessingState creates or updates a single channel processing state in the database.
	SaveChannelProcessingState(ctx context.Context, state *ChannelProcessingState) error

	// FindChannelProcessingState finds a single channel processing state in the database, for the specified channel ID.
	//
	// The database implementation should return an error if the query matches multiple states, and [nil, nil] if no state is found.
	FindChannelProcessingState(ctx context.Context, channelID string) (*ChannelProcessingState, error)

	// DropAllData drops *all* data from the database.
	// This is useful for testing purposes, to reset the database state.
	// It should be used with caution, as it will remove all alerts, issues, move mappings, and processing states.
	DropAllData(ctx context.Context) error
}

DB is an interface for interacting with the database. It must be implemented by any database driver used by the Slack Manager.

type Escalation

type Escalation struct {
	// Severity is the new severity of the issue, when the escalation is triggered.
	Severity AlertSeverity `json:"severity,omitzero"`

	// DelaySeconds is the number of seconds since the issue was created (first alert received),
	// before the escalation is triggered.
	DelaySeconds int `json:"delaySeconds,omitzero"`

	// SlackMentions is a list of Slack mentions that should be added to the Slack post when the escalation is triggered.
	SlackMentions []string `json:"slackMentions,omitzero"`

	// MoveToChannel is the ID or name of the Slack channel where the alert should be moved when the escalation is triggered.
	MoveToChannel string `json:"moveToChannel,omitzero"`
}

Escalation represents an escalation point for an issue.

type Field

type Field struct {
	// Title is the title of the field. It is automatically truncated at MaxFieldTitleLength characters.
	Title string `json:"title,omitzero"`

	// Value is the value of the field. It is automatically truncated at MaxFieldValueLength characters.
	Value string `json:"value,omitzero"`
}

Field is an alert field.

type FifoQueueItem

type FifoQueueItem struct {
	// MessageID is the unique identifier of the message (as defined by the queue implementation).
	MessageID string

	// SlackChannelID is the ID of the Slack channel to which the message is related.
	SlackChannelID string

	// ReceiveTimestamp is the time when the message was received from the queue.
	ReceiveTimestamp time.Time

	// Body is the body of the message.
	Body string

	// Ack acknowledges the successful processing of the message, effectively removing it from the queue.
	// This function cannot be nil.
	//
	// Ack does not accept a context parameter because acknowledgment is a commitment that must complete
	// regardless of the caller's context state. Each queue implementation is responsible for managing
	// its own timeouts and retry logic internally.
	Ack func()

	// Nack negatively acknowledges the processing of the message, thus making it available for reprocessing.
	// This function cannot be nil.
	//
	// Nack does not accept a context parameter because negative acknowledgment is a commitment that must
	// complete regardless of the caller's context state. Each queue implementation is responsible for
	// managing its own timeouts and retry logic internally.
	Nack func()
}

FifoQueueItem represents an item received from a FIFO queue.

type InMemoryDB added in v0.3.1

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

InMemoryDB is an in-memory implementation of the DB interface. For TEST purposes only! Do not use in production!

func NewInMemoryDB added in v0.3.1

func NewInMemoryDB() *InMemoryDB

NewInMemoryDB creates a new InMemoryDB instance. For TEST purposes only! Do not use in production!

func (*InMemoryDB) DeleteMoveMapping added in v0.3.1

func (db *InMemoryDB) DeleteMoveMapping(_ context.Context, channelID, correlationID string) error

DeleteMoveMapping deletes a move mapping. No error is returned if the mapping does not exist.

func (*InMemoryDB) DropAllData added in v0.3.1

func (db *InMemoryDB) DropAllData(_ context.Context) error

DropAllData clears all data from the in-memory store.

func (*InMemoryDB) FindActiveChannels added in v0.3.1

func (db *InMemoryDB) FindActiveChannels(_ context.Context) ([]string, error)

FindActiveChannels returns a list of all channels that have at least one open issue.

func (*InMemoryDB) FindChannelProcessingState added in v0.3.1

func (db *InMemoryDB) FindChannelProcessingState(_ context.Context, channelID string) (*ChannelProcessingState, error)

FindChannelProcessingState finds a channel processing state by channel ID. Returns nil without an error if no state is found.

func (*InMemoryDB) FindIssueBySlackPostID added in v0.3.1

func (db *InMemoryDB) FindIssueBySlackPostID(_ context.Context, channelID, postID string) (string, json.RawMessage, error)

FindIssueBySlackPostID finds a single issue by channel ID and Slack post ID. Returns an error if channelID or postID are empty.

func (*InMemoryDB) FindMoveMapping added in v0.3.1

func (db *InMemoryDB) FindMoveMapping(_ context.Context, channelID, correlationID string) (json.RawMessage, error)

FindMoveMapping finds a move mapping by channel ID and correlation ID. Returns an error if channelID or correlationID are empty.

func (*InMemoryDB) FindOpenIssueByCorrelationID added in v0.3.1

func (db *InMemoryDB) FindOpenIssueByCorrelationID(_ context.Context, channelID, correlationID string) (string, json.RawMessage, error)

FindOpenIssueByCorrelationID finds a single open issue by channel ID and correlation ID. Returns an error if channelID or correlationID are empty, or if multiple open issues match.

func (*InMemoryDB) Init added in v0.3.1

func (db *InMemoryDB) Init(_ context.Context, _ bool) error

Init is a no-op for the in-memory implementation.

func (*InMemoryDB) LoadOpenIssuesInChannel added in v0.3.1

func (db *InMemoryDB) LoadOpenIssuesInChannel(_ context.Context, channelID string) (map[string]json.RawMessage, error)

LoadOpenIssuesInChannel loads all open issues for the specified channel.

func (*InMemoryDB) MoveIssue added in v0.3.1

func (db *InMemoryDB) MoveIssue(_ context.Context, issue Issue, sourceChannelID, targetChannelID string) error

MoveIssue moves an issue from one channel to another. Returns an error if sourceChannelID and targetChannelID are the same. If the issue does not exist in the store, this is a no-op.

func (*InMemoryDB) SaveAlert added in v0.3.1

func (db *InMemoryDB) SaveAlert(_ context.Context, alert *Alert) error

SaveAlert saves an alert to the in-memory store.

func (*InMemoryDB) SaveChannelProcessingState added in v0.3.1

func (db *InMemoryDB) SaveChannelProcessingState(_ context.Context, state *ChannelProcessingState) error

SaveChannelProcessingState creates or updates a channel processing state.

func (*InMemoryDB) SaveIssue added in v0.3.1

func (db *InMemoryDB) SaveIssue(_ context.Context, issue Issue) error

SaveIssue creates or updates a single issue.

func (*InMemoryDB) SaveIssues added in v0.3.1

func (db *InMemoryDB) SaveIssues(ctx context.Context, issues ...Issue) error

SaveIssues creates or updates multiple issues.

func (*InMemoryDB) SaveMoveMapping added in v0.3.1

func (db *InMemoryDB) SaveMoveMapping(_ context.Context, moveMapping MoveMapping) error

SaveMoveMapping creates or updates a move mapping.

type InMemoryFifoQueue

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

InMemoryFifoQueue is an in-memory FIFO queue implementation For TEST purposes only! Do not use in production!

func NewInMemoryFifoQueue

func NewInMemoryFifoQueue(name string, bufferSize int, writeTimeout time.Duration) *InMemoryFifoQueue

NewInMemoryFifoQueue creates a new InMemoryFifoQueue instance. name is the name of the queue (for logging purposes only). bufferSize is the maximum number of items that can be stored in the queue. writeTimeout is the maximum time to wait for writing an item to the queue.

For TEST purposes only! Do not use in production!

func (*InMemoryFifoQueue) Name

func (q *InMemoryFifoQueue) Name() string

Name returns the name of the queue.

func (*InMemoryFifoQueue) Receive

func (q *InMemoryFifoQueue) Receive(ctx context.Context, sinkCh chan<- *FifoQueueItem) error

Receive receives messages from the queue, to the specified sink channel. An error is returned if the context is canceled. The sink channel is closed when the function returns.

func (*InMemoryFifoQueue) Send

func (q *InMemoryFifoQueue) Send(ctx context.Context, slackChannelID, _, body string) error

Send sends a message to the queue. An error is returned if the context is canceled or the write timeout is reached.

type InsightsAggregate added in v0.8.0

type InsightsAggregate string

InsightsAggregate is an aggregate function computed by InsightsReader.InsightsValueStats.

const (
	// InsightsAggregateSum is the sum of the values.
	InsightsAggregateSum InsightsAggregate = "sum"

	// InsightsAggregateAvg is the arithmetic mean of the values.
	InsightsAggregateAvg InsightsAggregate = "avg"

	// InsightsAggregateMin is the smallest value.
	InsightsAggregateMin InsightsAggregate = "min"

	// InsightsAggregateMax is the largest value.
	InsightsAggregateMax InsightsAggregate = "max"

	// InsightsAggregateP50 is the median (continuous percentile).
	InsightsAggregateP50 InsightsAggregate = "p50"

	// InsightsAggregateP90 is the 90th percentile (continuous percentile).
	InsightsAggregateP90 InsightsAggregate = "p90"

	// InsightsAggregateP99 is the 99th percentile (continuous percentile).
	InsightsAggregateP99 InsightsAggregate = "p99"
)

Supported insights aggregates.

func (InsightsAggregate) IsValid added in v0.8.0

func (a InsightsAggregate) IsValid() bool

IsValid returns true if a is a supported aggregate.

type InsightsCountQuery added in v0.8.0

type InsightsCountQuery struct {
	InsightsFilter
	InsightsGrouping

	// Distinct, if set, counts distinct non-empty values of this dimension instead of events
	// (e.g. distinct issues). [InsightsDimensionBucket] is not allowed.
	Distinct InsightsDimension

	// OrderByCountDesc orders rows by count, highest first (for top-N queries). Otherwise rows are ordered by the group keys.
	OrderByCountDesc bool
}

InsightsCountQuery counts events, optionally grouped. See InsightsReader.CountInsightsEvents.

func (*InsightsCountQuery) Validate added in v0.8.0

func (q *InsightsCountQuery) Validate() error

Validate returns an error if the query is invalid.

type InsightsCountRow added in v0.8.0

type InsightsCountRow struct {
	InsightsGroupKey

	// Count is the number of matching events (or distinct values, see [InsightsCountQuery.Distinct]).
	Count int64 `json:"count"`
}

InsightsCountRow is a row returned by InsightsReader.CountInsightsEvents.

type InsightsDimension added in v0.8.0

type InsightsDimension string

InsightsDimension is an event attribute that insights queries can group by.

const (
	// InsightsDimensionBucket groups by time bucket (the start of the bucket). Requires a bucket size in the query.
	InsightsDimensionBucket InsightsDimension = "bucket"

	// InsightsDimensionChannel groups by [InsightsEvent.ChannelID].
	InsightsDimensionChannel InsightsDimension = "channel"

	// InsightsDimensionRelatedChannel groups by [InsightsEvent.RelatedChannelID].
	InsightsDimensionRelatedChannel InsightsDimension = "related_channel"

	// InsightsDimensionType groups by [InsightsEvent.Type].
	InsightsDimensionType InsightsDimension = "type"

	// InsightsDimensionReason groups by [InsightsEvent.Reason].
	InsightsDimensionReason InsightsDimension = "reason"

	// InsightsDimensionSeverity groups by [InsightsEvent.Severity].
	InsightsDimensionSeverity InsightsDimension = "severity"

	// InsightsDimensionRouteKey groups by [InsightsEvent.RouteKey].
	InsightsDimensionRouteKey InsightsDimension = "route_key"

	// InsightsDimensionAlertType groups by [InsightsEvent.AlertType].
	InsightsDimensionAlertType InsightsDimension = "alert_type"

	// InsightsDimensionHost groups by [InsightsEvent.Host].
	InsightsDimensionHost InsightsDimension = "host"

	// InsightsDimensionAuthor groups by [InsightsEvent.Author].
	InsightsDimensionAuthor InsightsDimension = "author"

	// InsightsDimensionClient groups by [InsightsEvent.Client].
	InsightsDimensionClient InsightsDimension = "client"

	// InsightsDimensionActor groups by [InsightsEvent.ActorID].
	InsightsDimensionActor InsightsDimension = "actor"

	// InsightsDimensionCorrelationID groups by [InsightsEvent.CorrelationID].
	InsightsDimensionCorrelationID InsightsDimension = "correlation_id"

	// InsightsDimensionIssue groups by [InsightsEvent.IssueID].
	InsightsDimensionIssue InsightsDimension = "issue"
)

Supported insights dimensions.

func (InsightsDimension) IsValid added in v0.8.0

func (d InsightsDimension) IsValid() bool

IsValid returns true if d is a supported dimension.

type InsightsEvent added in v0.8.0

type InsightsEvent struct {
	// Time is when the event happened. Recorders set it to the current time if it is zero.
	Time time.Time `json:"time"`

	// Type identifies what the event describes.
	Type InsightsEventType `json:"type"`

	// Reason is an optional sub-classification. The possible values depend on Type.
	Reason string `json:"reason,omitempty"`

	// ChannelID is the Slack channel where the event happened. It may be empty for API rejections before routing,
	// and for API intake events whose channel is not a channel ID (see [InsightsEventAlertRejected]).
	ChannelID string `json:"channelId,omitempty"`

	// RelatedChannelID is a second channel involved in the event, e.g. the target channel of a move,
	// or the original channel of an alert that was redirected by a move mapping.
	RelatedChannelID string `json:"relatedChannelId,omitempty"`

	// IssueID is the unique ID of the issue the event relates to.
	IssueID string `json:"issueId,omitempty"`

	// CorrelationID is the correlation ID of the alert or issue.
	CorrelationID string `json:"correlationId,omitempty"`

	// Severity is the alert or issue severity after the event.
	Severity AlertSeverity `json:"severity,omitempty"`

	// PrevSeverity is the issue severity before the event, for events that change severity.
	PrevSeverity AlertSeverity `json:"prevSeverity,omitempty"`

	// RouteKey is the route key of the alert.
	RouteKey string `json:"routeKey,omitempty"`

	// AlertType is the alert type.
	AlertType string `json:"alertType,omitempty"`

	// Host is the alert host.
	Host string `json:"host,omitempty"`

	// Author is the alert author.
	Author string `json:"author,omitempty"`

	// Client is the effective client of the alert, or of the last alert of the issue (see [Alert.EffectiveClient]).
	// It is empty for events that do not relate to an alert or issue. At most [InsightsMaxClientLen] characters.
	Client string `json:"client,omitempty"`

	// ActorID is the Slack user ID of the user who caused the event (commands).
	ActorID string `json:"actorId,omitempty"`

	// ActorName is the real name of the user who caused the event (commands).
	ActorName string `json:"actorName,omitempty"`

	// Count is an event-specific count, e.g. the issue alert count at the time of the event.
	Count int `json:"count,omitempty"`

	// Detail is a short, event-specific free text (at most [InsightsMaxDetailLen] characters).
	Detail string `json:"detail,omitempty"`

	// Values holds event-specific numeric facts, keyed by the InsightsValue* constants. It is only used on
	// low-frequency events, to keep the cost of recording high-frequency events minimal.
	Values map[string]float64 `json:"values,omitempty"`
}

InsightsEvent is a structured record of something the Slack Manager did, used for dashboards and reporting.

Events carry identifiers and classifications only, never alert content such as headers, texts or fields. Only Time and Type are required; all other fields are optional and empty when not applicable.

func (*InsightsEvent) Normalize added in v0.8.0

func (e *InsightsEvent) Normalize(now time.Time)

Normalize prepares the event for storage: it sets Time to now (in UTC) if zero, converts Time to UTC, truncates Detail to InsightsMaxDetailLen bytes and Client to InsightsMaxClientLen characters, without splitting multi-byte characters. It is called by recorders before writing.

type InsightsEventPage added in v0.8.0

type InsightsEventPage struct {
	// Events holds the events in the page.
	Events []*InsightsEvent `json:"events"`

	// NextCursor continues the listing. It is empty when there are no more events.
	NextCursor string `json:"nextCursor,omitempty"`
}

InsightsEventPage is a page of events returned by InsightsReader.ListInsightsEvents.

type InsightsEventType added in v0.8.0

type InsightsEventType string

InsightsEventType identifies what an InsightsEvent describes.

Types are namespaced by subject ("alert.", "issue.", "command.", "webhook.", "slack.", "channel.", "insights."). New types may be added in minor releases, so consumers should tolerate unknown types.

const (
	// InsightsEventAlertNewIssue means the alert finished processing (acked as successful) and opened a new issue.
	InsightsEventAlertNewIssue InsightsEventType = "alert.new_issue"

	// InsightsEventAlertFireAndForget means the alert finished processing and created a fire-and-forget notification
	// (a Slack post without follow-up). No issue is opened, and no issue events are recorded. Later alerts with the
	// same correlation ID are ignored for a short while ([InsightsReasonFollowUpDisabled]).
	InsightsEventAlertFireAndForget InsightsEventType = "alert.fire_and_forget"

	// InsightsEventAlertGrouped means the alert finished processing and changed an existing open issue.
	InsightsEventAlertGrouped InsightsEventType = "alert.grouped"

	// InsightsEventAlertIgnored means the alert finished processing and was saved, but intentionally had no effect.
	// The reason is one of [InsightsReasonNotNewer], [InsightsReasonAlreadyResolved], [InsightsReasonFollowUpDisabled]
	// or [InsightsReasonResolvedWithoutIssue].
	InsightsEventAlertIgnored InsightsEventType = "alert.ignored"

	// InsightsEventAlertDropped means the alert was queued, but permanently discarded by the manager without being processed or saved.
	// The reason is one of [InsightsReasonInvalid], [InsightsReasonMissingEncryptionKey], [InsightsReasonCorruptIssue]
	// or [InsightsReasonUnreadable].
	InsightsEventAlertDropped InsightsEventType = "alert.dropped"

	// InsightsEventAlertRetried means a processing attempt was aborted and the alert was returned to the queue for redelivery.
	// This is not a terminal outcome. The reason is one of [InsightsReasonLockTimeout], [InsightsReasonGateTimeout],
	// [InsightsReasonSlackError], [InsightsReasonDBError] or [InsightsReasonMoveRace].
	InsightsEventAlertRetried InsightsEventType = "alert.retried"
)

Alert outcome events, recorded by the manager. Each processing attempt of a queued alert produces exactly one of these.

Issues are always issues with follow-up. An alert with follow-up disabled (including any new info alert) is a fire-and-forget notification, recorded as InsightsEventAlertFireAndForget. Fire-and-forget notifications are not issues: they never produce issue events, and are never counted as open, alerting, resolved or archived.

const (
	// InsightsEventAlertQueued means the API validated the alert and put it on the alert queue.
	InsightsEventAlertQueued InsightsEventType = "alert.queued"

	// InsightsEventAlertFiltered means the API discarded a valid alert because of a client-defined rule
	// (reason [InsightsReasonIgnoreTerm]). The client received a successful response.
	// If the alert's channel is not a channel ID (e.g. an unmapped channel name), ChannelID is empty and
	// Detail holds the value.
	InsightsEventAlertFiltered InsightsEventType = "alert.filtered"

	// InsightsEventAlertRejected means the API refused the alert and the client received an error response.
	// The reason describes why, e.g. "validation", "no_route" or "rate_limited".
	// If the alert's channel is not a channel ID (e.g. an unmapped channel name, or a channel that Slack
	// did not find), ChannelID is empty and Detail holds the value.
	InsightsEventAlertRejected InsightsEventType = "alert.rejected"
)

Alert intake events, recorded by the API server (when configured with an insights sink).

const (
	// InsightsEventIssueCreated means a new issue was created and saved.
	InsightsEventIssueCreated InsightsEventType = "issue.created"

	// InsightsEventIssueUpdated means an alert changed an existing open issue (one per [InsightsEventAlertGrouped]).
	InsightsEventIssueUpdated InsightsEventType = "issue.updated"

	// InsightsEventIssueResolved means an issue explicitly transitioned to resolved, by a resolved alert
	// ([InsightsReasonAlert]) or a user command ([InsightsReasonUser]). Resolution by auto-resolve timeout is
	// implicit and not recorded as a separate event; see [InsightsEventIssueArchived].
	InsightsEventIssueResolved InsightsEventType = "issue.resolved"

	// InsightsEventIssueReopened means a resolved issue (including auto-resolved) became unresolved again, by a
	// new alert ([InsightsReasonAlert]) or a user command ([InsightsReasonUser]).
	InsightsEventIssueReopened InsightsEventType = "issue.reopened"

	// InsightsEventIssueEscalated means an escalation rule raised the issue severity, or became active for the first time.
	InsightsEventIssueEscalated InsightsEventType = "issue.escalated"

	// InsightsEventIssueMoved means an issue was moved from ChannelID to RelatedChannelID,
	// by escalation ([InsightsReasonEscalation]) or a user command ([InsightsReasonUser]).
	InsightsEventIssueMoved InsightsEventType = "issue.moved"

	// InsightsEventIssueArchived means an issue was archived. The reason describes how the issue ended, e.g.
	// [InsightsReasonUserResolved] or [InsightsReasonAutoResolved]. The event carries lifecycle values such as
	// [InsightsValueOpenSeconds] and [InsightsValueTimeToResolveSeconds].
	InsightsEventIssueArchived InsightsEventType = "issue.archived"
)

Issue lifecycle events, recorded by the manager. They are never recorded for fire-and-forget notifications (see InsightsEventAlertFireAndForget).

const (
	// InsightsEventCommandExecuted means a user command was executed without error.
	InsightsEventCommandExecuted InsightsEventType = "command.executed"

	// InsightsEventCommandFailed means a user command failed. Commands are attempted exactly once.
	InsightsEventCommandFailed InsightsEventType = "command.failed"

	// InsightsEventCommandSkipped means a user command was ignored because no matching issue was found.
	InsightsEventCommandSkipped InsightsEventType = "command.skipped"

	// InsightsEventWebhookSucceeded means a webhook triggered by a user was delivered successfully. Detail holds the webhook ID.
	InsightsEventWebhookSucceeded InsightsEventType = "webhook.succeeded"

	// InsightsEventWebhookFailed means a webhook triggered by a user failed. Detail holds the webhook ID.
	InsightsEventWebhookFailed InsightsEventType = "webhook.failed"
)

Command and webhook events, recorded by the manager. For command events, the reason is the command action (e.g. "resolve_issue", "mute_issue", "webhook") and the actor fields identify the Slack user.

const (
	// InsightsEventSlackPostCreated means a Slack post was created for an issue. The reason is the post action ("alert" or "resolve").
	InsightsEventSlackPostCreated InsightsEventType = "slack.post_created"

	// InsightsEventSlackPostUpdated means an existing Slack post was updated. The reason is the post action ("alert" or "resolve").
	InsightsEventSlackPostUpdated InsightsEventType = "slack.post_updated"

	// InsightsEventSlackPostDeleted means a Slack post was deleted (or replaced by a tombstone when it has replies).
	InsightsEventSlackPostDeleted InsightsEventType = "slack.post_deleted"

	// InsightsEventSlackPostThrottled means a Slack post update was deferred by throttling. Repeated deferrals each count.
	InsightsEventSlackPostThrottled InsightsEventType = "slack.post_throttled"

	// InsightsEventSlackPostFailed means a Slack post could not be created, updated or deleted.
	// The reason is one of [InsightsReasonChannelUnavailable], [InsightsReasonInvalidBlocks], [InsightsReasonNotInChannel],
	// [InsightsReasonMessageNotFound] or [InsightsReasonAPIError].
	InsightsEventSlackPostFailed InsightsEventType = "slack.post_failed"
)

Slack post events, recorded by the manager.

const (
	// InsightsEventChannelStats is a periodic snapshot of the open issues in a channel, recorded while the channel
	// has open issues. Values hold counts such as [InsightsValueOpen]. Detail holds the channel name at the time.
	InsightsEventChannelStats InsightsEventType = "channel.stats"

	// InsightsEventGap is recorded by an insights recorder after events were lost (e.g. buffer overflow or write
	// errors). Count and the [InsightsValueLostEvents] value hold the number of lost events since the previous gap event.
	InsightsEventGap InsightsEventType = "insights.gap"
)

Channel and recorder events.

type InsightsFilter added in v0.8.0

type InsightsFilter struct {
	// From is the inclusive start of the time range. Required.
	From time.Time

	// To is the exclusive end of the time range. Required, and must be after From.
	To time.Time

	// ChannelIDs matches [InsightsEvent.ChannelID].
	ChannelIDs []string

	// RelatedChannelIDs matches [InsightsEvent.RelatedChannelID].
	RelatedChannelIDs []string

	// Types matches [InsightsEvent.Type].
	Types []InsightsEventType

	// Reasons matches [InsightsEvent.Reason].
	Reasons []string

	// Severities matches [InsightsEvent.Severity].
	Severities []AlertSeverity

	// RouteKeys matches [InsightsEvent.RouteKey].
	RouteKeys []string

	// Clients matches [InsightsEvent.Client]. Events without a client (e.g. channel stats) never match a
	// non-empty Clients filter.
	Clients []string

	// IssueID matches [InsightsEvent.IssueID].
	IssueID string

	// CorrelationID matches [InsightsEvent.CorrelationID].
	CorrelationID string

	// ActorID matches [InsightsEvent.ActorID].
	ActorID string
}

InsightsFilter selects insights events. Events match when their time is in [From, To) and every non-empty filter field matches. List fields match any of their values.

func (*InsightsFilter) Validate added in v0.8.0

func (f *InsightsFilter) Validate() error

Validate returns an error if the filter is invalid.

type InsightsGroupKey added in v0.8.0

type InsightsGroupKey struct {
	Bucket           time.Time         `json:"bucket,omitzero"`
	ChannelID        string            `json:"channelId,omitempty"`
	RelatedChannelID string            `json:"relatedChannelId,omitempty"`
	Type             InsightsEventType `json:"type,omitempty"`
	Reason           string            `json:"reason,omitempty"`
	Severity         AlertSeverity     `json:"severity,omitempty"`
	RouteKey         string            `json:"routeKey,omitempty"`
	AlertType        string            `json:"alertType,omitempty"`
	Host             string            `json:"host,omitempty"`
	Author           string            `json:"author,omitempty"`
	Client           string            `json:"client,omitempty"`
	ActorID          string            `json:"actorId,omitempty"`
	CorrelationID    string            `json:"correlationId,omitempty"`
	IssueID          string            `json:"issueId,omitempty"`
}

InsightsGroupKey holds the group values of a count or stats row. Only the fields of the dimensions in the query's GroupBy are set.

type InsightsGrouping added in v0.8.0

type InsightsGrouping struct {
	// GroupBy lists the dimensions to group by. Empty means a single total row.
	GroupBy []InsightsDimension

	// Bucket is the time bucket size. Required if GroupBy contains [InsightsDimensionBucket].
	// Buckets are aligned to the Unix epoch, so e.g. hourly buckets start on the hour (UTC).
	Bucket time.Duration

	// Limit is the maximum number of rows to return; any further rows are silently dropped (e.g. for top N
	// queries). Zero means all rows, up to [MaxInsightsRows]; if more rows match, the query fails with
	// [ErrInsightsTooManyRows].
	Limit int
}

InsightsGrouping defines how events are grouped in count and stats queries.

func (*InsightsGrouping) EffectiveLimit added in v0.8.0

func (g *InsightsGrouping) EffectiveLimit() int

EffectiveLimit returns Limit, or MaxInsightsRows if Limit is zero.

func (*InsightsGrouping) HasDimension added in v0.8.0

func (g *InsightsGrouping) HasDimension(d InsightsDimension) bool

HasDimension returns true if GroupBy contains d.

type InsightsListQuery added in v0.8.0

type InsightsListQuery struct {
	InsightsFilter

	// Cursor continues a previous listing. It must be a NextCursor value returned for the same query, or empty.
	Cursor string

	// Limit is the maximum number of events to return. Zero means [DefaultInsightsPageSize].
	Limit int

	// Descending orders events newest first. Otherwise oldest first.
	Descending bool
}

InsightsListQuery lists events. See InsightsReader.ListInsightsEvents.

func (*InsightsListQuery) EffectiveLimit added in v0.8.0

func (q *InsightsListQuery) EffectiveLimit() int

EffectiveLimit returns Limit, or DefaultInsightsPageSize if Limit is zero.

func (*InsightsListQuery) Validate added in v0.8.0

func (q *InsightsListQuery) Validate() error

Validate returns an error if the query is invalid.

type InsightsReader added in v0.8.0

type InsightsReader interface {
	// CountInsightsEvents counts events matching the query filter, grouped by the query dimensions.
	// If [InsightsGrouping.Limit] is zero and more than [MaxInsightsRows] groups match, it returns
	// [ErrInsightsTooManyRows] rather than a truncated result.
	CountInsightsEvents(ctx context.Context, query *InsightsCountQuery) ([]*InsightsCountRow, error)

	// InsightsValueStats computes aggregates of one numeric event value (see [InsightsEvent.Values]) for events
	// matching the query filter, grouped by the query dimensions. Events without the value are ignored.
	// If [InsightsGrouping.Limit] is zero and more than [MaxInsightsRows] groups match, it returns
	// [ErrInsightsTooManyRows] rather than a truncated result.
	InsightsValueStats(ctx context.Context, query *InsightsStatsQuery) ([]*InsightsStatsRow, error)

	// ListInsightsEvents returns a page of events matching the query filter, ordered by time.
	ListInsightsEvents(ctx context.Context, query *InsightsListQuery) (*InsightsEventPage, error)

	// LoadOpenIssues loads all open (non-archived) issues in the given channels, or in all channels if channelIDs is empty.
	// The returned map is keyed by issue ID, with the opaque issue JSON as value.
	LoadOpenIssues(ctx context.Context, channelIDs []string) (map[string]json.RawMessage, error)
}

InsightsReader answers insights queries.

Implementations must only require read (SELECT) privileges, and must never modify data or schema. Queries must be validated with the Validate method of the query type before they are executed.

type InsightsReaderProvider added in v0.8.0

type InsightsReaderProvider interface {
	// InsightsReader returns the reader, or nil if insights reading is not available.
	InsightsReader() InsightsReader
}

InsightsReaderProvider is optionally implemented by a DB implementation that supports reading insights.

type InsightsSink added in v0.8.0

type InsightsSink interface {
	// WriteInsightsEvents persists the events. The slice must not be retained after the call returns.
	WriteInsightsEvents(ctx context.Context, events []InsightsEvent) error
}

InsightsSink persists batches of InsightsEvent values.

Implementations must honour the context deadline, must be safe for concurrent use, and must not share transactions or connection capacity with the regular alert and issue writes, so that insights can never slow down alert processing. Events are best-effort data: an implementation may return an error and lose the batch rather than retrying for a long time.

type InsightsSinkProvider added in v0.8.0

type InsightsSinkProvider interface {
	// InsightsSink returns the sink, or nil if insights recording is disabled in the implementation.
	InsightsSink() InsightsSink
}

InsightsSinkProvider is optionally implemented by a DB implementation that supports recording insights. The Slack Manager discovers it with a type assertion.

type InsightsStatsQuery added in v0.8.0

type InsightsStatsQuery struct {
	InsightsFilter
	InsightsGrouping

	// ValueKey is the key in [InsightsEvent.Values] to aggregate, e.g. [InsightsValueOpenSeconds]. Required.
	ValueKey string

	// Aggregates lists the aggregates to compute. Required.
	Aggregates []InsightsAggregate
}

InsightsStatsQuery computes aggregates of a numeric event value. See InsightsReader.InsightsValueStats.

func (*InsightsStatsQuery) Validate added in v0.8.0

func (q *InsightsStatsQuery) Validate() error

Validate returns an error if the query is invalid.

type InsightsStatsRow added in v0.8.0

type InsightsStatsRow struct {
	InsightsGroupKey

	// Count is the number of events with the value.
	Count int64 `json:"count"`

	// Values holds the computed aggregates.
	Values map[InsightsAggregate]float64 `json:"values"`
}

InsightsStatsRow is a row returned by InsightsReader.InsightsValueStats.

type Issue

type Issue interface {
	json.Marshaler

	// ChannelID returns the Slack channel ID that this issue belongs to.
	ChannelID() string

	// UniqueID returns a unique and deterministic ID for this issue, for database/storage purposes.
	// The ID is based on certain issue fields, and is base64 encoded to ensure it is safe for use in URLs and as a database key.
	UniqueID() string

	// GetCorrelationID returns the correlation ID for this issue.
	// The correlation ID is used to group related alerts together, and may or may not be client defined.
	// It is not guaranteed to be unique across all issues, even in the same channel, and *cannot* be used as a unique issue identifier.
	// It is not URL safe, and should thus be encoded before being used in URLs or as part of a database key.
	GetCorrelationID() string

	// IsOpen returns true if this issue is currently open (i.e. not archived).
	// A resolved issue is still considered open until it is archived.
	IsOpen() bool

	// CurrentPostID returns the current Slack post ID associated with this issue.
	// The value may change over time as the issue is updated.
	// If the issue has no current post, it returns an empty string.
	CurrentPostID() string
}

Issue represents an issue in a Slack channel. It is used to track alerts, their resolution status, and their association with Slack posts.

The actual implementation of this interface is internal to the Slack Manager, and may change without notice. The database implementation should only store a JSON representation of the issue, and should not depend on any specific fields or structures of the issue.

type Logger

type Logger interface {
	Debug(msg string)
	Debugf(format string, args ...any)
	Info(msg string)
	Infof(format string, args ...any)
	Error(msg string)
	Errorf(format string, args ...any)
	WithField(key string, value any) Logger
	WithFields(fields map[string]any) Logger
}

type Metrics

type Metrics interface {
	// RegisterCounter registers a counter metric with the given name, help text, and optional labels.
	RegisterCounter(name, help string, labels ...string)

	// RegisterGauge registers a gauge metric with the given name, help text, and optional labels.
	RegisterGauge(name, help string, labels ...string)

	// RegisterHistogram registers a histogram metric with the given name, help text, buckets, and optional labels.
	RegisterHistogram(name, help string, buckets []float64, labels ...string)

	// CounterAdd adds the given value to the specified counter metric, with optional label values.
	CounterAdd(name string, value float64, labelValues ...string)

	// CounterInc increments the specified counter metric by 1, with optional label values.
	CounterInc(name string, labelValues ...string)

	// GaugeSet sets the specified gauge metric to the given value, with optional label values.
	GaugeSet(name string, value float64, labelValues ...string)

	// GaugeAdd adds the given value to the specified gauge metric, with optional label values.
	// Use a negative value to subtract.
	GaugeAdd(name string, value float64, labelValues ...string)

	// Observe records an observation for the specified histogram metric, with optional label values.
	Observe(name string, value float64, labelValues ...string)
}

type MoveMapping

type MoveMapping interface {
	json.Marshaler

	// ChannelID returns the Slack channel ID that this move mapping belongs to (i.e. the channel where the move was initiated).
	ChannelID() string

	// UniqueID returns a unique and deterministic ID for this move mapping, for database/storage purposes.
	// The ID is based on the original channel and the correlation ID, and is base64 encoded to ensure it is safe for use in URLs and as a database key.
	UniqueID() string

	// GetCorrelationID returns the correlation ID that this move mapping is associated with, for the given channel.
	// It is not URL safe, and should thus be encoded before being used in URLs or as part of a database key.
	GetCorrelationID() string
}

MoveMapping represents an issue that has been moved from one channel to another, based on the correlation ID. It is used to ensure that new alerts with the same correlation ID are not processed in the original channel, but instead are processed in the new channel.

The actual implementation of this interface is internal to the Slack Manager, and may change without notice. The database implementation should only store a JSON representation of the move mapping, and should not depend on any specific fields or structure of the move mapping.

type NoopLogger

type NoopLogger struct{}

func (*NoopLogger) Debug

func (l *NoopLogger) Debug(msg string)

func (*NoopLogger) Debugf

func (l *NoopLogger) Debugf(format string, args ...any)

func (*NoopLogger) Error

func (l *NoopLogger) Error(msg string)

func (*NoopLogger) Errorf

func (l *NoopLogger) Errorf(format string, args ...any)

func (*NoopLogger) Info

func (l *NoopLogger) Info(msg string)

func (*NoopLogger) Infof

func (l *NoopLogger) Infof(format string, args ...any)

func (*NoopLogger) WithField

func (l *NoopLogger) WithField(key string, value any) Logger

func (*NoopLogger) WithFields

func (l *NoopLogger) WithFields(fields map[string]any) Logger

type NoopMetrics

type NoopMetrics struct{}

NoopMetrics is a no-op implementation of the Metrics interface. It does not record any metrics. Use if no metrics are needed.

func (*NoopMetrics) CounterAdd added in v0.4.0

func (m *NoopMetrics) CounterAdd(_ string, _ float64, _ ...string)

func (*NoopMetrics) CounterInc added in v0.4.0

func (m *NoopMetrics) CounterInc(_ string, _ ...string)

func (*NoopMetrics) GaugeAdd added in v0.4.0

func (m *NoopMetrics) GaugeAdd(_ string, _ float64, _ ...string)

func (*NoopMetrics) GaugeSet added in v0.4.0

func (m *NoopMetrics) GaugeSet(_ string, _ float64, _ ...string)

func (*NoopMetrics) Observe

func (m *NoopMetrics) Observe(_ string, _ float64, _ ...string)

func (*NoopMetrics) RegisterCounter

func (m *NoopMetrics) RegisterCounter(_, _ string, _ ...string)

func (*NoopMetrics) RegisterGauge

func (m *NoopMetrics) RegisterGauge(_, _ string, _ ...string)

func (*NoopMetrics) RegisterHistogram

func (m *NoopMetrics) RegisterHistogram(_, _ string, _ []float64, _ ...string)

type Principal added in v0.14.0

type Principal struct {
	// ID is the stable identity of the caller, e.g. "alertmanager-prod". It is logged with each request.
	ID string `json:"id"`

	// Scopes are the scopes granted to the caller, e.g. [ScopeAlertsWrite]. See [Principal.HasScope].
	Scopes []string `json:"scopes,omitempty"`

	// Attributes holds optional, authenticator specific information, e.g. token claims.
	Attributes map[string]string `json:"attributes,omitempty"`
}

Principal is an authenticated caller of the REST API, e.g. a monitoring system or integration.

func (*Principal) HasScope added in v0.14.0

func (p *Principal) HasScope(scope string) bool

HasScope reports whether the principal has the given scope, or ScopeAll. A nil principal has no scopes.

type Webhook

type Webhook struct {
	// ID is the unique identifier for this webhook within the alert.
	// It must be unique among all webhooks in the same alert.
	// Maximum length: MaxWebhookIDLength characters.
	ID string `json:"id,omitzero"`

	// URL specifies the target for the webhook when the button is clicked.
	// For HTTP webhooks, this must be a valid absolute URL starting with http:// or https://.
	// For custom webhook handlers registered in the Slack Manager app, this can be an arbitrary
	// ASCII string identifier that the handler recognizes.
	// The field name "URL" is retained for backwards compatibility.
	// Maximum length: MaxWebhookURLLength characters.
	URL string `json:"url,omitzero"`

	// ConfirmationText is the text displayed as the header of the confirmation dialog
	// shown before triggering the webhook.
	// If empty, a default header referencing the webhook URL is used.
	// Ignored when SkipConfirmationDialog is true.
	// Maximum length: MaxWebhookConfirmationTextLength characters.
	ConfirmationText string `json:"confirmationText,omitzero"`

	// SkipConfirmationDialog, when true, instructs the core manager to post the webhook
	// without first showing a confirmation dialog to the user.
	// Defaults to false.
	// Must be false when ButtonStyle is WebhookButtonStyleDanger: destructive actions
	// always require a confirmation step.
	// Must be false when PlainTextInput or CheckboxInput is non-empty: input fields
	// are collected via the confirmation dialog, so skipping the dialog leaves nowhere
	// to render them.
	SkipConfirmationDialog bool `json:"skipConfirmationDialog,omitzero"`

	// ButtonText is the label displayed on the button in Slack.
	// This field is required.
	// Maximum length: MaxWebhookButtonTextLength characters.
	ButtonText string `json:"buttonText,omitzero"`

	// ButtonStyle determines the visual appearance of the button in Slack.
	// Valid values are defined by WebhookButtonStyle constants.
	// If empty, defaults to WebhookButtonStyleDefault.
	// When set to WebhookButtonStyleDanger, SkipConfirmationDialog must be false.
	ButtonStyle WebhookButtonStyle `json:"buttonStyle,omitzero"`

	// AccessLevel controls who can click this webhook button.
	// Valid values are defined by WebhookAccessLevel constants.
	// If empty, defaults to WebhookAccessLevelGlobalAdmins.
	AccessLevel WebhookAccessLevel `json:"accessLevel,omitzero"`

	// DisplayMode controls when the webhook button is visible.
	// Valid values are defined by WebhookDisplayMode constants.
	// If empty, behaves like WebhookDisplayModeOpenIssue (hidden when the issue is resolved).
	DisplayMode WebhookDisplayMode `json:"displayMode,omitzero"`

	// Payload is a map of static key-value pairs sent back in WebhookCallback.Payload when the webhook fires.
	// This data is defined at alert creation time and is not modified at runtime.
	// Maximum of MaxWebhookPayloadCount items.
	Payload map[string]any `json:"payload,omitzero"`

	// PlainTextInput defines text input fields shown in the webhook's modal dialog before the webhook fires.
	// User-entered values are sent back in WebhookCallback.PlainTextInput, keyed by each input's ID.
	// Maximum of MaxWebhookPlainTextInputCount inputs.
	// Must be empty when SkipConfirmationDialog is true.
	PlainTextInput []*WebhookPlainTextInput `json:"plainTextInput,omitzero"`

	// CheckboxInput defines checkbox groups shown in the webhook's modal dialog before the webhook fires.
	// Selected option values are sent back in WebhookCallback.CheckboxInput, keyed by each input's ID.
	// Maximum of MaxWebhookCheckboxInputCount inputs.
	// Must be empty when SkipConfirmationDialog is true.
	CheckboxInput []*WebhookCheckboxInput `json:"checkboxInput,omitzero"`

	// AfterClick optionally describes how the Slack post changes after the button was clicked and the webhook was
	// delivered, e.g. hiding buttons and showing a status text, until the next alert for the issue is received.
	// If nil, the Slack post is not changed.
	AfterClick *WebhookAfterClick `json:"afterClick,omitzero"`
}

Webhook represents an interactive button that appears on the Slack post. When clicked, it triggers an HTTP POST request to the specified URL (for http/https URLs), or invokes a custom webhook handler registered in the Slack Manager app.

type WebhookAccessLevel

type WebhookAccessLevel string

WebhookAccessLevel is the access level required to invoke a webhook.

const (
	// WebhookAccessLevelGlobalAdmins indicates that a webhook is available only to Slack Manager global admins.
	WebhookAccessLevelGlobalAdmins WebhookAccessLevel = "global_admins"

	// WebhookAccessLevelChannelAdmins indicates that a webhook is available to the Slack Manager channel admins (including global admins).
	WebhookAccessLevelChannelAdmins WebhookAccessLevel = "channel_admins"

	// WebhookAccessLevelChannelMembers indicates that a webhook is available to all members in a channel (including channel admins and global admins).
	WebhookAccessLevelChannelMembers WebhookAccessLevel = "channel_members"
)

type WebhookAfterClick added in v0.9.0

type WebhookAfterClick struct {
	// HideButtons controls which webhook buttons are hidden.
	// Valid values are defined by WebhookHideButtons constants.
	// If empty, defaults to WebhookHideButtonsNone.
	HideButtons WebhookHideButtons `json:"hideButtons,omitzero"`

	// HideWebhookIDs lists additional webhooks (by ID) whose buttons are hidden.
	// Each ID must match a webhook in the same alert. Ignored when HideButtons is WebhookHideButtonsAll.
	// Maximum of MaxWebhookCount items.
	HideWebhookIDs []string `json:"hideWebhookIds,omitzero"`

	// StatusText is an optional text shown on the Slack post, e.g. "Restart in progress, the alert will be updated
	// when done". The clicking user and time are added by Slack Manager.
	// Maximum length: MaxWebhookAfterClickStatusTextLength characters.
	StatusText string `json:"statusText,omitzero"`

	// ResetAfterSeconds is the maximum time the post-click state is kept if no new alert is received.
	// If 0, defaults to DefaultWebhookAfterClickResetSeconds.
	// Must be >=0 and <=MaxWebhookAfterClickResetSeconds.
	ResetAfterSeconds int `json:"resetAfterSeconds,omitzero"`
}

WebhookAfterClick describes how the Slack post changes after a webhook button was clicked and the webhook was delivered, while the receiving system is working on the request. It gives everyone in the channel immediate feedback, and prevents duplicate clicks.

The post-click state is temporary. It is cleared when the next alert for the issue is received (even if the alert is otherwise unchanged or ignored), or when ResetAfterSeconds has passed without an alert. On expiry, the buttons are shown again with a note that no update was received. Nothing changes if the webhook could not be delivered; the user who clicked is informed instead.

func (*WebhookAfterClick) HidesWebhook added in v0.9.0

func (w *WebhookAfterClick) HidesWebhook(clickedWebhookID, webhookID string) bool

HidesWebhook returns true if the button of the webhook with ID webhookID is hidden after the webhook with ID clickedWebhookID was clicked.

func (*WebhookAfterClick) ResetAfter added in v0.9.0

func (w *WebhookAfterClick) ResetAfter() time.Duration

ResetAfter returns the reset delay, i.e. ResetAfterSeconds, or DefaultWebhookAfterClickResetSeconds if it is 0.

type WebhookButtonStyle

type WebhookButtonStyle string

WebhookButtonStyle represents a webhook button style.

const (
	// WebhookButtonStyleDefault represents the default Slack button style (no special styling).
	WebhookButtonStyleDefault WebhookButtonStyle = "default"

	// WebhookButtonStylePrimary represents Slack button style 'primary'.
	// Green outline and text, used for affirmative or key confirmation actions (e.g., "Approve", "Confirm").
	WebhookButtonStylePrimary WebhookButtonStyle = "primary"

	// WebhookButtonStyleDanger represents Slack button style 'danger'.
	// Red outline and text, used for actions with significant consequences, such as deletion (e.g., "Delete", "Remove").
	WebhookButtonStyleDanger WebhookButtonStyle = "danger"
)

type WebhookCallback

type WebhookCallback struct {
	// ID is the webhook ID from the originating Webhook definition.
	ID string `json:"id"`

	// UserID is the Slack user ID of the user who clicked the button.
	UserID string `json:"userId"`

	// UserRealName is the display name of the user who clicked the button.
	UserRealName string `json:"userRealName"`

	// ChannelID is the Slack channel ID where the button was clicked.
	ChannelID string `json:"channelId"`

	// MessageID is the Slack message timestamp (ts) of the post that contained the button.
	MessageID string `json:"messageId"`

	// Timestamp is the time when the webhook was triggered.
	Timestamp time.Time `json:"timestamp"`

	// PlainTextInput contains the values entered by the user in the webhook's PlainTextInput fields,
	// keyed by each input's ID.
	PlainTextInput map[string]string `json:"plainTextInput"`

	// Deprecated: Input is a legacy copy of PlainTextInput, kept for compatibility with older
	// webhook receivers that read the "input" JSON key. It is only populated when the manager
	// runs with legacy features enabled. Use PlainTextInput instead.
	Input map[string]string `json:"input,omitempty"`

	// CheckboxInput contains the selected option values from the webhook's CheckboxInput groups,
	// keyed by each input's ID. Each value is the list of selected option values.
	CheckboxInput map[string][]string `json:"checkboxInput"`

	// Payload contains the static key-value pairs from the originating Webhook.Payload definition.
	// These values are set at alert creation time and are not modified by user interaction.
	Payload map[string]any `json:"payload"`
}

WebhookCallback is the payload sent via HTTP POST to the webhook URL when a user clicks a webhook button.

func (*WebhookCallback) GetCheckboxInputSelectedValues

func (w *WebhookCallback) GetCheckboxInputSelectedValues(key string) []string

func (*WebhookCallback) GetInputValue

func (w *WebhookCallback) GetInputValue(key string) string

func (*WebhookCallback) GetPayloadBool

func (w *WebhookCallback) GetPayloadBool(key string, defaultValue bool) bool

func (*WebhookCallback) GetPayloadInt

func (w *WebhookCallback) GetPayloadInt(key string, defaultValue int) int

func (*WebhookCallback) GetPayloadString

func (w *WebhookCallback) GetPayloadString(key string) string

func (*WebhookCallback) GetPayloadValue

func (w *WebhookCallback) GetPayloadValue(key string) any

type WebhookCheckboxInput

type WebhookCheckboxInput struct {
	// ID is the unique identifier for this checkbox group.
	// It must be unique among all inputs (both text and checkbox) in the same webhook.
	// The ID is used as the key in WebhookCallback.CheckboxInput.
	// Maximum length: MaxWebhookInputIDLength characters.
	ID string `json:"id,omitzero"`

	// Label is the text displayed above the checkbox group.
	// Maximum length: MaxWebhookInputLabelLength characters.
	Label string `json:"label,omitzero"`

	// Options is the list of checkbox options available in this group.
	// Maximum of MaxWebhookCheckboxOptionCount options.
	Options []*WebhookCheckboxOption `json:"options,omitzero"`
}

WebhookCheckboxInput represents a group of checkboxes in a webhook's modal dialog. Selected option values are sent back in WebhookCallback.CheckboxInput as an array, keyed by the field ID.

type WebhookCheckboxOption

type WebhookCheckboxOption struct {
	// Value is the value included in WebhookCallback.CheckboxInput when this option is selected.
	// Must be unique among all options in the same checkbox group.
	// Maximum length: MaxCheckboxOptionValueLength characters.
	Value string `json:"value,omitzero"`

	// Text is the label displayed next to the checkbox.
	// Maximum length: MaxWebhookCheckboxOptionTextLength characters.
	Text string `json:"text,omitzero"`

	// Selected determines whether this checkbox is pre-selected when the modal opens.
	Selected bool `json:"selected,omitzero"`
}

WebhookCheckboxOption represents a single checkbox option within a WebhookCheckboxInput.

type WebhookDisplayMode

type WebhookDisplayMode string

WebhookDisplayMode represents a display mode for a webhook button.

const (
	// WebhookDisplayModeAlways means that the webhook button is always displayed, regardless of issue state.
	WebhookDisplayModeAlways WebhookDisplayMode = "always"

	// WebhookDisplayModeOpenIssue means that the webhook button is displayed for open issues only (error, warning etc).
	WebhookDisplayModeOpenIssue WebhookDisplayMode = "open_issue"

	// WebhookDisplayModeResolvedIssue means that the webhook button is displayed for resolved issues only.
	WebhookDisplayModeResolvedIssue WebhookDisplayMode = "resolved_issue"
)

type WebhookHideButtons added in v0.9.0

type WebhookHideButtons string

WebhookHideButtons controls which webhook buttons are hidden after a webhook was clicked and delivered. See WebhookAfterClick.HideButtons.

const (
	// WebhookHideButtonsNone hides no buttons, except those listed in [WebhookAfterClick.HideWebhookIDs].
	WebhookHideButtonsNone WebhookHideButtons = "none"

	// WebhookHideButtonsClicked hides the clicked button, plus those listed in [WebhookAfterClick.HideWebhookIDs].
	WebhookHideButtonsClicked WebhookHideButtons = "clicked"

	// WebhookHideButtonsAll hides all webhook buttons on the alert.
	WebhookHideButtonsAll WebhookHideButtons = "all"
)

type WebhookPlainTextInput

type WebhookPlainTextInput struct {
	// ID is the unique identifier for this input field.
	// It must be unique among all inputs (both text and checkbox) in the same webhook.
	// The ID is used as the key in WebhookCallback.PlainTextInput.
	// Maximum length: MaxWebhookInputIDLength characters.
	ID string `json:"id,omitzero"`

	// Description is the label shown above the input field.
	// Maximum length: MaxWebhookInputDescriptionLength characters.
	Description string `json:"description,omitzero"`

	// MinLength is the minimum number of characters required for the input.
	// Zero makes the input optional, i.e. the user can leave it empty. Any other value makes it required.
	// Must be >= 0 and <= MaxLength.
	MinLength int `json:"minLength,omitzero"`

	// MaxLength is the maximum number of characters allowed for the input.
	// Must be >= MinLength and <= MaxWebhookInputTextLength.
	MaxLength int `json:"maxLength,omitzero"`

	// Multiline determines whether the input field allows multiple lines of text.
	// If true, a larger textarea is shown instead of a single-line input.
	Multiline bool `json:"multiline,omitzero"`

	// InitialValue is the default text pre-filled in the input field.
	// Must satisfy the MinLength and MaxLength constraints.
	InitialValue string `json:"initialValue,omitzero"`
}

WebhookPlainTextInput represents a text input field in a webhook's modal dialog. The user's input is sent back in WebhookCallback.PlainTextInput, keyed by the field ID.

type WebhookResponse added in v0.10.0

type WebhookResponse struct {
	// Result is the webhook result. Nil if the body has no [WebhookResultKey] key.
	Result *WebhookResult `json:"slackManagerResult"`
}

WebhookResponse is the body a synchronous webhook receiver (e.g. an HTTP endpoint) may respond with, to give feedback on a webhook button click. It wraps the WebhookResult in the WebhookResultKey key, so that existing response bodies are not mistaken for results.

Example body:

{"slackManagerResult": {"message": "Restarting 3 pods", "afterClick": {"hideButtons": "all"}}}

Whether the request was accepted is signalled by the response itself, e.g. the HTTP status code: 2xx means accepted, 4xx means rejected.

type WebhookResult added in v0.10.0

type WebhookResult struct {
	// Message is an optional message for the user who clicked the button, e.g. a validation error or
	// "3 pods will be restarted, the alert is updated in about 2 minutes". It is shown as plain text.
	// Maximum length: MaxWebhookResultMessageLength characters.
	Message string `json:"message"`

	// AfterClick optionally overrides [Webhook.AfterClick] for this click. Ignored when the request was rejected.
	// Each of AfterClick.HideWebhookIDs should match a webhook in the alert; unknown IDs are ignored, since the alert
	// is not known when the result is validated.
	AfterClick *WebhookAfterClick `json:"afterClick,omitempty"`
}

WebhookResult is the feedback from a synchronous webhook receiver on a webhook button click. See WebhookResponse for the response body format.

The Message is shown to the user who clicked the button, both when the request was accepted and when it was rejected. The AfterClick state is applied to the Slack post (seen by everyone in the channel) only when the request was accepted, and overrides Webhook.AfterClick for this click.

func (*WebhookResult) Clean added in v0.10.0

func (r *WebhookResult) Clean()

Clean trims whitespace and applies defaults (AfterClick.HideButtons). It is a no-op on a nil receiver.

func (*WebhookResult) Validate added in v0.10.0

func (r *WebhookResult) Validate() error

Validate validates the result. Call WebhookResult.Clean first to trim whitespace and apply defaults.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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