restapi

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 34 Imported by: 2

Documentation

Index

Constants

View Source
const ClientErrorReportClient = "slackmgr-api"

ClientErrorReportClient is the client (types.Alert.Client) of alerts that report client errors to the error report channel (config.APIConfig.ErrorReportChannelID). Without it, such alerts would be recorded in insights with the client types.UnknownClient, since they have no username.

View Source
const NA = "N/A"
View Source
const True = "true"

Variables

This section is empty.

Functions

func OpenAPISpec added in v0.30.0

func OpenAPISpec() []byte

OpenAPISpec returns the OpenAPI 3.1 specification of the REST API served by Server, in YAML format. The Server also serves it at GET /openapi.yaml. The returned slice is a copy, which the caller may modify.

Types

type AlertRateLimiter added in v0.27.0

type AlertRateLimiter interface {
	// TakeAll attempts to take tokens from the token buckets of all channels of a request at once,
	// using the rate and burst of limit. counts maps each channel to its number of tokens. Either the
	// tokens of all channels are taken, or none, so that a request is accepted or rejected as a whole.
	//
	// The result has an entry for each channel in counts. Allowed is the same for all entries: true if
	// the tokens were taken. When it is false, RetryAfter is set for the channels with too few tokens,
	// and zero for the others.
	//
	// An error means the limit could not be checked. The [Server] then allows the alerts (fails open).
	TakeAll(ctx context.Context, counts map[string]int, limit config.RateLimitConfig) (map[string]RateLimitResult, error)
}

AlertRateLimiter enforces the per-channel alert rate limit (APIConfig.RateLimitPerAlertChannel) of the Server. Each channel has its own token bucket.

The Server uses a LocalAlertRateLimiter by default, which limits each API instance separately. Use RedisAlertRateLimiter (via Server.WithAlertRateLimiter) to share the limit between all API instances, so that the configured rate is the total cap per channel.

type ChannelInfo

type ChannelInfo struct {
	Name               string
	ChannelExists      bool
	ChannelIsArchived  bool
	ChannelIsReadOnly  bool
	ManagerIsInChannel bool
	UserCount          int
}

ChannelInfo contains information about a Slack channel. Returned by ChannelInfoProvider.GetChannelInfo.

type ChannelInfoProvider

type ChannelInfoProvider interface {
	// GetChannelInfo returns [ChannelInfo] for the given Slack channel ID. The result
	// is served from an internal cache and refreshed periodically in the background.
	// A cache miss triggers a direct Slack API lookup.
	GetChannelInfo(ctx context.Context, channel string) (*ChannelInfo, error)

	// MapChannelNameToIDIfNeeded converts a human-readable channel name (e.g. "alerts")
	// to its Slack channel ID. If the input is already a channel ID, it is returned
	// unchanged. This allows alert clients to use either form interchangeably.
	MapChannelNameToIDIfNeeded(channelName string) string

	// ManagedChannels returns the current list of Slack channels the bot is a member of.
	ManagedChannels() []*internal.ChannelSummary
}

ChannelInfoProvider supplies Slack channel metadata to the Server for request validation and channel listing.

type FifoQueueConsumer

type FifoQueueConsumer interface {
	Receive(ctx context.Context, sinkCh chan<- *types.FifoQueueItem) error
}

FifoQueueConsumer is the read side of a FIFO queue. It is used by the Server to consume raw alert items delivered outside of the HTTP API (e.g. via a secondary SQS or Redis Streams queue registered with Server.WithRawAlertConsumer).

type FifoQueueProducer

type FifoQueueProducer interface {
	Send(ctx context.Context, slackChannelID, dedupID, body string) error
}

FifoQueueProducer is the write side of a FIFO queue. The Server uses it to dispatch processed alerts to the Manager for issue lifecycle handling.

type Hooks added in v0.9.1

type Hooks struct {
	// OnStartup is called once after Slack connects and channel info is
	// initialized, but before the TCP listener opens. Signals the end of the
	// startup phase — the process is past initialization but not yet accepting
	// traffic. Use it to pass a startup probe and enable a liveness probe.
	OnStartup func()

	// OnReady is called once after net.Listen succeeds and the TCP port is
	// bound. At this point the server is accepting HTTP connections. Use it
	// to pass a readiness probe.
	OnReady func()

	// OnNotReady is called when shutdown begins (context cancelled), before
	// srv.Close() drains in-flight connections. Flip your readiness flag here
	// so the load balancer stops routing traffic before connections are torn
	// down.
	OnNotReady func()

	// OnShutdown is called once when [Server.Run] returns, regardless of
	// whether shutdown was caused by context cancellation or a fatal error.
	// Use it to flip your liveness flag to false.
	OnShutdown func()
}

Hooks contains optional lifecycle callbacks for use with Kubernetes probe endpoints. All fields are optional; nil functions are silently skipped. Wire these to your own probe HTTP server — the library does not serve probes.

Typical Kubernetes probe mapping:

startupProbe:   set a flag to true in [Hooks.OnStartup]
livenessProbe:  set a flag to true in [Hooks.OnStartup], false in [Hooks.OnShutdown]
readinessProbe: set a flag to true in [Hooks.OnReady], false in [Hooks.OnNotReady]

Register hooks via Server.WithHooks before calling Server.Run.

type LocalAlertRateLimiter added in v0.27.0

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

LocalAlertRateLimiter is an in-process AlertRateLimiter. Each API instance has its own buckets, so with N instances the effective limit per channel is up to N times the configured limit. Use RedisAlertRateLimiter for multi-instance deployments.

Buckets of idle channels are removed once they are full again, so memory use is bounded by the number of recently active channels.

func NewLocalAlertRateLimiter added in v0.27.0

func NewLocalAlertRateLimiter() *LocalAlertRateLimiter

NewLocalAlertRateLimiter creates a LocalAlertRateLimiter.

func (*LocalAlertRateLimiter) TakeAll added in v0.29.0

TakeAll implements AlertRateLimiter. It never returns an error.

type PrometheusAlert

type PrometheusAlert struct {
	Status       string            `json:"status,omitempty"`
	Labels       map[string]string `json:"labels,omitempty"`
	Annotations  map[string]string `json:"annotations,omitempty"`
	StartsAt     time.Time         `json:"startsAt"`
	EndsAt       time.Time         `json:"endsAt"`
	GeneratorURL string            `json:"generatorURL,omitempty"` //nolint:tagliatelle
	Fingerprint  string            `json:"fingerprint,omitempty"`
}

PrometheusAlert is a single alert entry within a PrometheusWebhook payload.

type PrometheusWebhook

type PrometheusWebhook struct {
	Version           string             `json:"version,omitempty"`
	GroupKey          string             `json:"groupKey,omitempty"`
	TruncatedAlerts   int                `json:"truncatedAlerts,omitempty"`
	Status            string             `json:"status,omitempty"`
	Receiver          string             `json:"receiver,omitempty"`
	GroupLabels       map[string]string  `json:"groupLabels,omitempty"`
	CommonLabels      map[string]string  `json:"commonLabels,omitempty"`
	CommonAnnotations map[string]string  `json:"commonAnnotations,omitempty"`
	ExternalURL       string             `json:"externalURL,omitempty"` //nolint:tagliatelle
	Alerts            []*PrometheusAlert `json:"alerts,omitempty"`
}

PrometheusWebhook is the JSON payload sent by Prometheus Alertmanager to the /prometheus-alert endpoint. It follows the Alertmanager webhook v4 format. Each payload contains one or more PrometheusAlert entries in the Alerts field.

type RateLimitResult added in v0.27.0

type RateLimitResult struct {
	// Allowed is true if the tokens were taken (for all channels of the call).
	Allowed bool

	// Remaining is the number of whole tokens left in the bucket after the call.
	Remaining int

	// RetryAfter is how long to wait until the channel has enough tokens. It is only set when
	// Allowed is false, and the channel has too few tokens. It is capped at 24 hours when the
	// tokens can never be available (the count is larger than the burst).
	RetryAfter time.Duration

	// Reset is how long until the bucket is full again.
	Reset time.Duration
}

RateLimitResult is the outcome of an AlertRateLimiter.TakeAll call for one channel.

type RedisAlertRateLimiter added in v0.27.0

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

RedisAlertRateLimiter is an AlertRateLimiter backed by Redis. All API instances using the same Redis and key prefix share the token bucket of each channel, so the configured rate limit is the total cap per channel, regardless of the number of instances.

Each check is a single atomic Lua script call for all channels of a request (one round trip per request). The Redis server time is used, so clock skew between instances does not matter. The keys share the hash tag {alert-rate-limit}, so that the script can access the keys of several channels on Redis Cluster; all buckets are therefore stored on the same cluster node. Requires Redis 5 or later (or a compatible server, such as Valkey).

func NewRedisAlertRateLimiter added in v0.27.0

func NewRedisAlertRateLimiter(client redis.UniversalClient, keyPrefix string) *RedisAlertRateLimiter

NewRedisAlertRateLimiter creates a RedisAlertRateLimiter. The bucket of a channel is stored under the key <keyPrefix>{alert-rate-limit}:<channel>. An empty keyPrefix defaults to config.DefaultKeyPrefix.

func (*RedisAlertRateLimiter) TakeAll added in v0.29.0

TakeAll implements AlertRateLimiter. It returns an error if Redis is unavailable or returns an unexpected reply.

type Server

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

Server is the Slack Manager REST API server. It accepts alerts from external monitoring systems, applies per-channel token-bucket rate limiting, and enqueues them for the Manager to process into Slack issues.

Create a Server with New and start it with Server.Run. API settings can be updated at runtime via Server.UpdateSettings without restarting the service.

func New

func New(alertQueue FifoQueueProducer, logger types.Logger, cfg *config.APIConfig) *Server

New creates a Server with the three required dependencies.

Optional dependencies can be configured via method chaining before calling Server.Run:

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run starts the HTTP server and handles incoming requests. It also initializes the Slack API client and the channel info syncer. If raw alert consumers are set, it will start dedicated consumers for those queues.

This method blocks until the context is cancelled, or a server error occurs.

func (*Server) UpdateSettings

func (s *Server) UpdateSettings(settings *config.APISettings) error

UpdateSettings hot-reloads API settings without restarting. It is safe to call concurrently with request handling. The new settings are validated before being applied; if validation fails the existing settings remain active and an error is returned. Passing nil replaces the current settings with zero-value defaults.

func (*Server) WithAlertRateLimiter added in v0.27.0

func (s *Server) WithAlertRateLimiter(limiter AlertRateLimiter) *Server

WithAlertRateLimiter sets the per-channel alert rate limiter. If not called, a LocalAlertRateLimiter is used, which limits each API instance separately. Use a RedisAlertRateLimiter to make APIConfig.RateLimitPerAlertChannel the total cap per channel across all API instances. Passing nil is a no-op.

If the rate limiter returns an error, the alerts are allowed (fail open), the error is logged, and the http_alert_rate_limiter_errors_total metric is incremented.

func (*Server) WithCacheStore added in v0.5.0

func (s *Server) WithCacheStore(cacheStore cachestore.StoreInterface) *Server

WithCacheStore sets the cache store. If not called, Server.Run defaults to an in-process go-cache instance (unsuitable for multi-instance deployments that require shared channel-info caching). Passing nil is a no-op.

func (*Server) WithHooks added in v0.9.0

func (s *Server) WithHooks(hooks Hooks) *Server

WithHooks registers optional lifecycle callbacks for startup, readiness, and shutdown probe support. See Hooks for the available hooks and when they fire.

func (*Server) WithInsightsSink added in v0.16.0

func (s *Server) WithInsightsSink(sink types.InsightsSink) *Server

WithInsightsSink sets a sink for alert intake insights events (queued, filtered and rejected alerts). If not called, the server records no insights events. Recording can be disabled with APIConfig.Insights.Disabled. Passing nil is a no-op.

Insights recording never blocks or slows down request handling; see the insights package for details.

func (*Server) WithMetrics added in v0.5.0

func (s *Server) WithMetrics(metrics types.Metrics) *Server

WithMetrics sets the metrics implementation. If not called, a no-op implementation is used. Passing nil is a no-op.

func (*Server) WithRawAlertConsumer

func (s *Server) WithRawAlertConsumer(consumer FifoQueueConsumer) *Server

WithRawAlertConsumer registers a FifoQueueConsumer that reads alerts outside of the HTTP API (e.g. from SQS or Redis Streams). The consumer is started by Server.Run in a dedicated goroutine.

Multiple raw alert consumers can be added.

The server can receive alerts from both the main rest API and the raw alert consumers simultaneously.

The queue item body must be a single JSON-serialized types.Alert. Prometheus webhooks are not supported here.

func (*Server) WithSettings added in v0.5.0

func (s *Server) WithSettings(settings *config.APISettings) *Server

WithSettings sets the initial API settings. If not called, zero-value settings are used. For runtime updates after Server.Run is started, use Server.UpdateSettings instead. Passing nil is a no-op.

type SlackClient

type SlackClient interface {
	GetChannelInfo(ctx context.Context, channelID string) (*slack.Channel, error)
	GetUserIDsInChannel(ctx context.Context, channelID string) (map[string]struct{}, error)
	BotIsInChannel(ctx context.Context, channelID string) (bool, error)
	ListBotChannels(ctx context.Context) ([]*internal.ChannelSummary, error)
}

SlackClient is the Slack API subset required by the Server for channel validation (membership checks, user counts) and for listing managed channels.

Jump to

Keyboard shortcuts

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