Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

4.5 KB
Raw Blame
package implrulestatehistory

import (
	"context"
	"encoding/json"
	"log/slog"
	"time"

	"github.com/SigNoz/signoz/pkg/contextlinks"
	"github.com/SigNoz/signoz/pkg/errors"
	qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
	"github.com/SigNoz/signoz/pkg/types/rulestatehistorytypes"
	"github.com/SigNoz/signoz/pkg/types/ruletypes"
	"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
	"github.com/SigNoz/signoz/pkg/valuer"
)

// relatedLinkBuilder builds logs/traces explorer links that carry the rule's
// filter and the entry's labels, so a history entry can be opened in the
// explorer with the context that produced it.
type relatedLinkBuilder struct {
	alertType  ruletypes.AlertType
	signal     telemetrytypes.Signal
	evaluation ruletypes.Evaluation
	condition  *ruletypes.RuleCondition
	logger     *slog.Logger
}

// relatedLinkBuilderForRule returns nil when the rule cannot be loaded or is
// not a logs/traces rule; callers then leave the links empty.
func (m *module) relatedLinkBuilderForRule(ctx context.Context, orgID valuer.UUID, ruleID string) *relatedLinkBuilder {
	id, err := valuer.NewUUID(ruleID)
	if err != nil {
		return nil
	}

	storableRule, err := m.ruleStore.GetStoredRule(ctx, orgID, id)
	if err != nil {
		return nil
	}

	rule := ruletypes.PostableRule{}
	if err := json.Unmarshal([]byte(storableRule.Data), &rule); err != nil {
		return nil
	}

	signal, ok := relatedLinkSignal(rule.AlertType)
	if !ok {
		return nil
	}
	if rule.RuleCondition == nil || rule.RuleCondition.CompositeQuery == nil {
		return nil
	}

	builder := &relatedLinkBuilder{alertType: rule.AlertType, signal: signal, condition: rule.RuleCondition, logger: m.logger.With(slog.String("rule.id", ruleID))}
	if rule.Evaluation != nil {
		if evaluation, err := rule.Evaluation.GetEvaluation(); err == nil {
			builder.evaluation = evaluation
		}
	}
	if builder.evaluation == nil {
		evalWindow := rule.EvalWindow
		if evalWindow.IsZero() {
			evalWindow = valuer.MustParseTextDuration("5m")
		}
		builder.evaluation = ruletypes.RollingWindow{EvalWindow: evalWindow}
	}

	return builder
}

// queryWindow returns the range the rule evaluated when it recorded a state
// change at unixMilli.
// why are we subtracting 3 minutes?
// the query range is calculated based on the rule's evaluation window and
// evalDelay; alerts have 2 minutes delay built in, so we need to subtract
// that from the start time to get the correct query range.
func (b *relatedLinkBuilder) queryWindow(unixMilli int64) (time.Time, time.Time) {
	start, end := b.evaluation.NextWindowFor(time.Unix(unixMilli/1000, 0))
	return start.Add(-3 * time.Minute), end
}

// links returns the explorer query params for the given entry labels and time
// range.
func (b *relatedLinkBuilder) links(ctx context.Context, labels rulestatehistorytypes.LabelsString, start, end time.Time) rulestatehistorytypes.RelatedLinks {
	lbls := map[string]string{}
	if err := json.Unmarshal([]byte(labels), &lbls); err != nil {
		return rulestatehistorytypes.RelatedLinks{}
	}

	// links are still built from the labels alone when the rule has no builder
	// query for the signal (e.g. ClickHouse SQL alerts)
	whereClause, _, err := contextlinks.PrepareRuleFilterExpression(b.condition, b.signal, lbls)
	if err != nil {
		b.logger.ErrorContext(ctx, "failed to prepare the filter for related links", errors.Attr(err))
		return rulestatehistorytypes.RelatedLinks{}
	}

	switch b.alertType {
	case ruletypes.AlertTypeLogs:
		return rulestatehistorytypes.RelatedLinks{RelatedLogsLink: contextlinks.PrepareParamsForLogsV5(start, end, whereClause).Encode()}
	case ruletypes.AlertTypeTraces:
		return rulestatehistorytypes.RelatedLinks{RelatedTracesLink: contextlinks.PrepareParamsForTracesV5(start, end, whereClause, qbtypes.QueryTypeBuilder).Encode()}
	case ruletypes.AlertTypeAITraces:
		return rulestatehistorytypes.RelatedLinks{RelatedAITracesLink: contextlinks.PrepareParamsForTracesV5(start, end, whereClause, qbtypes.QueryTypeBuilderAI).Encode()}
	}
	return rulestatehistorytypes.RelatedLinks{}
}

// relatedLinkSignal returns the explorer signal that related links open for
// the alert type, or ok=false when the alert type has none (e.g. metrics).
func relatedLinkSignal(alertType ruletypes.AlertType) (telemetrytypes.Signal, bool) {
	switch alertType {
	case ruletypes.AlertTypeLogs:
		return telemetrytypes.SignalLogs, true
	case ruletypes.AlertTypeTraces, ruletypes.AlertTypeAITraces:
		return telemetrytypes.SignalTraces, true
	}
	return telemetrytypes.SignalUnspecified, false
}