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.

chore: add alert link visitor for expression link (#8641)

Srikanth Chekuri8b2ed674a425
diff --git a/pkg/contextlinks/alert_link_visitor.go b/pkg/contextlinks/alert_link_visitor.go
new file mode 100644
index 0000000000..cac8bba29f
--- /dev/null
+++ b/pkg/contextlinks/alert_link_visitor.go
@@ -0,0 +1,448 @@
+package contextlinks
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ parser "github.com/SigNoz/signoz/pkg/parser/grammar"
+ "github.com/antlr4-go/antlr/v4"
+ "golang.org/x/exp/maps"
+
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+)
+
+type WhereClauseRewriter struct {
+ parser.BaseFilterQueryVisitor
+ labels map[string]string
+ groupByItems []qbtypes.GroupByKey
+ groupBySet map[string]struct{}
+ keysSeen map[string]struct{}
+ rewritten strings.Builder
+}
+
+// PrepareFilterExpression prepares the where clause for the query
+// `labels` contains the key value pairs of the labels from the result of the query
+// We "visit" the where clause and make necessary changes to existing query
+// There are two cases:
+// 1. The label is present in the where clause
+// 2. The label is not present in the where clause
+//
+// Example for case 2:
+// Latency by service.name without any filter
+// In this case, for each service with latency > threshold we send a notification
+// The expectation is that clicking on the related traces for service A, will
+// take us to the traces page with the filter service.name=A
+// So for all the missing labels in the where clause, we add them as key = value
+//
+// Example for case 1:
+// Severity text IN (WARN, ERROR)
+// In this case, the Severity text will appear in the `labels` if it were part of the group
+// by clause, in which case we replace it with the actual value for the notification
+// i.e Severity text = WARN
+// If the Severity text is not part of the group by clause, then we add it as it is
+func PrepareFilterExpression(labels map[string]string, whereClause string, groupByItems []qbtypes.GroupByKey) string {
+ if whereClause == "" && len(labels) == 0 {
+ return ""
+ }
+
+ groupBySet := make(map[string]struct{})
+ for _, item := range groupByItems {
+ groupBySet[item.Name] = struct{}{}
+ }
+
+ input := antlr.NewInputStream(whereClause)
+ lexer := parser.NewFilterQueryLexer(input)
+ stream := antlr.NewCommonTokenStream(lexer, 0)
+ parser := parser.NewFilterQueryParser(stream)
+
+ tree := parser.Query()
+
+ rewriter := &WhereClauseRewriter{
+ labels: labels,
+ groupByItems: groupByItems,
+ groupBySet: groupBySet,
+ keysSeen: map[string]struct{}{},
+ }
+
+ // visit the tree to rewrite the where clause
+ rewriter.Visit(tree)
+ rewrittenClause := strings.TrimSpace(rewriter.rewritten.String())
+
+ // sorted key for deterministic order
+ sortedKeys := maps.Keys(labels)
+ slices.Sort(sortedKeys)
+
+ // case 2: add missing labels from the labels map
+ missingLabels := []string{}
+ for _, key := range sortedKeys {
+ if !rewriter.isKeyInWhereClause(key) {
+ // escape the value if it contains special characters or spaces
+ escapedValue := escapeValueIfNeeded(labels[key])
+ missingLabels = append(missingLabels, fmt.Sprintf("%s=%s", key, escapedValue))
+ }
+ }
+
+ // combine
+ if len(missingLabels) > 0 {
+ if rewrittenClause != "" {
+ rewrittenClause = fmt.Sprintf("(%s) AND %s", rewrittenClause, strings.Join(missingLabels, " AND "))
+ } else {
+ rewrittenClause = strings.Join(missingLabels, " AND ")
+ }
+ }
+
+ return rewrittenClause
+}
+
+// Visit implements the visitor for the query rule
+func (r *WhereClauseRewriter) Visit(tree antlr.ParseTree) interface{} {
+ return tree.Accept(r)
+}
+
+// VisitQuery visits the query node
+func (r *WhereClauseRewriter) VisitQuery(ctx *parser.QueryContext) interface{} {
+ if ctx.Expression() != nil {
+ ctx.Expression().Accept(r)
+ }
+ return nil
+}
+
+// VisitExpression visits the expression node
+func (r *WhereClauseRewriter) VisitExpression(ctx *parser.ExpressionContext) interface{} {
+ if ctx.OrExpression() != nil {
+ ctx.OrExpression().Accept(r)
+ }
+ return nil
+}
+
+// VisitOrExpression visits OR expressions
+func (r *WhereClauseRewriter) VisitOrExpression(ctx *parser.OrExpressionContext) interface{} {
+ for i, andExpr := range ctx.AllAndExpression() {
+ if i > 0 {
+ r.rewritten.WriteString(" OR ")
+ }
+ andExpr.Accept(r)
+ }
+ return nil
+}
+
+// VisitAndExpression visits AND expressions
+func (r *WhereClauseRewriter) VisitAndExpression(ctx *parser.AndExpressionContext) interface{} {
+ unaryExprs := ctx.AllUnaryExpression()
+ for i, unaryExpr := range unaryExprs {
+ if i > 0 {
+ // Check if there's an explicit AND
+ if i-1 < len(ctx.AllAND()) && ctx.AND(i-1) != nil {
+ r.rewritten.WriteString(" AND ")
+ } else {
+ // implicit
+ r.rewritten.WriteString(" AND ")
+ }
+ }
+ unaryExpr.Accept(r)
+ }
+ return nil
+}
+
+// VisitUnaryExpression visits unary expressions (with optional NOT)
+func (r *WhereClauseRewriter) VisitUnaryExpression(ctx *parser.UnaryExpressionContext) interface{} {
+ if ctx.NOT() != nil {
+ r.rewritten.WriteString("NOT ")
+ }
+ if ctx.Primary() != nil {
+ ctx.Primary().Accept(r)
+ }
+ return nil
+}
+
+// VisitPrimary visits primary expressions
+func (r *WhereClauseRewriter) VisitPrimary(ctx *parser.PrimaryContext) interface{} {
+ if ctx.LPAREN() != nil && ctx.RPAREN() != nil {
+ r.rewritten.WriteString("(")
+ if ctx.OrExpression() != nil {
+ ctx.OrExpression().Accept(r)
+ }
+ r.rewritten.WriteString(")")
+ } else if ctx.Comparison() != nil {
+ ctx.Comparison().Accept(r)
+ } else if ctx.FunctionCall() != nil {
+ ctx.FunctionCall().Accept(r)
+ } else if ctx.FullText() != nil {
+ ctx.FullText().Accept(r)
+ } else if ctx.Key() != nil {
+ ctx.Key().Accept(r)
+ } else if ctx.Value() != nil {
+ ctx.Value().Accept(r)
+ }
+ return nil
+}
+
+// VisitComparison visits comparison expressions
+func (r *WhereClauseRewriter) VisitComparison(ctx *parser.ComparisonContext) interface{} {
+ if ctx.Key() == nil {
+ return nil
+ }
+
+ key := ctx.Key().GetText()
+ r.keysSeen[key] = struct{}{}
+
+ // Check if this key is in the labels and was part of group by
+ if value, exists := r.labels[key]; exists {
+ if _, partOfGroup := r.groupBySet[key]; partOfGroup {
+ // Case 1: Replace with actual value
+ escapedValue := escapeValueIfNeeded(value)
+ r.rewritten.WriteString(fmt.Sprintf("%s=%s", key, escapedValue))
+ return nil
+ }
+ }
+
+ // Otherwise, keep the original comparison
+ r.rewritten.WriteString(key)
+
+ if ctx.EQUALS() != nil {
+ r.rewritten.WriteString("=")
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.NOT_EQUALS() != nil || ctx.NEQ() != nil {
+ if ctx.NOT_EQUALS() != nil {
+ r.rewritten.WriteString("!=")
+ } else {
+ r.rewritten.WriteString("<>")
+ }
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.LT() != nil {
+ r.rewritten.WriteString("<")
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.LE() != nil {
+ r.rewritten.WriteString("<=")
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.GT() != nil {
+ r.rewritten.WriteString(">")
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.GE() != nil {
+ r.rewritten.WriteString(">=")
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.LIKE() != nil || ctx.ILIKE() != nil {
+ if ctx.LIKE() != nil {
+ r.rewritten.WriteString(" LIKE ")
+ } else {
+ r.rewritten.WriteString(" ILIKE ")
+ }
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.NOT_LIKE() != nil || ctx.NOT_ILIKE() != nil {
+ if ctx.NOT_LIKE() != nil {
+ r.rewritten.WriteString(" NOT LIKE ")
+ } else {
+ r.rewritten.WriteString(" NOT ILIKE ")
+ }
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.BETWEEN() != nil {
+ if ctx.NOT() != nil {
+ r.rewritten.WriteString(" NOT BETWEEN ")
+ } else {
+ r.rewritten.WriteString(" BETWEEN ")
+ }
+ if len(ctx.AllValue()) >= 2 {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ r.rewritten.WriteString(" AND ")
+ r.rewritten.WriteString(ctx.Value(1).GetText())
+ }
+ } else if ctx.InClause() != nil {
+ r.rewritten.WriteString(" ")
+ ctx.InClause().Accept(r)
+ } else if ctx.NotInClause() != nil {
+ r.rewritten.WriteString(" ")
+ ctx.NotInClause().Accept(r)
+ } else if ctx.EXISTS() != nil {
+ if ctx.NOT() != nil {
+ r.rewritten.WriteString(" NOT EXISTS")
+ } else {
+ r.rewritten.WriteString(" EXISTS")
+ }
+ } else if ctx.REGEXP() != nil {
+ if ctx.NOT() != nil {
+ r.rewritten.WriteString(" NOT REGEXP ")
+ } else {
+ r.rewritten.WriteString(" REGEXP ")
+ }
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ } else if ctx.CONTAINS() != nil {
+ if ctx.NOT() != nil {
+ r.rewritten.WriteString(" NOT CONTAINS ")
+ } else {
+ r.rewritten.WriteString(" CONTAINS ")
+ }
+ if ctx.Value(0) != nil {
+ r.rewritten.WriteString(ctx.Value(0).GetText())
+ }
+ }
+
+ return nil
+}
+
+// VisitInClause visits IN clauses
+func (r *WhereClauseRewriter) VisitInClause(ctx *parser.InClauseContext) interface{} {
+ r.rewritten.WriteString("IN ")
+ if ctx.LPAREN() != nil {
+ r.rewritten.WriteString("(")
+ if ctx.ValueList() != nil {
+ ctx.ValueList().Accept(r)
+ }
+ r.rewritten.WriteString(")")
+ } else if ctx.LBRACK() != nil {
+ r.rewritten.WriteString("[")
+ if ctx.ValueList() != nil {
+ ctx.ValueList().Accept(r)
+ }
+ r.rewritten.WriteString("]")
+ } else if ctx.Value() != nil {
+ r.rewritten.WriteString(ctx.Value().GetText())
+ }
+ return nil
+}
+
+// VisitNotInClause visits NOT IN clauses
+func (r *WhereClauseRewriter) VisitNotInClause(ctx *parser.NotInClauseContext) interface{} {
+ r.rewritten.WriteString("NOT IN ")
+ if ctx.LPAREN() != nil {
+ r.rewritten.WriteString("(")
+ if ctx.ValueList() != nil {
+ ctx.ValueList().Accept(r)
+ }
+ r.rewritten.WriteString(")")
+ } else if ctx.LBRACK() != nil {
+ r.rewritten.WriteString("[")
+ if ctx.ValueList() != nil {
+ ctx.ValueList().Accept(r)
+ }
+ r.rewritten.WriteString("]")
+ } else if ctx.Value() != nil {
+ r.rewritten.WriteString(ctx.Value().GetText())
+ }
+ return nil
+}
+
+// VisitValueList visits value lists
+func (r *WhereClauseRewriter) VisitValueList(ctx *parser.ValueListContext) interface{} {
+ values := ctx.AllValue()
+ for i, val := range values {
+ if i > 0 {
+ r.rewritten.WriteString(", ")
+ }
+ r.rewritten.WriteString(val.GetText())
+ }
+ return nil
+}
+
+// VisitFullText visits full text expressions
+func (r *WhereClauseRewriter) VisitFullText(ctx *parser.FullTextContext) interface{} {
+ r.rewritten.WriteString(ctx.GetText())
+ return nil
+}
+
+// VisitFunctionCall visits function calls
+func (r *WhereClauseRewriter) VisitFunctionCall(ctx *parser.FunctionCallContext) interface{} {
+ // Write function name
+ if ctx.HAS() != nil {
+ r.rewritten.WriteString("has")
+ } else if ctx.HASANY() != nil {
+ r.rewritten.WriteString("hasany")
+ } else if ctx.HASALL() != nil {
+ r.rewritten.WriteString("hasall")
+ }
+
+ r.rewritten.WriteString("(")
+ if ctx.FunctionParamList() != nil {
+ ctx.FunctionParamList().Accept(r)
+ }
+ r.rewritten.WriteString(")")
+ return nil
+}
+
+// VisitFunctionParamList visits function parameter lists
+func (r *WhereClauseRewriter) VisitFunctionParamList(ctx *parser.FunctionParamListContext) interface{} {
+ params := ctx.AllFunctionParam()
+ for i, param := range params {
+ if i > 0 {
+ r.rewritten.WriteString(", ")
+ }
+ param.Accept(r)
+ }
+ return nil
+}
+
+// VisitFunctionParam visits function parameters
+func (r *WhereClauseRewriter) VisitFunctionParam(ctx *parser.FunctionParamContext) interface{} {
+ if ctx.Key() != nil {
+ ctx.Key().Accept(r)
+ } else if ctx.Value() != nil {
+ ctx.Value().Accept(r)
+ } else if ctx.Array() != nil {
+ ctx.Array().Accept(r)
+ }
+ return nil
+}
+
+// VisitArray visits array expressions
+func (r *WhereClauseRewriter) VisitArray(ctx *parser.ArrayContext) interface{} {
+ r.rewritten.WriteString("[")
+ if ctx.ValueList() != nil {
+ ctx.ValueList().Accept(r)
+ }
+ r.rewritten.WriteString("]")
+ return nil
+}
+
+// VisitValue visits value expressions
+func (r *WhereClauseRewriter) VisitValue(ctx *parser.ValueContext) interface{} {
+ r.rewritten.WriteString(ctx.GetText())
+ return nil
+}
+
+// VisitKey visits key expressions
+func (r *WhereClauseRewriter) VisitKey(ctx *parser.KeyContext) interface{} {
+ r.keysSeen[ctx.GetText()] = struct{}{}
+ r.rewritten.WriteString(ctx.GetText())
+ return nil
+}
+
+func (r *WhereClauseRewriter) isKeyInWhereClause(key string) bool {
+ _, ok := r.keysSeen[key]
+ return ok
+}
+
+// escapeValueIfNeeded adds single quotes to string values and escapes single quotes within them
+// Numeric and boolean values are returned as-is
+func escapeValueIfNeeded(value string) string {
+ // Check if it's a number
+ if _, err := fmt.Sscanf(value, "%f", new(float64)); err == nil {
+ return value
+ }
+
+ // Check if it's a boolean
+ if strings.ToLower(value) == "true" || strings.ToLower(value) == "false" {
+ return value
+ }
+
+ // For all other values (strings), escape single quotes and wrap in single quotes
+ escaped := strings.ReplaceAll(value, "'", "\\'")
+ return fmt.Sprintf("'%s'", escaped)
+}
diff --git a/pkg/contextlinks/alert_link_visitor_test.go b/pkg/contextlinks/alert_link_visitor_test.go
new file mode 100644
index 0000000000..d1efe3db6c
--- /dev/null
+++ b/pkg/contextlinks/alert_link_visitor_test.go
@@ -0,0 +1,260 @@
+package contextlinks
+
+import (
+ "testing"
+
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestPrepareFiltersV5(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ whereClause string
+ groupByItems []qbtypes.GroupByKey
+ expected string
+ description string
+ }{
+ {
+ name: "empty_inputs",
+ labels: map[string]string{},
+ whereClause: "",
+ groupByItems: []qbtypes.GroupByKey{},
+ expected: "",
+ description: "Should return empty string for empty inputs",
+ },
+ {
+ name: "no_label_replacement",
+ labels: map[string]string{},
+ whereClause: "service.name = 'serviceB'",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ },
+ expected: "service.name='serviceB'",
+ description: "No change",
+ },
+ {
+ name: "in_clause_replacement",
+ labels: map[string]string{
+ "severity_text": "WARN",
+ },
+ whereClause: "severity_text IN ('WARN', 'ERROR')",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "severity_text"}},
+ },
+ expected: "severity_text='WARN'",
+ description: "Should replace IN clause with actual value when key is in group by",
+ },
+ {
+ name: "missing_label_addition", // case 2
+ labels: map[string]string{
+ "service.name": "serviceA",
+ },
+ whereClause: "status_code > 400",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ },
+ expected: "(status_code>400) AND service.name='serviceA'",
+ description: "Should add missing labels from labels map",
+ },
+ {
+ name: "multiple_missing_labels",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ "region": "us-east-1",
+ },
+ whereClause: "status_code > 400",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "region"}},
+ },
+ expected: "(status_code>400) AND region='us-east-1' AND service.name='serviceA'",
+ description: "Should add all missing labels",
+ },
+ {
+ name: "complex_where_clause",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ },
+ whereClause: "(status_code > 400 OR status_code < 200) AND method = 'GET'",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ },
+ expected: "((status_code>400 OR status_code<200) AND method='GET') AND service.name='serviceA'",
+ description: "Should preserve complex boolean logic and add missing labels",
+ },
+ {
+ name: "label_not_in_group_by",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ },
+ whereClause: "service.name = 'serviceB'",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "region"}}, // service.name not in group by
+ },
+ expected: "service.name='serviceB'",
+ description: "Should not replace label if not in group by items",
+ },
+ {
+ name: "special_characters_in_values",
+ labels: map[string]string{
+ "message": "Error: Connection failed",
+ "path": "/api/v1/users",
+ },
+ whereClause: "",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "message"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "path"}},
+ },
+ expected: "message='Error: Connection failed' AND path='/api/v1/users'",
+ description: "Should quote values with special characters",
+ },
+ {
+ name: "numeric_and_boolean_values",
+ labels: map[string]string{
+ "count": "42",
+ "isEnabled": "true",
+ },
+ whereClause: "",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "count"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "isEnabled"}},
+ },
+ expected: "count=42 AND isEnabled=true",
+ description: "Should not quote numeric and boolean values",
+ },
+
+ {
+ name: "like_operator",
+ labels: map[string]string{
+ "path": "/api/users",
+ },
+ whereClause: "path LIKE '/api%'",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "path"}},
+ },
+ expected: "path='/api/users'",
+ description: "Should replace LIKE comparisons when key is in group by",
+ },
+
+ {
+ name: "not_operators",
+ labels: map[string]string{
+ "status": "active",
+ },
+ whereClause: "status NOT IN ('deleted', 'archived')",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "status"}},
+ },
+ expected: "status='active'",
+ description: "Should replace NOT IN clause when key is in group by",
+ },
+
+ {
+ name: "between_operator",
+ labels: map[string]string{
+ "response_time": "250",
+ },
+ whereClause: "response_time BETWEEN 100 AND 500",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "response_time"}},
+ },
+ expected: "response_time=250",
+ description: "Should replace BETWEEN clause when key is in group by",
+ },
+
+ {
+ name: "function_calls",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ },
+ whereClause: "has(tags, 'production')",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ },
+ expected: "(has(tags, 'production')) AND service.name='serviceA'",
+ description: "Should preserve function calls and add missing labels",
+ },
+ {
+ name: "already_quoted_values",
+ labels: map[string]string{
+ "message": "\"Error message\"",
+ "tag": "'production'",
+ },
+ whereClause: "",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "message"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "tag"}},
+ },
+ expected: "message='\"Error message\"' AND tag='\\'production\\''",
+ description: "Should not double-quote already quoted values",
+ },
+
+ {
+ name: "mixed_replacement_and_addition",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ "severity_text": "ERROR",
+ "region": "us-west-2",
+ },
+ whereClause: "severity_text IN ('WARN', 'ERROR') AND status_code > 400",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "severity_text"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "region"}},
+ },
+ expected: "(severity_text='ERROR' AND status_code>400) AND region='us-west-2' AND service.name='serviceA'",
+ description: "Should both replace existing labels and add missing ones",
+ },
+
+ {
+ name: "implicit_and_handling",
+ labels: map[string]string{
+ "env": "production",
+ },
+ whereClause: "status_code=200 method='GET'", // implicit AND
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "env"}},
+ },
+ expected: "(status_code=200 AND method='GET') AND env='production'",
+ description: "Should handle implicit AND between expressions",
+ },
+
+ {
+ name: "exists_operator",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ },
+ whereClause: "error_details EXISTS",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ },
+ expected: "(error_details EXISTS) AND service.name='serviceA'",
+ description: "Should preserve EXISTS operator",
+ },
+
+ {
+ name: "empty_where_clause_with_labels",
+ labels: map[string]string{
+ "service.name": "serviceA",
+ "region": "us-east-1",
+ },
+ whereClause: "",
+ groupByItems: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}},
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "region"}},
+ },
+ expected: "region='us-east-1' AND service.name='serviceA'",
+ description: "Should create where clause from labels when original is empty",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := PrepareFilterExpression(tt.labels, tt.whereClause, tt.groupByItems)
+ assert.Equal(t, tt.expected, result, tt.description)
+ })
+ }
+}
diff --git a/pkg/query-service/contextlinks/links.go b/pkg/contextlinks/links.go
similarity index 100%
rename from pkg/query-service/contextlinks/links.go
rename to pkg/contextlinks/links.go
diff --git a/pkg/contextlinks/types.go b/pkg/contextlinks/types.go
new file mode 100644
index 0000000000..bfc1ab6abb
--- /dev/null
+++ b/pkg/contextlinks/types.go
@@ -0,0 +1,40 @@
+package contextlinks
+
+import v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
+
+// TODO(srikanthccv): Fix the URL management
+type URLShareableTimeRange struct {
+ Start int64 `json:"start"`
+ End int64 `json:"end"`
+ PageSize int64 `json:"pageSize"`
+}
+
+type FilterExpression struct {
+ Expression string `json:"expression,omitempty"`
+}
+
+type Aggregation struct {
+ Expression string `json:"expression,omitempty"`
+}
+
+type LinkQuery struct {
+ v3.BuilderQuery
+ Filter *FilterExpression `json:"filter,omitempty"`
+ Aggregations []*Aggregation `json:"aggregations,omitempty"`
+}
+
+type URLShareableBuilderQuery struct {
+ QueryData []LinkQuery `json:"queryData"`
+ QueryFormulas []string `json:"queryFormulas"`
+}
+
+type URLShareableCompositeQuery struct {
+ QueryType string `json:"queryType"`
+ Builder URLShareableBuilderQuery `json:"builder"`
+}
+
+type URLShareableOptions struct {
+ MaxLines int `json:"maxLines"`
+ Format string `json:"format"`
+ SelectColumns []v3.AttributeKey `json:"selectColumns"`
+}
diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go
index 73cd2dbbff..69be0b7f18 100644
--- a/pkg/query-service/app/http_handler.go
+++ b/pkg/query-service/app/http_handler.go
@@ -38,6 +38,7 @@ import (
jsoniter "github.com/json-iterator/go"
_ "github.com/mattn/go-sqlite3"
+ "github.com/SigNoz/signoz/pkg/contextlinks"
traceFunnelsModule "github.com/SigNoz/signoz/pkg/modules/tracefunnel"
"github.com/SigNoz/signoz/pkg/query-service/agentConf"
"github.com/SigNoz/signoz/pkg/query-service/app/cloudintegrations"
@@ -55,7 +56,6 @@ import (
tracesV3 "github.com/SigNoz/signoz/pkg/query-service/app/traces/v3"
tracesV4 "github.com/SigNoz/signoz/pkg/query-service/app/traces/v4"
"github.com/SigNoz/signoz/pkg/query-service/constants"
- "github.com/SigNoz/signoz/pkg/query-service/contextlinks"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
"github.com/SigNoz/signoz/pkg/query-service/postprocess"
"github.com/SigNoz/signoz/pkg/types"
diff --git a/pkg/query-service/rules/threshold_rule.go b/pkg/query-service/rules/threshold_rule.go
index 191c1dc41f..192de55219 100644
--- a/pkg/query-service/rules/threshold_rule.go
+++ b/pkg/query-service/rules/threshold_rule.go
@@ -11,8 +11,8 @@ import (
"go.uber.org/zap"
+ "github.com/SigNoz/signoz/pkg/contextlinks"
"github.com/SigNoz/signoz/pkg/query-service/common"
- "github.com/SigNoz/signoz/pkg/query-service/contextlinks"
"github.com/SigNoz/signoz/pkg/query-service/model"
"github.com/SigNoz/signoz/pkg/query-service/postprocess"
ruletypes "github.com/SigNoz/signoz/pkg/types/ruletypes"