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
- Variables
- func IsKnownScope(scope string) bool
- func KnownScopes() []string
- func SeverityIsValid(s AlertSeverity) bool
- func SeverityPriority(s AlertSeverity) int
- func ValidSeverities() []string
- func ValidWebhookAccessLevels() []string
- func ValidWebhookButtonStyles() []string
- func ValidWebhookDisplayModes() []string
- func ValidWebhookHideButtons() []string
- func WebhookAccessLevelIsValid(s WebhookAccessLevel) bool
- func WebhookButtonStyleIsValid(s WebhookButtonStyle) bool
- func WebhookDisplayModeIsValid(s WebhookDisplayMode) bool
- func WebhookHideButtonsIsValid(s WebhookHideButtons) bool
- type Alert
- func (a *Alert) Clean()
- func (a *Alert) EffectiveClient() string
- func (a *Alert) UniqueID() string
- func (a *Alert) Validate() error
- func (a *Alert) ValidateAutoResolve() error
- func (a *Alert) ValidateCorrelationID() error
- func (a *Alert) ValidateEscalation() error
- func (a *Alert) ValidateFields() error
- func (a *Alert) ValidateHeaderAndText() error
- func (a *Alert) ValidateIcon() error
- func (a *Alert) ValidateIgnoreIfTextContains() error
- func (a *Alert) ValidateLink() error
- func (a *Alert) ValidateSeverity() error
- func (a *Alert) ValidateSlackChannelIDAndRouteKey() error
- func (a *Alert) ValidateWebhooks() error
- type AlertSeverity
- type Authenticator
- type AuthenticatorFunc
- type Authorizer
- type AuthorizerFunc
- type ChannelAuthorizer
- type ChannelAuthorizerFunc
- type ChannelProcessingState
- type DB
- type Escalation
- type Field
- type FifoQueueItem
- type InMemoryDB
- func (db *InMemoryDB) DeleteMoveMapping(_ context.Context, channelID, correlationID string) error
- func (db *InMemoryDB) DropAllData(_ context.Context) error
- func (db *InMemoryDB) FindActiveChannels(_ context.Context) ([]string, error)
- func (db *InMemoryDB) FindChannelProcessingState(_ context.Context, channelID string) (*ChannelProcessingState, error)
- func (db *InMemoryDB) FindIssueBySlackPostID(_ context.Context, channelID, postID string) (string, json.RawMessage, error)
- func (db *InMemoryDB) FindMoveMapping(_ context.Context, channelID, correlationID string) (json.RawMessage, error)
- func (db *InMemoryDB) FindOpenIssueByCorrelationID(_ context.Context, channelID, correlationID string) (string, json.RawMessage, error)
- func (db *InMemoryDB) Init(_ context.Context, _ bool) error
- func (db *InMemoryDB) LoadOpenIssuesInChannel(_ context.Context, channelID string) (map[string]json.RawMessage, error)
- func (db *InMemoryDB) MoveIssue(_ context.Context, issue Issue, sourceChannelID, targetChannelID string) error
- func (db *InMemoryDB) SaveAlert(_ context.Context, alert *Alert) error
- func (db *InMemoryDB) SaveChannelProcessingState(_ context.Context, state *ChannelProcessingState) error
- func (db *InMemoryDB) SaveIssue(_ context.Context, issue Issue) error
- func (db *InMemoryDB) SaveIssues(ctx context.Context, issues ...Issue) error
- func (db *InMemoryDB) SaveMoveMapping(_ context.Context, moveMapping MoveMapping) error
- type InMemoryFifoQueue
- type InsightsAggregate
- type InsightsCountQuery
- type InsightsCountRow
- type InsightsDimension
- type InsightsEvent
- type InsightsEventPage
- type InsightsEventType
- type InsightsFilter
- type InsightsGroupKey
- type InsightsGrouping
- type InsightsListQuery
- type InsightsReader
- type InsightsReaderProvider
- type InsightsSink
- type InsightsSinkProvider
- type InsightsStatsQuery
- type InsightsStatsRow
- type Issue
- type Logger
- type Metrics
- type MoveMapping
- type NoopLogger
- func (l *NoopLogger) Debug(msg string)
- func (l *NoopLogger) Debugf(format string, args ...any)
- func (l *NoopLogger) Error(msg string)
- func (l *NoopLogger) Errorf(format string, args ...any)
- func (l *NoopLogger) Info(msg string)
- func (l *NoopLogger) Infof(format string, args ...any)
- func (l *NoopLogger) WithField(key string, value any) Logger
- func (l *NoopLogger) WithFields(fields map[string]any) Logger
- type NoopMetrics
- func (m *NoopMetrics) CounterAdd(_ string, _ float64, _ ...string)
- func (m *NoopMetrics) CounterInc(_ string, _ ...string)
- func (m *NoopMetrics) GaugeAdd(_ string, _ float64, _ ...string)
- func (m *NoopMetrics) GaugeSet(_ string, _ float64, _ ...string)
- func (m *NoopMetrics) Observe(_ string, _ float64, _ ...string)
- func (m *NoopMetrics) RegisterCounter(_, _ string, _ ...string)
- func (m *NoopMetrics) RegisterGauge(_, _ string, _ ...string)
- func (m *NoopMetrics) RegisterHistogram(_, _ string, _ []float64, _ ...string)
- type Principal
- type Webhook
- type WebhookAccessLevel
- type WebhookAfterClick
- type WebhookButtonStyle
- type WebhookCallback
- func (w *WebhookCallback) GetCheckboxInputSelectedValues(key string) []string
- func (w *WebhookCallback) GetInputValue(key string) string
- func (w *WebhookCallback) GetPayloadBool(key string, defaultValue bool) bool
- func (w *WebhookCallback) GetPayloadInt(key string, defaultValue int) int
- func (w *WebhookCallback) GetPayloadString(key string) string
- func (w *WebhookCallback) GetPayloadValue(key string) any
- type WebhookCheckboxInput
- type WebhookCheckboxOption
- type WebhookDisplayMode
- type WebhookHideButtons
- type WebhookPlainTextInput
- type WebhookResponse
- type WebhookResult
Constants ¶
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 = 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 )
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.
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.
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.
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.
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.
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.
const ( 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.
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.
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.
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.
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 )
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.
const InsightsMaxDetailLen = 200
InsightsMaxDetailLen is the maximum length of InsightsEvent.Detail. Longer values are truncated by InsightsEvent.Normalize.
const (
// InsightsReasonIgnoreTerm means the alert text contained one of the alert's ignoreIfTextContains terms.
InsightsReasonIgnoreTerm = "ignore_term"
)
Reasons used by InsightsEventAlertFiltered.
const UnknownClient = "unknown"
UnknownClient is the effective client of an alert with neither Client nor Username set (see Alert.EffectiveClient).
Variables ¶
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)) )
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).
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.
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
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"`
// 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
EffectiveClient returns the client that produced the alert, for grouping, filtering and reporting. It returns the first non-empty value, in this order:
- the trimmed Alert.Client
- the trimmed Alert.Username
- UnknownClient
func (*Alert) UniqueID ¶
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 ¶
Validate returns an error if one or more of the required fields are empty or invalid
func (*Alert) ValidateAutoResolve ¶
ValidateAutoResolve validates that AutoResolveSeconds is within the allowed range when IssueFollowUpEnabled is true.
func (*Alert) ValidateCorrelationID ¶
ValidateCorrelationID validates that CorrelationID, if set, does not exceed MaxCorrelationIDLength.
func (*Alert) ValidateEscalation ¶
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 ¶
ValidateFields validates that the number of fields does not exceed MaxFieldCount.
func (*Alert) ValidateHeaderAndText ¶
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 ¶
ValidateIcon validates that IconEmoji, if set, matches the expected Slack emoji format ':emoji:'.
func (*Alert) ValidateIgnoreIfTextContains ¶
ValidateIgnoreIfTextContains validates that the IgnoreIfTextContains slice does not exceed the maximum count and that each item does not exceed the maximum length.
func (*Alert) ValidateLink ¶
ValidateLink validates that Link, if set, is a valid absolute URL with a scheme.
func (*Alert) ValidateSeverity ¶
ValidateSeverity validates that Severity is one of the allowed AlertSeverity values.
func (*Alert) ValidateSlackChannelIDAndRouteKey ¶
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 ¶
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
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
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
AuthorizerFunc is a function that implements Authorizer.
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
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.
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 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) 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) 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.
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.
Source Files
¶
- alert.go
- alert_severity.go
- auth.go
- channel_processing_state.go
- db.go
- doc.go
- fifo_queue_item.go
- in_memory_db.go
- in_memory_fifo_queue.go
- insights.go
- insights_event.go
- insights_query.go
- issue.go
- logger.go
- metrics.go
- move_mapping.go
- noop_logger.go
- noop_metrics.go
- webhook_access_level.go
- webhook_after_click.go
- webhook_button_style.go
- webhook_callback.go
- webhook_display_mode.go
- webhook_result.go