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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix(alerts): drop vulnerable v1 rule history endpoints (#12163)
Pandeyc2dd94f1905a
diff --git a/pkg/query-service/app/clickhouseReader/reader.go b/pkg/query-service/app/clickhouseReader/reader.goindex 5cb6622bcc..f02ba177ca 100644--- a/pkg/query-service/app/clickhouseReader/reader.go+++ b/pkg/query-service/app/clickhouseReader/reader.go@@ -62,8 +62,6 @@ const (primaryNamespace = "clickhouse"archiveNamespace = "clickhouse-archive"signozTraceDBName = "signoz_traces"- signozHistoryDBName = "signoz_analytics"- ruleStateHistoryTableName = "distributed_rule_state_history_v0"signozDurationMVTable = "distributed_durationSort"signozUsageExplorerTable = "distributed_usage_explorer"signozSpansTable = "distributed_signoz_spans"@@ -4484,483 +4482,6 @@ func (r *ClickHouseReader) GetSpanAttributeKeysByNames(ctx context.Context, namereturn response, nil}-func (r *ClickHouseReader) AddRuleStateHistory(ctx context.Context, ruleStateHistory []model.RuleStateHistory) error {- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "AddRuleStateHistory",- })- var statement driver.Batch- var err error-- defer func() {- if statement != nil {- statement.Abort()- }- }()-- statement, err = r.db.PrepareBatch(ctx, fmt.Sprintf("INSERT INTO %s.%s (rule_id, rule_name, overall_state, overall_state_changed, state, state_changed, unix_milli, labels, fingerprint, value) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",- signozHistoryDBName, ruleStateHistoryTableName))-- if err != nil {- return err- }-- for _, history := range ruleStateHistory {- err = statement.Append(history.RuleID, history.RuleName, history.OverallState, history.OverallStateChanged, history.State, history.StateChanged, history.UnixMilli, history.Labels, history.Fingerprint, history.Value)- if err != nil {- return err- }- }-- err = statement.Send()- if err != nil {- return err- }- return nil-}--func (r *ClickHouseReader) GetLastSavedRuleStateHistory(ctx context.Context, ruleID string) ([]model.RuleStateHistory, error) {- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "GetLastSavedRuleStateHistory",- })- query := fmt.Sprintf("SELECT * FROM %s.%s WHERE rule_id = '%s' AND state_changed = true ORDER BY unix_milli DESC LIMIT 1 BY fingerprint",- signozHistoryDBName, ruleStateHistoryTableName, ruleID)-- history := []model.RuleStateHistory{}- err := r.db.Select(ctx, &history, query)- if err != nil {- return nil, err- }- return history, nil-}--func (r *ClickHouseReader) ReadRuleStateHistoryByRuleID(- ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (*model.RuleStateTimeline, error) {-- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "ReadRuleStateHistoryByRuleID",- })- var conditions []string-- conditions = append(conditions, fmt.Sprintf("rule_id = '%s'", ruleID))-- conditions = append(conditions, fmt.Sprintf("unix_milli >= %d AND unix_milli < %d", params.Start, params.End))-- if params.State != "" {- conditions = append(conditions, fmt.Sprintf("state = '%s'", params.State))- }-- if params.Filters != nil && len(params.Filters.Items) != 0 {- for _, item := range params.Filters.Items {- toFormat := item.Value- op := v3.FilterOperator(strings.ToLower(strings.TrimSpace(string(item.Operator))))- if op == v3.FilterOperatorContains || op == v3.FilterOperatorNotContains {- toFormat = fmt.Sprintf("%%%s%%", toFormat)- }- fmtVal := utils.ClickHouseFormattedValue(toFormat)- switch op {- case v3.FilterOperatorEqual:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') = %s", item.Key.Key, fmtVal))- case v3.FilterOperatorNotEqual:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') != %s", item.Key.Key, fmtVal))- case v3.FilterOperatorIn:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') IN %s", item.Key.Key, fmtVal))- case v3.FilterOperatorNotIn:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') NOT IN %s", item.Key.Key, fmtVal))- case v3.FilterOperatorLike:- conditions = append(conditions, fmt.Sprintf("like(JSONExtractString(labels, '%s'), %s)", item.Key.Key, fmtVal))- case v3.FilterOperatorNotLike:- conditions = append(conditions, fmt.Sprintf("notLike(JSONExtractString(labels, '%s'), %s)", item.Key.Key, fmtVal))- case v3.FilterOperatorRegex:- conditions = append(conditions, fmt.Sprintf("match(JSONExtractString(labels, '%s'), %s)", item.Key.Key, fmtVal))- case v3.FilterOperatorNotRegex:- conditions = append(conditions, fmt.Sprintf("not match(JSONExtractString(labels, '%s'), %s)", item.Key.Key, fmtVal))- case v3.FilterOperatorGreaterThan:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') > %s", item.Key.Key, fmtVal))- case v3.FilterOperatorGreaterThanOrEq:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') >= %s", item.Key.Key, fmtVal))- case v3.FilterOperatorLessThan:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') < %s", item.Key.Key, fmtVal))- case v3.FilterOperatorLessThanOrEq:- conditions = append(conditions, fmt.Sprintf("JSONExtractString(labels, '%s') <= %s", item.Key.Key, fmtVal))- case v3.FilterOperatorContains:- conditions = append(conditions, fmt.Sprintf("like(JSONExtractString(labels, '%s'), %s)", item.Key.Key, fmtVal))- case v3.FilterOperatorNotContains:- conditions = append(conditions, fmt.Sprintf("notLike(JSONExtractString(labels, '%s'), %s)", item.Key.Key, fmtVal))- case v3.FilterOperatorExists:- conditions = append(conditions, fmt.Sprintf("has(JSONExtractKeys(labels), '%s')", item.Key.Key))- case v3.FilterOperatorNotExists:- conditions = append(conditions, fmt.Sprintf("not has(JSONExtractKeys(labels), '%s')", item.Key.Key))- default:- return nil, fmt.Errorf("unsupported filter operator")- }- }- }- whereClause := strings.Join(conditions, " AND ")-- query := fmt.Sprintf("SELECT * FROM %s.%s WHERE %s ORDER BY unix_milli %s LIMIT %d OFFSET %d",- signozHistoryDBName, ruleStateHistoryTableName, whereClause, params.Order, params.Limit, params.Offset)-- history := []model.RuleStateHistory{}- r.logger.Debug("rule state history query", "query", query)- err := r.db.Select(ctx, &history, query)- if err != nil {- r.logger.Error("Error while reading rule state history", errorsV2.Attr(err))- return nil, err- }-- var total uint64- r.logger.Debug("rule state history total query", "query", fmt.Sprintf("SELECT count(*) FROM %s.%s WHERE %s",- signozHistoryDBName, ruleStateHistoryTableName, whereClause))- err = r.db.QueryRow(ctx, fmt.Sprintf("SELECT count(*) FROM %s.%s WHERE %s",- signozHistoryDBName, ruleStateHistoryTableName, whereClause)).Scan(&total)- if err != nil {- return nil, err- }-- labelsQuery := fmt.Sprintf("SELECT DISTINCT labels FROM %s.%s WHERE rule_id = $1",- signozHistoryDBName, ruleStateHistoryTableName)- rows, err := r.db.Query(ctx, labelsQuery, ruleID)- if err != nil {- return nil, err- }- defer rows.Close()-- labelsMap := make(map[string][]string)- for rows.Next() {- var rawLabel string- err = rows.Scan(&rawLabel)- if err != nil {- return nil, err- }- label := map[string]string{}- err = json.Unmarshal([]byte(rawLabel), &label)- if err != nil {- return nil, err- }- for k, v := range label {- labelsMap[k] = append(labelsMap[k], v)- }- }-- timeline := &model.RuleStateTimeline{- Items: history,- Total: total,- Labels: labelsMap,- }-- return timeline, nil-}--func (r *ClickHouseReader) ReadRuleStateHistoryTopContributorsByRuleID(- ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) ([]model.RuleStateHistoryContributor, error) {- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "ReadRuleStateHistoryTopContributorsByRuleID",- })- query := fmt.Sprintf(`SELECT- fingerprint,- any(labels) as labels,- count(*) as count- FROM %s.%s- WHERE rule_id = '%s' AND (state_changed = true) AND (state = '%s') AND unix_milli >= %d AND unix_milli <= %d- GROUP BY fingerprint- HAVING labels != '{}'- ORDER BY count DESC`,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, model.StateFiring.String(), params.Start, params.End)-- r.logger.Debug("rule state history top contributors query", "query", query)- contributors := []model.RuleStateHistoryContributor{}- err := r.db.Select(ctx, &contributors, query)- if err != nil {- r.logger.Error("Error while reading rule state history", errorsV2.Attr(err))- return nil, err- }-- return contributors, nil-}--func (r *ClickHouseReader) GetOverallStateTransitions(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) ([]model.ReleStateItem, error) {-- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "GetOverallStateTransitions",- })- tmpl := `WITH firing_events AS (- SELECT- rule_id,- state,- unix_milli AS firing_time- FROM %s.%s- WHERE overall_state = '` + model.StateFiring.String() + `'- AND overall_state_changed = true- AND rule_id IN ('%s')- AND unix_milli >= %d AND unix_milli <= %d-),-resolution_events AS (- SELECT- rule_id,- state,- unix_milli AS resolution_time- FROM %s.%s- WHERE overall_state = '` + model.StateInactive.String() + `'- AND overall_state_changed = true- AND rule_id IN ('%s')- AND unix_milli >= %d AND unix_milli <= %d-),-matched_events AS (- SELECT- f.rule_id,- f.state,- f.firing_time,- MIN(r.resolution_time) AS resolution_time- FROM firing_events f- LEFT JOIN resolution_events r- ON f.rule_id = r.rule_id- WHERE r.resolution_time > f.firing_time- GROUP BY f.rule_id, f.state, f.firing_time-)-SELECT *-FROM matched_events-ORDER BY firing_time ASC;`-- query := fmt.Sprintf(tmpl,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.Start, params.End,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.Start, params.End)-- r.logger.Debug("overall state transitions query", "query", query)-- transitions := []model.RuleStateTransition{}- err := r.db.Select(ctx, &transitions, query)- if err != nil {- return nil, err- }-- stateItems := []model.ReleStateItem{}-- for idx, item := range transitions {- start := item.FiringTime- end := item.ResolutionTime- stateItems = append(stateItems, model.ReleStateItem{- State: item.State,- Start: start,- End: end,- })- if idx < len(transitions)-1 {- nextStart := transitions[idx+1].FiringTime- if nextStart > end {- stateItems = append(stateItems, model.ReleStateItem{- State: model.StateInactive,- Start: end,- End: nextStart,- })- }- }- }-- // fetch the most recent overall_state from the table- var state model.AlertState- stateQuery := fmt.Sprintf("SELECT state FROM %s.%s WHERE rule_id = '%s' AND unix_milli <= %d ORDER BY unix_milli DESC LIMIT 1",- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.End)- if err := r.db.QueryRow(ctx, stateQuery).Scan(&state); err != nil {- if err != sql.ErrNoRows {- return nil, err- }- state = model.StateInactive- }-- if len(transitions) == 0 {- // no transitions found, it is either firing or inactive for whole time range- stateItems = append(stateItems, model.ReleStateItem{- State: state,- Start: params.Start,- End: params.End,- })- } else {- // there were some transitions, we need to add the last state at the end- if state == model.StateInactive {- stateItems = append(stateItems, model.ReleStateItem{- State: model.StateInactive,- Start: transitions[len(transitions)-1].ResolutionTime,- End: params.End,- })- } else {- // fetch the most recent firing event from the table in the given time range- var firingTime int64- firingQuery := fmt.Sprintf(`- SELECT- unix_milli- FROM %s.%s- WHERE rule_id = '%s' AND overall_state_changed = true AND overall_state = '%s' AND unix_milli <= %d- ORDER BY unix_milli DESC LIMIT 1`, signozHistoryDBName, ruleStateHistoryTableName, ruleID, model.StateFiring.String(), params.End)- if err := r.db.QueryRow(ctx, firingQuery).Scan(&firingTime); err != nil {- return nil, err- }- stateItems = append(stateItems, model.ReleStateItem{- State: model.StateInactive,- Start: transitions[len(transitions)-1].ResolutionTime,- End: firingTime,- })- stateItems = append(stateItems, model.ReleStateItem{- State: model.StateFiring,- Start: firingTime,- End: params.End,- })- }- }- return stateItems, nil-}--func (r *ClickHouseReader) GetAvgResolutionTime(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (float64, error) {-- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "GetAvgResolutionTime",- })- tmpl := `-WITH firing_events AS (- SELECT- rule_id,- state,- unix_milli AS firing_time- FROM %s.%s- WHERE overall_state = '` + model.StateFiring.String() + `'- AND overall_state_changed = true- AND rule_id IN ('%s')- AND unix_milli >= %d AND unix_milli <= %d-),-resolution_events AS (- SELECT- rule_id,- state,- unix_milli AS resolution_time- FROM %s.%s- WHERE overall_state = '` + model.StateInactive.String() + `'- AND overall_state_changed = true- AND rule_id IN ('%s')- AND unix_milli >= %d AND unix_milli <= %d-),-matched_events AS (- SELECT- f.rule_id,- f.state,- f.firing_time,- MIN(r.resolution_time) AS resolution_time- FROM firing_events f- LEFT JOIN resolution_events r- ON f.rule_id = r.rule_id- WHERE r.resolution_time > f.firing_time- GROUP BY f.rule_id, f.state, f.firing_time-)-SELECT AVG(resolution_time - firing_time) / 1000 AS avg_resolution_time-FROM matched_events;-`-- query := fmt.Sprintf(tmpl,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.Start, params.End,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.Start, params.End)-- r.logger.Debug("avg resolution time query", "query", query)- var avgResolutionTime float64- err := r.db.QueryRow(ctx, query).Scan(&avgResolutionTime)- if err != nil {- return 0, err- }-- return avgResolutionTime, nil-}--func (r *ClickHouseReader) GetAvgResolutionTimeByInterval(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (*v3.Series, error) {-- step := common.MinAllowedStepInterval(params.Start, params.End)-- tmpl := `-WITH firing_events AS (- SELECT- rule_id,- state,- unix_milli AS firing_time- FROM %s.%s- WHERE overall_state = '` + model.StateFiring.String() + `'- AND overall_state_changed = true- AND rule_id IN ('%s')- AND unix_milli >= %d AND unix_milli <= %d-),-resolution_events AS (- SELECT- rule_id,- state,- unix_milli AS resolution_time- FROM %s.%s- WHERE overall_state = '` + model.StateInactive.String() + `'- AND overall_state_changed = true- AND rule_id IN ('%s')- AND unix_milli >= %d AND unix_milli <= %d-),-matched_events AS (- SELECT- f.rule_id,- f.state,- f.firing_time,- MIN(r.resolution_time) AS resolution_time- FROM firing_events f- LEFT JOIN resolution_events r- ON f.rule_id = r.rule_id- WHERE r.resolution_time > f.firing_time- GROUP BY f.rule_id, f.state, f.firing_time-)-SELECT toStartOfInterval(toDateTime(firing_time / 1000), INTERVAL %d SECOND) AS ts, AVG(resolution_time - firing_time) / 1000 AS avg_resolution_time-FROM matched_events-GROUP BY ts-ORDER BY ts ASC;`-- query := fmt.Sprintf(tmpl,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.Start, params.End,- signozHistoryDBName, ruleStateHistoryTableName, ruleID, params.Start, params.End, step)-- r.logger.Debug("avg resolution time by interval query", "query", query)- result, err := r.GetTimeSeriesResultV3(ctx, query)- if err != nil || len(result) == 0 {- return nil, err- }-- return result[0], nil-}--func (r *ClickHouseReader) GetTotalTriggers(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (uint64, error) {- ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{- instrumentationtypes.CodeNamespace: "clickhouse-reader",- instrumentationtypes.CodeFunctionName: "GetTotalTriggers",- })- query := fmt.Sprintf("SELECT count(*) FROM %s.%s WHERE rule_id = '%s' AND (state_changed = true) AND (state = '%s') AND unix_milli >= %d AND unix_milli <= %d",- signozHistoryDBName, ruleStateHistoryTableName, ruleID, model.StateFiring.String(), params.Start, params.End)-- var totalTriggers uint64-- err := r.db.QueryRow(ctx, query).Scan(&totalTriggers)- if err != nil {- return 0, err- }-- return totalTriggers, nil-}--func (r *ClickHouseReader) GetTriggersByInterval(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (*v3.Series, error) {- step := common.MinAllowedStepInterval(params.Start, params.End)-- query := fmt.Sprintf("SELECT count(*), toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), INTERVAL %d SECOND) as ts FROM %s.%s WHERE rule_id = '%s' AND (state_changed = true) AND (state = '%s') AND unix_milli >= %d AND unix_milli <= %d GROUP BY ts ORDER BY ts ASC",- step, signozHistoryDBName, ruleStateHistoryTableName, ruleID, model.StateFiring.String(), params.Start, params.End)-- result, err := r.GetTimeSeriesResultV3(ctx, query)- if err != nil || len(result) == 0 {- return nil, err- }-- return result[0], nil-}-func (r *ClickHouseReader) GetMinAndMaxTimestampForTraceID(ctx context.Context, traceID []string) (int64, int64, error) {ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{instrumentationtypes.TelemetrySignal: telemetrytypes.SignalTraces.StringValue(),diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.goindex 87a1612479..2ad44e6bde 100644--- a/pkg/query-service/app/http_handler.go+++ b/pkg/query-service/app/http_handler.go@@ -15,7 +15,6 @@ import ("github.com/SigNoz/signoz/pkg/queryparser""log/slog"- "math""net/http""regexp""slices"@@ -39,7 +38,6 @@ import (jsoniter "github.com/json-iterator/go"_ "modernc.org/sqlite"- "github.com/SigNoz/signoz/pkg/contextlinks"traceFunnelsModule "github.com/SigNoz/signoz/pkg/modules/tracefunnel""github.com/SigNoz/signoz/pkg/query-service/agentConf"queues2 "github.com/SigNoz/signoz/pkg/query-service/app/integrations/messagingQueues/queues"@@ -64,7 +62,6 @@ import ("github.com/SigNoz/signoz/pkg/types/opamptypes""github.com/SigNoz/signoz/pkg/types/pipelinetypes"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"- "github.com/SigNoz/signoz/pkg/types/ruletypes"traceFunnels "github.com/SigNoz/signoz/pkg/types/tracefunneltypes""github.com/SigNoz/signoz/pkg/query-service/app/integrations/messagingQueues/kafka"@@ -370,10 +367,6 @@ func (aH *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {router.HandleFunc("/api/v1/rules/{id}", am.EditAccess(aH.deleteRule)).Methods(http.MethodDelete)router.HandleFunc("/api/v1/rules/{id}", am.EditAccess(aH.patchRule)).Methods(http.MethodPatch)router.HandleFunc("/api/v1/testRule", am.EditAccess(aH.testRule)).Methods(http.MethodPost)- router.HandleFunc("/api/v1/rules/{id}/history/stats", am.ViewAccess(aH.getRuleStats)).Methods(http.MethodPost)- router.HandleFunc("/api/v1/rules/{id}/history/timeline", am.ViewAccess(aH.getRuleStateHistory)).Methods(http.MethodPost)- router.HandleFunc("/api/v1/rules/{id}/history/top_contributors", am.ViewAccess(aH.getRuleStateHistoryTopContributors)).Methods(http.MethodPost)- router.HandleFunc("/api/v1/rules/{id}/history/overall_status", am.ViewAccess(aH.getOverallStateTransitions)).Methods(http.MethodPost)router.HandleFunc("/api/v2/variables/query", am.ViewAccess(aH.queryDashboardVarsV2)).Methods(http.MethodPost)@@ -663,217 +656,6 @@ func (aH *APIHandler) testRule(w http.ResponseWriter, r *http.Request) {aH.Respond(w, response)}-func (aH *APIHandler) getRuleStats(w http.ResponseWriter, r *http.Request) {- ruleID := mux.Vars(r)["id"]- params := model.QueryRuleStateHistory{}- err := json.NewDecoder(r.Body).Decode(¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }-- totalCurrentTriggers, err := aH.reader.GetTotalTriggers(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }- currentTriggersSeries, err := aH.reader.GetTriggersByInterval(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }-- currentAvgResolutionTime, err := aH.reader.GetAvgResolutionTime(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }- currentAvgResolutionTimeSeries, err := aH.reader.GetAvgResolutionTimeByInterval(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }-- if params.End-params.Start >= 86400000 {- days := int64(math.Ceil(float64(params.End-params.Start) / 86400000))- params.Start -= days * 86400000- params.End -= days * 86400000- } else {- params.Start -= 86400000- params.End -= 86400000- }-- totalPastTriggers, err := aH.reader.GetTotalTriggers(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }- pastTriggersSeries, err := aH.reader.GetTriggersByInterval(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }-- pastAvgResolutionTime, err := aH.reader.GetAvgResolutionTime(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }- pastAvgResolutionTimeSeries, err := aH.reader.GetAvgResolutionTimeByInterval(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }- if math.IsNaN(currentAvgResolutionTime) || math.IsInf(currentAvgResolutionTime, 0) {- currentAvgResolutionTime = 0- }- if math.IsNaN(pastAvgResolutionTime) || math.IsInf(pastAvgResolutionTime, 0) {- pastAvgResolutionTime = 0- }-- stats := model.Stats{- TotalCurrentTriggers: totalCurrentTriggers,- TotalPastTriggers: totalPastTriggers,- CurrentTriggersSeries: currentTriggersSeries,- PastTriggersSeries: pastTriggersSeries,- CurrentAvgResolutionTime: strconv.FormatFloat(currentAvgResolutionTime, 'f', -1, 64),- PastAvgResolutionTime: strconv.FormatFloat(pastAvgResolutionTime, 'f', -1, 64),- CurrentAvgResolutionTimeSeries: currentAvgResolutionTimeSeries,- PastAvgResolutionTimeSeries: pastAvgResolutionTimeSeries,- }-- aH.Respond(w, stats)-}--func (aH *APIHandler) getOverallStateTransitions(w http.ResponseWriter, r *http.Request) {- ruleID := mux.Vars(r)["id"]- params := model.QueryRuleStateHistory{}- err := json.NewDecoder(r.Body).Decode(¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }-- stateItems, err := aH.reader.GetOverallStateTransitions(r.Context(), ruleID, ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }-- aH.Respond(w, stateItems)-}--func (aH *APIHandler) getRuleStateHistory(w http.ResponseWriter, r *http.Request) {- idStr := mux.Vars(r)["id"]- id, err := valuer.NewUUID(idStr)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }-- params := model.QueryRuleStateHistory{}- err = json.NewDecoder(r.Body).Decode(¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }- if err := params.Validate(); err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }-- res, err := aH.reader.ReadRuleStateHistoryByRuleID(r.Context(), id.StringValue(), ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }-- rule, err := aH.ruleManager.GetRule(r.Context(), id)- if err == nil {- for idx := range res.Items {- lbls := make(map[string]string)- err := json.Unmarshal([]byte(res.Items[idx].Labels), &lbls)- if err != nil {- continue- }- end := time.Unix(res.Items[idx].UnixMilli/1000, 0)- // why are we subtracting 3 minutes?- // the query range is calculated based on the rule's evalWindow 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- start := end.Add(-rule.EvalWindow.Duration() - 3*time.Minute)- if rule.AlertType == ruletypes.AlertTypeLogs {- // TODO(srikanthccv): re-visit this and support multiple queries- var q qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]-- for _, query := range rule.RuleCondition.CompositeQuery.Queries {- if query.Type == qbtypes.QueryTypeBuilder {- switch spec := query.Spec.(type) {- case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:- q = spec- }- }- }-- filterExpr := ""- if q.Filter != nil && q.Filter.Expression != "" {- filterExpr = q.Filter.Expression- }-- whereClause := contextlinks.PrepareFilterExpression(lbls, filterExpr, q.GroupBy)-- res.Items[idx].RelatedLogsLink = contextlinks.PrepareParamsForLogsV5(start, end, whereClause).Encode()- } else if rule.AlertType == ruletypes.AlertTypeTraces || rule.AlertType == ruletypes.AlertTypeAITraces {- // TODO(srikanthccv): re-visit this and support multiple queries- var q qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]-- for _, query := range rule.RuleCondition.CompositeQuery.Queries {- if query.Type == qbtypes.QueryTypeBuilder || query.Type == qbtypes.QueryTypeBuilderAI {- switch spec := query.Spec.(type) {- case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:- q = spec- }- }- }-- filterExpr := ""- if q.Filter != nil && q.Filter.Expression != "" {- filterExpr = q.Filter.Expression- }-- whereClause := contextlinks.PrepareFilterExpression(lbls, filterExpr, q.GroupBy)- res.Items[idx].RelatedTracesLink = contextlinks.PrepareParamsForTracesV5(start, end, whereClause, rule.AlertType.BuilderQueryType()).Encode()- }- }- }-- aH.Respond(w, res)-}--func (aH *APIHandler) getRuleStateHistoryTopContributors(w http.ResponseWriter, r *http.Request) {- idStr := mux.Vars(r)["id"]- id, err := valuer.NewUUID(idStr)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }-- params := model.QueryRuleStateHistory{}- err = json.NewDecoder(r.Body).Decode(¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, nil)- return- }-- res, err := aH.reader.ReadRuleStateHistoryTopContributorsByRuleID(r.Context(), id.StringValue(), ¶ms)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorInternal, Err: err}, nil)- return- }-- aH.Respond(w, res)-}-func prepareQuery(r *http.Request) (string, error) {var postData *model.DashboardVarsdiff --git a/pkg/query-service/interfaces/interface.go b/pkg/query-service/interfaces/interface.goindex a2389c5ff4..bfef9f841f 100644--- a/pkg/query-service/interfaces/interface.go+++ b/pkg/query-service/interfaces/interface.go@@ -79,16 +79,6 @@ type Reader interface {GetMetricMetadata(context.Context, valuer.UUID, string, string) (*v3.MetricMetadataResponse, error)- AddRuleStateHistory(ctx context.Context, ruleStateHistory []model.RuleStateHistory) error- GetOverallStateTransitions(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) ([]model.ReleStateItem, error)- ReadRuleStateHistoryByRuleID(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (*model.RuleStateTimeline, error)- GetTotalTriggers(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (uint64, error)- GetTriggersByInterval(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (*v3.Series, error)- GetAvgResolutionTime(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (float64, error)- GetAvgResolutionTimeByInterval(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) (*v3.Series, error)- ReadRuleStateHistoryTopContributorsByRuleID(ctx context.Context, ruleID string, params *model.QueryRuleStateHistory) ([]model.RuleStateHistoryContributor, error)- GetLastSavedRuleStateHistory(ctx context.Context, ruleID string) ([]model.RuleStateHistory, error)-GetMinAndMaxTimestampForTraceID(ctx context.Context, traceID []string) (int64, int64, error)//tracediff --git a/pkg/query-service/model/alerting.go b/pkg/query-service/model/alerting.godeleted file mode 100644index ce77fe39b6..0000000000--- a/pkg/query-service/model/alerting.go+++ /dev/null@@ -1,202 +0,0 @@-package model--import (- "database/sql/driver"- "encoding/json"- "fmt"-- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/pkg/errors"-)--// AlertState denotes the state of an active alert.-type AlertState int--// The enum values are ordered by priority (lowest to highest).-// When determining overall rule state, higher numeric values take precedence.-const (- StateInactive AlertState = iota- StatePending- StateRecovering- StateFiring- StateNoData- StateDisabled-)--func (s AlertState) String() string {- switch s {- case StateInactive:- return "inactive"- case StatePending:- return "pending"- case StateFiring:- return "firing"- case StateNoData:- return "nodata"- case StateDisabled:- return "disabled"- case StateRecovering:- return "recovering"- }- panic(errors.Errorf("unknown alert state: %d", s))-}--func (s AlertState) MarshalJSON() ([]byte, error) {- return json.Marshal(s.String())-}--func (s *AlertState) UnmarshalJSON(b []byte) error {- var v interface{}- if err := json.Unmarshal(b, &v); err != nil {- return err- }- switch value := v.(type) {- case string:- switch value {- case "inactive":- *s = StateInactive- case "pending":- *s = StatePending- case "firing":- *s = StateFiring- case "nodata":- *s = StateNoData- case "disabled":- *s = StateDisabled- case "recovering":- *s = StateRecovering- default:- *s = StateInactive- }- return nil- default:- return errors.New("invalid alert state")- }-}--func (s *AlertState) Scan(value interface{}) error {- v, ok := value.(string)- if !ok {- return errors.New("invalid alert state")- }- switch v {- case "inactive":- *s = StateInactive- case "pending":- *s = StatePending- case "firing":- *s = StateFiring- case "nodata":- *s = StateNoData- case "disabled":- *s = StateDisabled- case "recovering":- *s = StateRecovering- }- return nil-}--func (s *AlertState) Value() (driver.Value, error) {- return s.String(), nil-}--type LabelsString string--func (l *LabelsString) MarshalJSON() ([]byte, error) {- lbls := make(map[string]string)- err := json.Unmarshal([]byte(*l), &lbls)- if err != nil {- return nil, err- }- return json.Marshal(lbls)-}--func (l *LabelsString) Scan(src interface{}) error {- if data, ok := src.(string); ok {- *l = LabelsString(data)- }- return nil-}--func (l LabelsString) String() string {- return string(l)-}--type RuleStateTimeline struct {- Items []RuleStateHistory `json:"items"`- Total uint64 `json:"total"`- Labels map[string][]string `json:"labels"`-}--type RuleStateHistory struct {- RuleID string `json:"ruleID" ch:"rule_id"`- RuleName string `json:"ruleName" ch:"rule_name"`- // One of ["normal", "firing"]- OverallState AlertState `json:"overallState" ch:"overall_state"`- OverallStateChanged bool `json:"overallStateChanged" ch:"overall_state_changed"`- // One of ["normal", "firing", "nodata", "muted"]- State AlertState `json:"state" ch:"state"`- StateChanged bool `json:"stateChanged" ch:"state_changed"`- UnixMilli int64 `json:"unixMilli" ch:"unix_milli"`- Labels LabelsString `json:"labels" ch:"labels"`- Fingerprint uint64 `json:"fingerprint" ch:"fingerprint"`- Value float64 `json:"value" ch:"value"`-- RelatedTracesLink string `json:"relatedTracesLink"`- RelatedLogsLink string `json:"relatedLogsLink"`-}--type QueryRuleStateHistory struct {- Start int64 `json:"start"`- End int64 `json:"end"`- State string `json:"state"`- Filters *v3.FilterSet `json:"filters"`- Offset int64 `json:"offset"`- Limit int64 `json:"limit"`- Order string `json:"order"`-}--func (r *QueryRuleStateHistory) Validate() error {- if r.Start == 0 || r.End == 0 {- return fmt.Errorf("start and end are required")- }- if r.Offset < 0 || r.Limit < 0 {- return fmt.Errorf("offset and limit must be greater than 0")- }- if r.Order != "asc" && r.Order != "desc" {- return fmt.Errorf("order must be asc or desc")- }- return nil-}--type RuleStateHistoryContributor struct {- Fingerprint uint64 `json:"fingerprint" ch:"fingerprint"`- Labels LabelsString `json:"labels" ch:"labels"`- Count uint64 `json:"count" ch:"count"`- RelatedTracesLink string `json:"relatedTracesLink"`- RelatedLogsLink string `json:"relatedLogsLink"`-}--type RuleStateTransition struct {- RuleID string `json:"ruleID" ch:"rule_id"`- State AlertState `json:"state" ch:"state"`- FiringTime int64 `json:"firingTime" ch:"firing_time"`- ResolutionTime int64 `json:"resolutionTime" ch:"resolution_time"`-}--type ReleStateItem struct {- State AlertState `json:"state"`- Start int64 `json:"start"`- End int64 `json:"end"`-}--type Stats struct {- TotalCurrentTriggers uint64 `json:"totalCurrentTriggers"`- TotalPastTriggers uint64 `json:"totalPastTriggers"`- CurrentTriggersSeries *v3.Series `json:"currentTriggersSeries"`- PastTriggersSeries *v3.Series `json:"pastTriggersSeries"`- CurrentAvgResolutionTime string `json:"currentAvgResolutionTime"`- PastAvgResolutionTime string `json:"pastAvgResolutionTime"`- CurrentAvgResolutionTimeSeries *v3.Series `json:"currentAvgResolutionTimeSeries"`- PastAvgResolutionTimeSeries *v3.Series `json:"pastAvgResolutionTimeSeries"`-}