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: update Services to use QBV5 (#9287)

Nikhil Mantridb75ec56bc13
diff --git a/frontend/src/api/metrics/getService.ts b/frontend/src/api/metrics/getService.ts
index 731da11c81..b269be96bd 100644
--- a/frontend/src/api/metrics/getService.ts
+++ b/frontend/src/api/metrics/getService.ts
@@ -1,13 +1,20 @@
-import axios from 'api';
+import { ApiV2Instance } from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp } from 'types/api';
import { PayloadProps, Props } from 'types/api/metrics/getService';
const getService = async (props: Props): Promise<PayloadProps> => {
- const response = await axios.post(`/services`, {
- start: `${props.start}`,
- end: `${props.end}`,
- tags: props.selectedTags,
- });
- return response.data;
+ try {
+ const response = await ApiV2Instance.post(`/services`, {
+ start: `${props.start}`,
+ end: `${props.end}`,
+ tags: props.selectedTags,
+ });
+ return response.data.data;
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
};
export default getService;
diff --git a/frontend/src/api/metrics/getTopOperations.ts b/frontend/src/api/metrics/getTopOperations.ts
index af02e2c333..bf72660d03 100644
--- a/frontend/src/api/metrics/getTopOperations.ts
+++ b/frontend/src/api/metrics/getTopOperations.ts
@@ -1,22 +1,27 @@
-import axios from 'api';
+import { ApiV2Instance } from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp } from 'types/api';
import { PayloadProps, Props } from 'types/api/metrics/getTopOperations';
const getTopOperations = async (props: Props): Promise<PayloadProps> => {
- const endpoint = props.isEntryPoint
- ? '/service/entry_point_operations'
- : '/service/top_operations';
+ try {
+ const endpoint = props.isEntryPoint
+ ? '/service/entry_point_operations'
+ : '/service/top_operations';
- const response = await axios.post(endpoint, {
- start: `${props.start}`,
- end: `${props.end}`,
- service: props.service,
- tags: props.selectedTags,
- });
+ const response = await ApiV2Instance.post(endpoint, {
+ start: `${props.start}`,
+ end: `${props.end}`,
+ service: props.service,
+ tags: props.selectedTags,
+ limit: 5000,
+ });
- if (props.isEntryPoint) {
return response.data.data;
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
}
- return response.data;
};
export default getTopOperations;
diff --git a/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx b/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx
index bc6560939a..d7d29dba92 100644
--- a/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx
+++ b/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx
@@ -115,19 +115,25 @@ describe('TopOperation API Integration', () => {
server.use(
rest.post(
- 'http://localhost/api/v1/service/top_operations',
+ 'http://localhost/api/v2/service/top_operations',
async (req, res, ctx) => {
const body = await req.json();
apiCalls.push({ endpoint: TOP_OPERATIONS_ENDPOINT, body });
- return res(ctx.status(200), ctx.json(mockTopOperationsData));
+ return res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: mockTopOperationsData }),
+ );
},
),
rest.post(
- 'http://localhost/api/v1/service/entry_point_operations',
+ 'http://localhost/api/v2/service/entry_point_operations',
async (req, res, ctx) => {
const body = await req.json();
apiCalls.push({ endpoint: ENTRY_POINT_OPERATIONS_ENDPOINT, body });
- return res(ctx.status(200), ctx.json({ data: mockEntryPointData }));
+ return res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: mockEntryPointData }),
+ );
},
),
);
@@ -162,6 +168,7 @@ describe('TopOperation API Integration', () => {
end: `${defaultApiCallExpectation.end}`,
service: defaultApiCallExpectation.service,
tags: defaultApiCallExpectation.selectedTags,
+ limit: 5000,
});
});
@@ -195,6 +202,7 @@ describe('TopOperation API Integration', () => {
end: `${defaultApiCallExpectation.end}`,
service: defaultApiCallExpectation.service,
tags: defaultApiCallExpectation.selectedTags,
+ limit: 5000,
});
});
diff --git a/frontend/src/mocks-server/handlers.ts b/frontend/src/mocks-server/handlers.ts
index ccb4dd603a..abb3fc1aec 100644
--- a/frontend/src/mocks-server/handlers.ts
+++ b/frontend/src/mocks-server/handlers.ts
@@ -26,8 +26,11 @@ export const handlers = [
res(ctx.status(200), ctx.json(queryRangeSuccessResponse)),
),
- rest.post('http://localhost/api/v1/services', (req, res, ctx) =>
- res(ctx.status(200), ctx.json(serviceSuccessResponse)),
+ rest.post('http://localhost/api/v2/services', (req, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: serviceSuccessResponse }),
+ ),
),
rest.post(
diff --git a/frontend/src/pages/MetricsApplication/MetricsApplication.tsx b/frontend/src/pages/MetricsApplication/MetricsApplication.tsx
index 25013bf388..b06917ece8 100644
--- a/frontend/src/pages/MetricsApplication/MetricsApplication.tsx
+++ b/frontend/src/pages/MetricsApplication/MetricsApplication.tsx
@@ -19,8 +19,6 @@ function MetricsApplication(): JSX.Element {
servicename: string;
}>();
- const servicename = decodeURIComponent(encodedServiceName);
-
const activeKey = useMetricsApplicationTabKey();
const urlQuery = useUrlQuery();
@@ -46,7 +44,7 @@ function MetricsApplication(): JSX.Element {
const onTabChange = (tab: string): void => {
urlQuery.set(QueryParams.tab, tab);
- safeNavigate(`/services/${servicename}?${urlQuery.toString()}`);
+ safeNavigate(`/services/${encodedServiceName}?${urlQuery.toString()}`);
};
return (
diff --git a/pkg/modules/services/implservices/handler.go b/pkg/modules/services/implservices/handler.go
new file mode 100644
index 0000000000..9edc4d7e63
--- /dev/null
+++ b/pkg/modules/services/implservices/handler.go
@@ -0,0 +1,100 @@
+package implservices
+
+import (
+ "net/http"
+
+ "github.com/SigNoz/signoz/pkg/http/binding"
+ "github.com/SigNoz/signoz/pkg/http/render"
+ "github.com/SigNoz/signoz/pkg/modules/services"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/servicetypes/servicetypesv1"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+type handler struct {
+ Module services.Module
+}
+
+func NewHandler(m services.Module) services.Handler {
+ return &handler{
+ Module: m,
+ }
+}
+
+func (h *handler) Get(rw http.ResponseWriter, req *http.Request) {
+ claims, err := authtypes.ClaimsFromContext(req.Context())
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ var in servicetypesv1.Request
+ if err := binding.JSON.BindBody(req.Body, &in); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgUUID, err := valuer.NewUUID(claims.OrgID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ out, err := h.Module.Get(req.Context(), orgUUID, &in)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ render.Success(rw, http.StatusOK, out)
+}
+
+func (h *handler) GetTopOperations(rw http.ResponseWriter, req *http.Request) {
+ claims, err := authtypes.ClaimsFromContext(req.Context())
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ var in servicetypesv1.OperationsRequest
+ if err := binding.JSON.BindBody(req.Body, &in); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgUUID, err := valuer.NewUUID(claims.OrgID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ out, err := h.Module.GetTopOperations(req.Context(), orgUUID, &in)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ render.Success(rw, http.StatusOK, out)
+}
+
+func (h *handler) GetEntryPointOperations(rw http.ResponseWriter, req *http.Request) {
+ claims, err := authtypes.ClaimsFromContext(req.Context())
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ var in servicetypesv1.OperationsRequest
+ if err := binding.JSON.BindBody(req.Body, &in); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgUUID, err := valuer.NewUUID(claims.OrgID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ out, err := h.Module.GetEntryPointOperations(req.Context(), orgUUID, &in)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ render.Success(rw, http.StatusOK, out)
+}
diff --git a/pkg/modules/services/implservices/helpers.go b/pkg/modules/services/implservices/helpers.go
new file mode 100644
index 0000000000..2674343cf4
--- /dev/null
+++ b/pkg/modules/services/implservices/helpers.go
@@ -0,0 +1,132 @@
+package implservices
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/servicetypes/servicetypesv1"
+)
+
+// validateTagFilterItems validates the tag filter items. This should be used before using
+// buildFilterExpression or any other function that uses tag filter items.
+func validateTagFilterItems(tags []servicetypesv1.TagFilterItem) error {
+ for _, t := range tags {
+ if t.Key == "" {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "key is required")
+ }
+ if strings.ToLower(t.Operator) != "in" && strings.ToLower(t.Operator) != "notin" {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "only in and notin operators are supported")
+ }
+ if len(t.StringValues) == 0 && len(t.BoolValues) == 0 && len(t.NumberValues) == 0 {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "at least one of stringValues, boolValues, or numberValues must be populated")
+ }
+ }
+ return nil
+}
+
+// buildFilterExpression converts tag filters into a QBv5-compatible filter expression and set of variableItems.
+// before calling this function, should validate tags with validateTagFilterItems first.
+func buildFilterExpression(tags []servicetypesv1.TagFilterItem) (string, map[string]qbtypes.VariableItem) {
+ variables := make(map[string]qbtypes.VariableItem)
+ parts := make([]string, 0, len(tags))
+ valueItr := 1
+ for _, t := range tags {
+ valueIdentifier := fmt.Sprintf("%d", valueItr)
+
+ switch strings.ToLower(t.Operator) {
+ case "notin":
+ if vals, ok := pickInValuesFromTag(t); ok {
+ variables[valueIdentifier] = qbtypes.VariableItem{Type: qbtypes.DynamicVariableType, Value: vals}
+ } else {
+ continue
+ }
+ parts = append(parts, fmt.Sprintf("%s NOT IN $%s", t.Key, valueIdentifier))
+ case "in":
+ if vals, ok := pickInValuesFromTag(t); ok {
+ variables[valueIdentifier] = qbtypes.VariableItem{Type: qbtypes.DynamicVariableType, Value: vals}
+ } else {
+ continue
+ }
+ parts = append(parts, fmt.Sprintf("%s IN $%s", t.Key, valueIdentifier))
+ default:
+ continue
+ }
+
+ valueItr++
+ }
+
+ filterExpr := strings.Join(parts, " AND ")
+ return filterExpr, variables
+}
+
+// pickInValuesFromTag returns a []any for IN operator in the precedence order of
+// StringValues, BoolValues, NumberValues. Returns false if none are populated.
+func pickInValuesFromTag(t servicetypesv1.TagFilterItem) ([]any, bool) {
+ if len(t.StringValues) > 0 {
+ vals := make([]any, 0, len(t.StringValues))
+ for _, v := range t.StringValues {
+ vals = append(vals, v)
+ }
+ return vals, true
+ }
+ if len(t.BoolValues) > 0 {
+ vals := make([]any, 0, len(t.BoolValues))
+ for _, v := range t.BoolValues {
+ vals = append(vals, v)
+ }
+ return vals, true
+ }
+ if len(t.NumberValues) > 0 {
+ vals := make([]any, 0, len(t.NumberValues))
+ for _, v := range t.NumberValues {
+ vals = append(vals, v)
+ }
+ return vals, true
+ }
+ return nil, false
+}
+
+// toFloat safely converts a cell value to float64, returning 0 on type mismatch.
+func toFloat(row []any, idx int) float64 {
+ if idx < 0 || idx >= len(row) || row[idx] == nil {
+ return 0
+ }
+ v, ok := row[idx].(float64)
+ if !ok {
+ return 0
+ }
+ return v
+}
+
+// toUint64 safely converts a cell value to uint64.
+func toUint64(row []any, idx int) uint64 {
+ if idx < 0 || idx >= len(row) || row[idx] == nil {
+ return 0
+ }
+ v, ok := row[idx].(uint64)
+ if !ok {
+ return 0
+ }
+ return v
+}
+
+// applyOpsToItems sets topLevelOps for matching service names.
+// If opsMap is nil, it performs no changes.
+func applyOpsToItems(items []*servicetypesv1.ResponseItem, opsMap map[string][]string) {
+ if len(items) == 0 {
+ return
+ }
+ if opsMap == nil {
+ return
+ }
+ for i := range items {
+ if items[i] == nil {
+ continue
+ }
+ if tops, ok := opsMap[items[i].ServiceName]; ok {
+ items[i].DataWarning.TopLevelOps = tops
+ }
+ }
+}
diff --git a/pkg/modules/services/implservices/helpers_test.go b/pkg/modules/services/implservices/helpers_test.go
new file mode 100644
index 0000000000..bfc7bd8030
--- /dev/null
+++ b/pkg/modules/services/implservices/helpers_test.go
@@ -0,0 +1,266 @@
+package implservices
+
+import (
+ "testing"
+
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/servicetypes/servicetypesv1"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestToFloat(t *testing.T) {
+ tests := []struct {
+ name string
+ row []any
+ idx int
+ want float64
+ }{
+ {name: "float64", row: []any{1.5}, idx: 0, want: 1.5},
+ {name: "nil", row: []any{nil}, idx: 0, want: 0},
+ {name: "oob", row: []any{1}, idx: 1, want: 0},
+ {name: "wrong type -> 0", row: []any{"not-number"}, idx: 0, want: 0},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := toFloat(tt.row, tt.idx)
+ assert.Equal(t, tt.want, got)
+ })
+ }
+}
+
+func TestToUint64(t *testing.T) {
+ tests := []struct {
+ name string
+ row []any
+ idx int
+ want uint64
+ }{
+ {name: "uint64", row: []any{uint64(5)}, idx: 0, want: 5},
+ {name: "nil -> 0", row: []any{nil}, idx: 0, want: 0},
+ {name: "oob -> 0", row: []any{1}, idx: 2, want: 0},
+ {name: "wrong type -> 0", row: []any{"not-number"}, idx: 0, want: 0},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := toUint64(tt.row, tt.idx)
+ assert.Equal(t, tt.want, got)
+ })
+ }
+}
+
+func TestApplyOpsToItems(t *testing.T) {
+ tests := []struct {
+ name string
+ items []*servicetypesv1.ResponseItem
+ ops map[string][]string
+ want [][]string
+ }{
+ {
+ name: "maps ops to matching services",
+ items: []*servicetypesv1.ResponseItem{
+ {ServiceName: "svc-a", DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}}},
+ {ServiceName: "svc-b", DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}}},
+ },
+ ops: map[string][]string{
+ "svc-a": {"op1", "op2"},
+ "svc-c": {"opx"},
+ },
+ want: [][]string{
+ {"op1", "op2"},
+ {},
+ },
+ },
+ {
+ name: "nil ops map is no-op",
+ items: []*servicetypesv1.ResponseItem{
+ {ServiceName: "svc-a", DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}}},
+ {ServiceName: "svc-b", DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}}},
+ },
+ ops: nil,
+ want: [][]string{{}, {}},
+ },
+ {
+ name: "empty items slice is no-op",
+ items: []*servicetypesv1.ResponseItem{},
+ ops: map[string][]string{"svc-a": {"op1"}},
+ want: [][]string{},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ applyOpsToItems(tt.items, tt.ops)
+ if len(tt.items) != len(tt.want) {
+ assert.Equal(t, len(tt.want), len(tt.items))
+ return
+ }
+ for i := range tt.items {
+ if tt.items[i] == nil {
+ continue
+ }
+ assert.Equal(t, tt.want[i], tt.items[i].DataWarning.TopLevelOps)
+ }
+ })
+ }
+}
+
+func TestBuildFilterExpression(t *testing.T) {
+ tests := []struct {
+ name string
+ tags []servicetypesv1.TagFilterItem
+ wantExpr string
+ assertV func(t *testing.T, vars map[string]qbtypes.VariableItem)
+ }{
+ {
+ name: "no tags -> empty expr",
+ tags: nil,
+ wantExpr: "",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ assert.Equal(t, 0, len(vars))
+ },
+ },
+ {
+ name: "not in multiple strings",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "service.name", Operator: "NotIn", StringValues: []string{"svc-a", "svc-b"}},
+ },
+ wantExpr: "service.name NOT IN $1",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ arr, ok := vars["1"].Value.([]any)
+ assert.True(t, ok)
+ assert.ElementsMatch(t, []any{"svc-a", "svc-b"}, arr)
+ },
+ },
+ {
+ name: "in single string",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "deployment.environment", Operator: "in", StringValues: []string{"staging"}},
+ },
+ wantExpr: "deployment.environment IN $1",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ arr, ok := vars["1"].Value.([]any)
+ assert.True(t, ok)
+ assert.Len(t, arr, 1)
+ assert.Equal(t, "staging", arr[0])
+ },
+ },
+ {
+ name: "in multiple strings",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "service.name", Operator: "IN", StringValues: []string{"svc-a", "svc-b"}},
+ },
+ wantExpr: "service.name IN $1",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ arr, ok := vars["1"].Value.([]any)
+ assert.True(t, ok)
+ assert.ElementsMatch(t, []any{"svc-a", "svc-b"}, arr)
+ },
+ },
+ {
+ name: "in multiple numbers",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "http.status_code", Operator: "in", NumberValues: []float64{200, 500}},
+ },
+ wantExpr: "http.status_code IN $1",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ arr, ok := vars["1"].Value.([]any)
+ assert.True(t, ok)
+ assert.ElementsMatch(t, []any{200.0, 500.0}, arr)
+ },
+ },
+ {
+ name: "in multiple bools",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "feature.flag", Operator: "IN", BoolValues: []bool{true, false}},
+ },
+ wantExpr: "feature.flag IN $1",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ arr, ok := vars["1"].Value.([]any)
+ assert.True(t, ok)
+ assert.ElementsMatch(t, []any{true, false}, arr)
+ },
+ },
+ {
+ name: "in and not in both conditions",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "service.name", Operator: "In", StringValues: []string{"svc-a", "svc-b"}},
+ {Key: "deployment.environment", Operator: "NotIn", StringValues: []string{"production", "staging"}},
+ },
+ wantExpr: "service.name IN $1 AND deployment.environment NOT IN $2",
+ assertV: func(t *testing.T, vars map[string]qbtypes.VariableItem) {
+ arr, ok := vars["1"].Value.([]any)
+ assert.True(t, ok)
+ assert.ElementsMatch(t, []any{"svc-a", "svc-b"}, arr)
+ arr, ok = vars["2"].Value.([]any)
+ assert.True(t, ok)
+ assert.ElementsMatch(t, []any{"production", "staging"}, arr)
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ expr, vars := buildFilterExpression(tt.tags)
+ assert.Equal(t, tt.wantExpr, expr)
+ if tt.assertV != nil {
+ tt := tt
+ tt.assertV(t, vars)
+ }
+ })
+ }
+}
+
+func TestValidateTagFilterItems(t *testing.T) {
+ tests := []struct {
+ name string
+ tags []servicetypesv1.TagFilterItem
+ wantErr string
+ }{
+ {
+ name: "empty tags -> ok",
+ tags: nil,
+ wantErr: "",
+ },
+ {
+ name: "missing key -> error",
+ tags: []servicetypesv1.TagFilterItem{{Key: "", Operator: "in", StringValues: []string{"a"}}},
+ wantErr: "key is required",
+ },
+ {
+ name: "valid in and notin",
+ tags: []servicetypesv1.TagFilterItem{
+ {Key: "service.name", Operator: "in", StringValues: []string{"svc-a", "svc-b"}},
+ {Key: "deployment.environment", Operator: "notin", StringValues: []string{"prod"}},
+ },
+ wantErr: "",
+ },
+ {
+ name: "invalid operator -> error",
+ tags: []servicetypesv1.TagFilterItem{{Key: "service.name", Operator: "equals", StringValues: []string{"a"}}},
+ wantErr: "only in and notin operators are supported",
+ },
+ {
+ name: "in with no values -> error",
+ tags: []servicetypesv1.TagFilterItem{{Key: "env", Operator: "in"}},
+ wantErr: "at least one of stringValues, boolValues, or numberValues must be populated",
+ },
+ {
+ name: "notin with no values -> error",
+ tags: []servicetypesv1.TagFilterItem{{Key: "env", Operator: "notin"}},
+ wantErr: "at least one of stringValues, boolValues, or numberValues must be populated",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateTagFilterItems(tt.tags)
+ if tt.wantErr == "" {
+ assert.NoError(t, err)
+ } else {
+ if assert.Error(t, err) {
+ assert.Contains(t, err.Error(), tt.wantErr)
+ }
+ }
+ })
+ }
+}
diff --git a/pkg/modules/services/implservices/module.go b/pkg/modules/services/implservices/module.go
new file mode 100644
index 0000000000..984f321c2d
--- /dev/null
+++ b/pkg/modules/services/implservices/module.go
@@ -0,0 +1,519 @@
+package implservices
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "strconv"
+
+ "github.com/ClickHouse/clickhouse-go/v2"
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/modules/services"
+ "github.com/SigNoz/signoz/pkg/querier"
+ "github.com/SigNoz/signoz/pkg/telemetrystore"
+ "github.com/SigNoz/signoz/pkg/telemetrytraces"
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/servicetypes/servicetypesv1"
+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+type module struct {
+ Querier querier.Querier
+ TelemetryStore telemetrystore.TelemetryStore
+}
+
+// NewModule constructs the services module with the provided querier dependency.
+func NewModule(q querier.Querier, ts telemetrystore.TelemetryStore) services.Module {
+ return &module{
+ Querier: q,
+ TelemetryStore: ts,
+ }
+}
+
+// FetchTopLevelOperations returns top-level operations per service using db query
+func (m *module) FetchTopLevelOperations(ctx context.Context, start time.Time, services []string) (map[string][]string, error) {
+ db := m.TelemetryStore.ClickhouseDB()
+ query := fmt.Sprintf("SELECT name, serviceName, max(time) as ts FROM %s.%s WHERE time >= @start", telemetrytraces.DBName, telemetrytraces.TopLevelOperationsTableName)
+ args := []any{clickhouse.Named("start", start)}
+ if len(services) > 0 {
+ query += " AND serviceName IN @services"
+ args = append(args, clickhouse.Named("services", services))
+ }
+ query += " GROUP BY name, serviceName ORDER BY ts DESC LIMIT 5000"
+
+ rows, err := db.Query(ctx, query, args...)
+ if err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to fetch top level operations")
+ }
+ defer rows.Close()
+
+ ops := make(map[string][]string)
+ if err := rows.Err(); err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to fetch top level operations")
+ }
+ for rows.Next() {
+ var name, serviceName string
+ var ts time.Time
+ if err := rows.Scan(&name, &serviceName, &ts); err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to scan top level operation")
+ }
+ if _, ok := ops[serviceName]; !ok {
+ ops[serviceName] = []string{"overflow_operation"}
+ }
+ ops[serviceName] = append(ops[serviceName], name)
+ }
+ return ops, nil
+}
+
+// Get implements services.Module
+// Builds a QBv5 traces aggregation grouped by service.name and maps results to ResponseItem.
+func (m *module) Get(ctx context.Context, orgUUID valuer.UUID, req *servicetypesv1.Request) ([]*servicetypesv1.ResponseItem, error) {
+ if req == nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "request is nil")
+ }
+
+ // Prepare phase
+ queryRangeReq, startMs, endMs, err := m.buildQueryRangeRequest(req)
+ if err != nil {
+ return nil, err
+ }
+
+ // Fetch phase
+ resp, err := m.executeQuery(ctx, orgUUID, queryRangeReq)
+ if err != nil {
+ return nil, err
+ }
+
+ // Process phase
+ items, serviceNames := m.mapQueryRangeRespToServices(resp, startMs, endMs)
+ if len(items) == 0 {
+ return []*servicetypesv1.ResponseItem{}, nil
+ }
+
+ // attach top level ops to service items
+ if len(serviceNames) > 0 {
+ if err := m.attachTopLevelOps(ctx, serviceNames, startMs, items); err != nil {
+ return nil, err
+ }
+ }
+
+ return items, nil
+}
+
+// GetTopOperations implements services.Module for QBV5 based top ops
+func (m *module) GetTopOperations(ctx context.Context, orgUUID valuer.UUID, req *servicetypesv1.OperationsRequest) ([]servicetypesv1.OperationItem, error) {
+ if req == nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "request is nil")
+ }
+
+ qr, err := m.buildTopOpsQueryRangeRequest(req)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := m.executeQuery(ctx, orgUUID, qr)
+ if err != nil {
+ return nil, err
+ }
+
+ items := m.mapTopOpsQueryRangeResp(resp)
+ return items, nil
+}
+
+// GetEntryPointOperations implements services.Module for QBV5 based entry point ops
+func (m *module) GetEntryPointOperations(ctx context.Context, orgUUID valuer.UUID, req *servicetypesv1.OperationsRequest) ([]servicetypesv1.OperationItem, error) {
+ if req == nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "request is nil")
+ }
+
+ qr, err := m.buildEntryPointOpsQueryRangeRequest(req)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := m.executeQuery(ctx, orgUUID, qr)
+ if err != nil {
+ return nil, err
+ }
+
+ items := m.mapEntryPointOpsQueryRangeResp(resp)
+ return items, nil
+}
+
+// buildQueryRangeRequest constructs the QBv5 QueryRangeRequest and computes the time window.
+func (m *module) buildQueryRangeRequest(req *servicetypesv1.Request) (*qbtypes.QueryRangeRequest, uint64, uint64, error) {
+ // Parse start/end (nanoseconds) from strings and convert to milliseconds for QBv5
+ startNs, err := strconv.ParseUint(req.Start, 10, 64)
+ if err != nil {
+ return nil, 0, 0, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid start time: %v", err)
+ }
+ endNs, err := strconv.ParseUint(req.End, 10, 64)
+ if err != nil {
+ return nil, 0, 0, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid end time: %v", err)
+ }
+ if startNs >= endNs {
+ return nil, 0, 0, errors.NewInvalidInputf(errors.CodeInvalidInput, "start must be before end")
+ }
+ if err := validateTagFilterItems(req.Tags); err != nil {
+ return nil, 0, 0, err
+ }
+
+ startMs := startNs / 1_000_000
+ endMs := endNs / 1_000_000
+
+ // tags filter
+ filterExpr, variables := buildFilterExpression(req.Tags)
+ // ensure we only consider root or entry-point spans
+ scopeExpr := "isRoot = true OR isEntryPoint = true"
+ if filterExpr != "" {
+ filterExpr = "(" + filterExpr + ") AND (" + scopeExpr + ")"
+ } else {
+ filterExpr = scopeExpr
+ }
+
+ reqV5 := qbtypes.QueryRangeRequest{
+ Start: startMs,
+ End: endMs,
+ RequestType: qbtypes.RequestTypeScalar,
+ Variables: variables,
+ CompositeQuery: qbtypes.CompositeQuery{
+ Queries: []qbtypes.QueryEnvelope{
+ {Type: qbtypes.QueryTypeBuilder,
+ Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
+ Name: "A",
+ Signal: telemetrytypes.SignalTraces,
+ Filter: &qbtypes.Filter{
+ Expression: filterExpr,
+ },
+ GroupBy: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
+ Name: "service.name",
+ FieldContext: telemetrytypes.FieldContextResource,
+ FieldDataType: telemetrytypes.FieldDataTypeString,
+ Materialized: true,
+ }},
+ },
+ Aggregations: []qbtypes.TraceAggregation{
+ {Expression: "p99(duration_nano)", Alias: "p99"},
+ {Expression: "avg(duration_nano)", Alias: "avgDuration"},
+ {Expression: "count()", Alias: "numCalls"},
+ {Expression: "countIf(status_code = 2)", Alias: "numErrors"},
+ {Expression: "countIf(response_status_code >= 400 AND response_status_code < 500)", Alias: "num4XX"},
+ },
+ },
+ },
+ },
+ },
+ }
+
+ return &reqV5, startMs, endMs, nil
+}
+
+// executeQuery calls the underlying Querier with the provided request.
+func (m *module) executeQuery(ctx context.Context, orgUUID valuer.UUID, qr *qbtypes.QueryRangeRequest) (*qbtypes.QueryRangeResponse, error) {
+ return m.Querier.QueryRange(ctx, orgUUID, qr)
+}
+
+// mapQueryRangeRespToServices converts the raw query response into service items and collected service names.
+func (m *module) mapQueryRangeRespToServices(resp *qbtypes.QueryRangeResponse, startMs, endMs uint64) ([]*servicetypesv1.ResponseItem, []string) {
+ if resp == nil || len(resp.Data.Results) == 0 { // no rows
+ return []*servicetypesv1.ResponseItem{}, []string{}
+ }
+
+ sd, ok := resp.Data.Results[0].(*qbtypes.ScalarData) // empty rows
+ if !ok || sd == nil {
+ return []*servicetypesv1.ResponseItem{}, []string{}
+ }
+
+ // this stores the index at which service name is found in the response
+ serviceNameRespIndex := -1
+ aggIndexMappings := map[int]int{}
+ for i, c := range sd.Columns {
+ switch c.Type {
+ case qbtypes.ColumnTypeGroup:
+ if c.TelemetryFieldKey.Name == "service.name" {
+ serviceNameRespIndex = i
+ }
+ case qbtypes.ColumnTypeAggregation:
+ aggIndexMappings[int(c.AggregationIndex)] = i
+ }
+ }
+
+ periodSeconds := float64((endMs - startMs) / 1000)
+
+ out := make([]*servicetypesv1.ResponseItem, 0, len(sd.Data))
+ serviceNames := make([]string, 0, len(sd.Data))
+ for _, row := range sd.Data {
+ svcName := fmt.Sprintf("%v", row[serviceNameRespIndex])
+ serviceNames = append(serviceNames, svcName)
+
+ p99 := toFloat(row, aggIndexMappings[0])
+ avgDuration := toFloat(row, aggIndexMappings[1])
+ numCalls := toUint64(row, aggIndexMappings[2])
+ numErrors := toUint64(row, aggIndexMappings[3])
+ num4xx := toUint64(row, aggIndexMappings[4])
+
+ callRate := 0.0
+ if numCalls > 0 {
+ callRate = float64(numCalls) / periodSeconds
+ }
+ errorRate := 0.0
+ if numCalls > 0 {
+ errorRate = float64(numErrors) * 100 / float64(numCalls) // percentage
+ }
+ fourXXRate := 0.0
+ if numCalls > 0 {
+ fourXXRate = float64(num4xx) * 100 / float64(numCalls) // percentage
+ }
+
+ out = append(out, &servicetypesv1.ResponseItem{
+ ServiceName: svcName,
+ Percentile99: p99,
+ AvgDuration: avgDuration,
+ NumCalls: numCalls,
+ CallRate: callRate,
+ NumErrors: numErrors,
+ ErrorRate: errorRate,
+ Num4XX: num4xx,
+ FourXXRate: fourXXRate,
+ DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}},
+ })
+ }
+
+ return out, serviceNames
+}
+
+// attachTopLevelOps fetches top-level ops from TelemetryStore and attaches them to items.
+func (m *module) attachTopLevelOps(ctx context.Context, serviceNames []string, startMs uint64, items []*servicetypesv1.ResponseItem) error {
+ startTime := time.UnixMilli(int64(startMs)).UTC()
+ opsMap, err := m.FetchTopLevelOperations(ctx, startTime, serviceNames)
+ if err != nil {
+ return err
+ }
+ applyOpsToItems(items, opsMap)
+ return nil
+}
+
+func (m *module) buildTopOpsQueryRangeRequest(req *servicetypesv1.OperationsRequest) (*qbtypes.QueryRangeRequest, error) {
+ if req.Service == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "service is required")
+ }
+ startNs, err := strconv.ParseUint(req.Start, 10, 64)
+ if err != nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid start time: %v", err)
+ }
+ endNs, err := strconv.ParseUint(req.End, 10, 64)
+ if err != nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid end time: %v", err)
+ }
+ if startNs >= endNs {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "start must be before end")
+ }
+ if req.Limit < 1 || req.Limit > 5000 {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "limit must be between 1 and 5000")
+ }
+ if err := validateTagFilterItems(req.Tags); err != nil {
+ return nil, err
+ }
+
+ startMs := startNs / 1_000_000
+ endMs := endNs / 1_000_000
+
+ serviceTag := servicetypesv1.TagFilterItem{
+ Key: "service.name",
+ Operator: "in",
+ StringValues: []string{req.Service},
+ }
+ tags := append([]servicetypesv1.TagFilterItem{serviceTag}, req.Tags...)
+ filterExpr, variables := buildFilterExpression(tags)
+
+ reqV5 := qbtypes.QueryRangeRequest{
+ Start: startMs,
+ End: endMs,
+ RequestType: qbtypes.RequestTypeScalar,
+ Variables: variables,
+ CompositeQuery: qbtypes.CompositeQuery{
+ Queries: []qbtypes.QueryEnvelope{
+ {Type: qbtypes.QueryTypeBuilder,
+ Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
+ Name: "A",
+ Signal: telemetrytypes.SignalTraces,
+ Filter: &qbtypes.Filter{Expression: filterExpr},
+ GroupBy: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
+ Name: "name",
+ FieldContext: telemetrytypes.FieldContextSpan,
+ FieldDataType: telemetrytypes.FieldDataTypeString,
+ }},
+ },
+ Aggregations: []qbtypes.TraceAggregation{
+ {Expression: "p50(duration_nano)", Alias: "p50"},
+ {Expression: "p95(duration_nano)", Alias: "p95"},
+ {Expression: "p99(duration_nano)", Alias: "p99"},
+ {Expression: "count()", Alias: "numCalls"},
+ {Expression: "countIf(status_code = 2)", Alias: "errorCount"},
+ },
+ Order: []qbtypes.OrderBy{
+ {Key: qbtypes.OrderByKey{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "p99"}}, Direction: qbtypes.OrderDirectionDesc},
+ },
+ Limit: req.Limit,
+ },
+ },
+ },
+ },
+ }
+ return &reqV5, nil
+}
+
+func (m *module) mapTopOpsQueryRangeResp(resp *qbtypes.QueryRangeResponse) []servicetypesv1.OperationItem {
+ if resp == nil || len(resp.Data.Results) == 0 {
+ return []servicetypesv1.OperationItem{}
+ }
+ sd, ok := resp.Data.Results[0].(*qbtypes.ScalarData)
+ if !ok || sd == nil {
+ return []servicetypesv1.OperationItem{}
+ }
+
+ nameIdx := -1
+ aggIdx := map[int]int{}
+ for i, c := range sd.Columns {
+ switch c.Type {
+ case qbtypes.ColumnTypeGroup:
+ if c.TelemetryFieldKey.Name == "name" {
+ nameIdx = i
+ }
+ case qbtypes.ColumnTypeAggregation:
+ aggIdx[int(c.AggregationIndex)] = i
+ }
+ }
+
+ out := make([]servicetypesv1.OperationItem, 0, len(sd.Data))
+ for _, row := range sd.Data {
+ item := servicetypesv1.OperationItem{
+ Name: fmt.Sprintf("%v", row[nameIdx]),
+ P50: toFloat(row, aggIdx[0]),
+ P95: toFloat(row, aggIdx[1]),
+ P99: toFloat(row, aggIdx[2]),
+ NumCalls: toUint64(row, aggIdx[3]),
+ ErrorCount: toUint64(row, aggIdx[4]),
+ }
+ out = append(out, item)
+ }
+ return out
+}
+
+func (m *module) buildEntryPointOpsQueryRangeRequest(req *servicetypesv1.OperationsRequest) (*qbtypes.QueryRangeRequest, error) {
+ if req.Service == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "service is required")
+ }
+ startNs, err := strconv.ParseUint(req.Start, 10, 64)
+ if err != nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid start time: %v", err)
+ }
+ endNs, err := strconv.ParseUint(req.End, 10, 64)
+ if err != nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid end time: %v", err)
+ }
+ if startNs >= endNs {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "start must be before end")
+ }
+ if req.Limit < 1 || req.Limit > 5000 {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "limit must be between 1 and 5000")
+ }
+ if err := validateTagFilterItems(req.Tags); err != nil {
+ return nil, err
+ }
+
+ startMs := startNs / 1_000_000
+ endMs := endNs / 1_000_000
+
+ serviceTag := servicetypesv1.TagFilterItem{
+ Key: "service.name",
+ Operator: "in",
+ StringValues: []string{req.Service},
+ }
+ tags := append([]servicetypesv1.TagFilterItem{serviceTag}, req.Tags...)
+ filterExpr, variables := buildFilterExpression(tags)
+ scopeExpr := "isRoot = true OR isEntryPoint = true"
+ if filterExpr != "" {
+ filterExpr = "(" + filterExpr + ") AND (" + scopeExpr + ")"
+ } else {
+ filterExpr = scopeExpr
+ }
+
+ reqV5 := qbtypes.QueryRangeRequest{
+ Start: startMs,
+ End: endMs,
+ RequestType: qbtypes.RequestTypeScalar,
+ Variables: variables,
+ CompositeQuery: qbtypes.CompositeQuery{
+ Queries: []qbtypes.QueryEnvelope{
+ {Type: qbtypes.QueryTypeBuilder,
+ Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
+ Name: "A",
+ Signal: telemetrytypes.SignalTraces,
+ Filter: &qbtypes.Filter{Expression: filterExpr},
+ GroupBy: []qbtypes.GroupByKey{
+ {TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
+ Name: "name",
+ FieldContext: telemetrytypes.FieldContextSpan,
+ FieldDataType: telemetrytypes.FieldDataTypeString,
+ }},
+ },
+ Aggregations: []qbtypes.TraceAggregation{
+ {Expression: "p50(duration_nano)", Alias: "p50"},
+ {Expression: "p95(duration_nano)", Alias: "p95"},
+ {Expression: "p99(duration_nano)", Alias: "p99"},
+ {Expression: "count()", Alias: "numCalls"},
+ {Expression: "countIf(status_code = 2)", Alias: "errorCount"},
+ },
+ Order: []qbtypes.OrderBy{
+ {Key: qbtypes.OrderByKey{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "p99"}}, Direction: qbtypes.OrderDirectionDesc},
+ },
+ Limit: req.Limit,
+ },
+ },
+ },
+ },
+ }
+ return &reqV5, nil
+}
+
+func (m *module) mapEntryPointOpsQueryRangeResp(resp *qbtypes.QueryRangeResponse) []servicetypesv1.OperationItem {
+ if resp == nil || len(resp.Data.Results) == 0 {
+ return []servicetypesv1.OperationItem{}
+ }
+ sd, ok := resp.Data.Results[0].(*qbtypes.ScalarData)
+ if !ok || sd == nil {
+ return []servicetypesv1.OperationItem{}
+ }
+
+ nameIdx := -1
+ aggIdx := map[int]int{}
+ for i, c := range sd.Columns {
+ switch c.Type {
+ case qbtypes.ColumnTypeGroup:
+ if c.TelemetryFieldKey.Name == "name" {
+ nameIdx = i
+ }
+ case qbtypes.ColumnTypeAggregation:
+ aggIdx[int(c.AggregationIndex)] = i
+ }
+ }
+
+ out := make([]servicetypesv1.OperationItem, 0, len(sd.Data))
+ for _, row := range sd.Data {
+ item := servicetypesv1.OperationItem{
+ Name: fmt.Sprintf("%v", row[nameIdx]),
+ P50: toFloat(row, aggIdx[0]),
+ P95: toFloat(row, aggIdx[1]),
+ P99: toFloat(row, aggIdx[2]),
+ NumCalls: toUint64(row, aggIdx[3]),
+ ErrorCount: toUint64(row, aggIdx[4]),
+ }
+ out = append(out, item)
+ }
+ return out
+}
diff --git a/pkg/modules/services/implservices/module_test.go b/pkg/modules/services/implservices/module_test.go
new file mode 100644
index 0000000000..e5ce9d0ee7
--- /dev/null
+++ b/pkg/modules/services/implservices/module_test.go
@@ -0,0 +1,773 @@
+package implservices
+
+import (
+ "testing"
+
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/types/servicetypes/servicetypesv1"
+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestBuildQueryRangeRequest(t *testing.T) {
+ m := &module{}
+
+ tests := []struct {
+ name string
+ req servicetypesv1.Request
+ wantErr string
+ assertOK func(t *testing.T, qr *qbtypes.QueryRangeRequest, startMs, endMs uint64)
+ }{
+ {
+ name: "valid with tags builds scope+filter and query",
+ req: servicetypesv1.Request{
+ Start: "1000000000", // 1s in ns -> 1000 ms
+ End: "2000000000", // 2s in ns -> 2000 ms
+ Tags: []servicetypesv1.TagFilterItem{
+ {Key: "service.name", Operator: "in", StringValues: []string{"frontend", "backend"}},
+ {Key: "env", Operator: "notin", StringValues: []string{"prod"}},
+ },
+ },
+ assertOK: func(t *testing.T, qr *qbtypes.QueryRangeRequest, startMs, endMs uint64) {
+ assert.Equal(t, uint64(1000), startMs)
+ assert.Equal(t, uint64(2000), endMs)
+ assert.Equal(t, qbtypes.RequestTypeScalar, qr.RequestType)
+ assert.Equal(t, 1, len(qr.CompositeQuery.Queries))
+
+ qe := qr.CompositeQuery.Queries[0]
+ assert.Equal(t, qbtypes.QueryTypeBuilder, qe.Type)
+
+ // Spec should be a traces builder query
+ spec, ok := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ if !ok {
+ t.Fatalf("unexpected spec type: %T", qe.Spec)
+ }
+ assert.Equal(t, telemetrytypes.SignalTraces, spec.Signal)
+
+ // Filter should include both user filter and the scope expression
+ assert.NotNil(t, spec.Filter)
+ expr := spec.Filter.Expression
+ assert.Contains(t, expr, "service.name IN $1")
+ assert.Contains(t, expr, "env NOT IN $2")
+ assert.Contains(t, expr, "isRoot = true OR isEntryPoint = true")
+
+ // GroupBy should include service.name
+ if assert.Equal(t, 1, len(spec.GroupBy)) {
+ assert.Equal(t, "service.name", spec.GroupBy[0].TelemetryFieldKey.Name)
+ }
+
+ // Aggregations should match expected expressions and aliases
+ if assert.Equal(t, 5, len(spec.Aggregations)) {
+ assert.Equal(t, "p99(duration_nano)", spec.Aggregations[0].Expression)
+ assert.Equal(t, "p99", spec.Aggregations[0].Alias)
+ assert.Equal(t, "avg(duration_nano)", spec.Aggregations[1].Expression)
+ assert.Equal(t, "avgDuration", spec.Aggregations[1].Alias)
+ assert.Equal(t, "count()", spec.Aggregations[2].Expression)
+ assert.Equal(t, "numCalls", spec.Aggregations[2].Alias)
+ assert.Equal(t, "countIf(status_code = 2)", spec.Aggregations[3].Expression)
+ assert.Equal(t, "numErrors", spec.Aggregations[3].Alias)
+ assert.Equal(t, "countIf(response_status_code >= 400 AND response_status_code < 500)", spec.Aggregations[4].Expression)
+ assert.Equal(t, "num4XX", spec.Aggregations[4].Alias)
+ }
+ },
+ },
+ {
+ name: "valid without tags uses only scope filter",
+ req: servicetypesv1.Request{
+ Start: "3000000000", // 3s ns -> 3000 ms
+ End: "5000000000", // 5s ns -> 5000 ms
+ },
+ assertOK: func(t *testing.T, qr *qbtypes.QueryRangeRequest, startMs, endMs uint64) {
+ assert.Equal(t, uint64(3000), startMs)
+ assert.Equal(t, uint64(5000), endMs)
+ qe := qr.CompositeQuery.Queries[0]
+ spec := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ if assert.NotNil(t, spec.Filter) {
+ assert.Equal(t, "isRoot = true OR isEntryPoint = true", spec.Filter.Expression)
+ }
+ },
+ },
+ {
+ name: "invalid start",
+ req: servicetypesv1.Request{Start: "abc", End: "100"},
+ wantErr: "invalid start time",
+ },
+ {
+ name: "invalid end",
+ req: servicetypesv1.Request{Start: "100", End: "abc"},
+ wantErr: "invalid end time",
+ },
+ {
+ name: "start not before end",
+ req: servicetypesv1.Request{Start: "2000", End: "2000"},
+ wantErr: "start must be before end",
+ },
+ {
+ name: "start greater than end",
+ req: servicetypesv1.Request{Start: "2001", End: "2000"},
+ wantErr: "start must be before end",
+ },
+ {
+ name: "invalid tag: missing key -> error",
+ req: servicetypesv1.Request{
+ Start: "1000000000",
+ End: "2000000000",
+ Tags: []servicetypesv1.TagFilterItem{{Key: "", Operator: "in", StringValues: []string{"x"}}},
+ },
+ wantErr: "key is required",
+ },
+ {
+ name: "invalid tag: unsupported operator -> error",
+ req: servicetypesv1.Request{
+ Start: "1000000000",
+ End: "2000000000",
+ Tags: []servicetypesv1.TagFilterItem{{Key: "env", Operator: "equals", StringValues: []string{"staging"}}},
+ },
+ wantErr: "only in and notin operators are supported",
+ },
+ {
+ name: "invalid tag: in but no values -> error",
+ req: servicetypesv1.Request{
+ Start: "1000000000",
+ End: "2000000000",
+ Tags: []servicetypesv1.TagFilterItem{{Key: "env", Operator: "in"}},
+ },
+ wantErr: "at least one of stringValues, boolValues, or numberValues must be populated",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ qr, startMs, endMs, err := m.buildQueryRangeRequest(&tt.req)
+ if tt.wantErr != "" {
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ return
+ }
+ assert.NoError(t, err)
+ if tt.assertOK != nil {
+ tt.assertOK(t, qr, startMs, endMs)
+ }
+ })
+ }
+}
+
+func TestMapQueryRangeRespToServices(t *testing.T) {
+ m := &module{}
+
+ groupCol := &qbtypes.ColumnDescriptor{
+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"},
+ Type: qbtypes.ColumnTypeGroup,
+ }
+ agg := func(idx int64) *qbtypes.ColumnDescriptor {
+ return &qbtypes.ColumnDescriptor{AggregationIndex: idx, Type: qbtypes.ColumnTypeAggregation}
+ }
+
+ tests := []struct {
+ name string
+ resp *qbtypes.QueryRangeResponse
+ startMs, endMs uint64
+ wantItems []*servicetypesv1.ResponseItem
+ wantServices []string
+ }{
+ {
+ name: "empty response -> no items",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{Results: []any{}},
+ },
+ startMs: 1000, endMs: 2000,
+ wantItems: []*servicetypesv1.ResponseItem{},
+ wantServices: []string{},
+ },
+ {
+ name: "no ScalarData -> no items",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{Results: []any{"not-scalar"}},
+ },
+ startMs: 1000, endMs: 2000,
+ wantItems: []*servicetypesv1.ResponseItem{},
+ wantServices: []string{},
+ },
+ {
+ name: "missing service.name column -> no items",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{
+ Results: []any{&qbtypes.ScalarData{
+ QueryName: "A",
+ Columns: []*qbtypes.ColumnDescriptor{agg(0)}, Data: [][]any{},
+ },
+ },
+ },
+ },
+ startMs: 1000, endMs: 2000,
+ wantItems: []*servicetypesv1.ResponseItem{},
+ wantServices: []string{},
+ },
+ {
+ name: "single row maps fields and rates",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{
+ Results: []any{
+ &qbtypes.ScalarData{
+ QueryName: "A",
+ Columns: []*qbtypes.ColumnDescriptor{groupCol, agg(0), agg(1), agg(2), agg(3), agg(4)},
+ Data: [][]any{{"svc-a", float64(123.0), float64(45.0), uint64(10), uint64(2), uint64(1)}},
+ },
+ },
+ },
+ },
+ startMs: 0, endMs: 10000, // 10s window -> callRate = 10/10=1, errorRate=20%, fourXXRate=10%
+ wantItems: []*servicetypesv1.ResponseItem{
+ {
+ ServiceName: "svc-a",
+ Percentile99: 123.0,
+ AvgDuration: 45.0,
+ NumCalls: 10,
+ CallRate: 1.0,
+ NumErrors: 2,
+ ErrorRate: 20.0, // in percentage
+ Num4XX: 1,
+ FourXXRate: 10.0, // in percentage
+ DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}},
+ },
+ },
+ wantServices: []string{"svc-a"},
+ },
+ {
+ name: "group column in middle maps correctly",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{
+ Results: []any{&qbtypes.ScalarData{
+ QueryName: "A",
+ Columns: []*qbtypes.ColumnDescriptor{agg(0), groupCol, agg(1), agg(2), agg(3), agg(4)},
+ Data: [][]any{{float64(200.0), "svc-mid", float64(50.0), uint64(20), uint64(5), uint64(2)}},
+ },
+ },
+ },
+ },
+ startMs: 0, endMs: 10000, // 10s window -> callRate = 2, errorRate=25%, fourXXRate=10%
+ wantItems: []*servicetypesv1.ResponseItem{
+ {
+ ServiceName: "svc-mid",
+ Percentile99: 200.0,
+ AvgDuration: 50.0,
+ NumCalls: 20,
+ CallRate: 2.0,
+ NumErrors: 5,
+ ErrorRate: 25.0, // in percentage
+ Num4XX: 2,
+ FourXXRate: 10.0, // in percentage
+ DataWarning: servicetypesv1.DataWarning{TopLevelOps: []string{}},
+ },
+ },
+ wantServices: []string{"svc-mid"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotItems, gotServices := m.mapQueryRangeRespToServices(tt.resp, tt.startMs, tt.endMs)
+ assert.Equal(t, tt.wantServices, gotServices)
+ assert.Equal(t, len(tt.wantItems), len(gotItems))
+ if len(tt.wantItems) == 1 {
+ assert.InDelta(t, tt.wantItems[0].Percentile99, gotItems[0].Percentile99, 1e-9)
+ assert.InDelta(t, tt.wantItems[0].AvgDuration, gotItems[0].AvgDuration, 1e-9)
+ assert.Equal(t, tt.wantItems[0].NumCalls, gotItems[0].NumCalls)
+ assert.InDelta(t, tt.wantItems[0].CallRate, gotItems[0].CallRate, 1e-9)
+ assert.Equal(t, tt.wantItems[0].NumErrors, gotItems[0].NumErrors)
+ assert.InDelta(t, tt.wantItems[0].ErrorRate, gotItems[0].ErrorRate, 1e-9)
+ assert.Equal(t, tt.wantItems[0].Num4XX, gotItems[0].Num4XX)
+ assert.InDelta(t, tt.wantItems[0].FourXXRate, gotItems[0].FourXXRate, 1e-9)
+ assert.Equal(t, tt.wantItems[0].DataWarning.TopLevelOps, gotItems[0].DataWarning.TopLevelOps)
+ assert.Equal(t, tt.wantItems[0].ServiceName, gotItems[0].ServiceName)
+ }
+ })
+ }
+}
+
+func TestBuildTopOpsQueryRangeRequest(t *testing.T) {
+ m := &module{}
+
+ tests := []struct {
+ name string
+ req servicetypesv1.OperationsRequest
+ wantErr string
+ assertQ func(t *testing.T, qr *qbtypes.QueryRangeRequest)
+ }{
+ {
+ name: "with tag filters (In, NotIn) and no scope",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "frontend",
+ Tags: []servicetypesv1.TagFilterItem{
+ {Key: "deployment.environment", Operator: "NotIn", StringValues: []string{"prod", "staging"}},
+ {Key: "http.method", Operator: "in", StringValues: []string{"GET"}},
+ },
+ Limit: 10,
+ },
+ assertQ: func(t *testing.T, qr *qbtypes.QueryRangeRequest) {
+ if assert.Equal(t, 1, len(qr.CompositeQuery.Queries)) {
+ qe := qr.CompositeQuery.Queries[0]
+ spec, ok := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ if !ok {
+ t.Fatalf("unexpected spec type: %T", qe.Spec)
+ }
+ assert.NotNil(t, spec.Filter)
+ expr := spec.Filter.Expression
+ // service.name added first as $1, then user tags as $2, $3
+ assert.Contains(t, expr, "service.name IN $1")
+ assert.Contains(t, expr, "deployment.environment NOT IN $2")
+ assert.Contains(t, expr, "http.method IN $3")
+ assert.NotContains(t, expr, "isRoot = true OR isEntryPoint = true")
+
+ // variables populated correctly
+ if v, ok := qr.Variables["1"]; assert.True(t, ok) {
+ vals, _ := v.Value.([]any)
+ if assert.Equal(t, 1, len(vals)) {
+ assert.Equal(t, "frontend", vals[0])
+ }
+ }
+ if v, ok := qr.Variables["2"]; assert.True(t, ok) {
+ vals, _ := v.Value.([]any)
+ if assert.Equal(t, 2, len(vals)) {
+ assert.ElementsMatch(t, []any{"prod", "staging"}, vals)
+ }
+ }
+ if v, ok := qr.Variables["3"]; assert.True(t, ok) {
+ vals, _ := v.Value.([]any)
+ if assert.Equal(t, 1, len(vals)) {
+ assert.Equal(t, "GET", vals[0])
+ }
+ }
+ }
+ },
+ },
+ {
+ name: "valid minimal filters, no scope added",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000", // 1s ns -> 1000 ms
+ End: "4000000000", // 4s ns -> 4000 ms
+ Service: "cartservice",
+ Limit: 50,
+ },
+ assertQ: func(t *testing.T, qr *qbtypes.QueryRangeRequest) {
+ assert.Equal(t, qbtypes.RequestTypeScalar, qr.RequestType)
+ if assert.Equal(t, 1, len(qr.CompositeQuery.Queries)) {
+ qe := qr.CompositeQuery.Queries[0]
+ assert.Equal(t, qbtypes.QueryTypeBuilder, qe.Type)
+ spec, ok := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ if !ok {
+ t.Fatalf("unexpected spec type: %T", qe.Spec)
+ }
+ assert.Equal(t, telemetrytypes.SignalTraces, spec.Signal)
+ if assert.NotNil(t, spec.Filter) {
+ expr := spec.Filter.Expression
+ // should contain only tag filter for service.name and NOT the scope expression
+ assert.Contains(t, expr, "service.name IN $1")
+ assert.NotContains(t, expr, "isRoot = true OR isEntryPoint = true")
+ }
+ if assert.Equal(t, 1, len(spec.GroupBy)) {
+ assert.Equal(t, "name", spec.GroupBy[0].TelemetryFieldKey.Name)
+ assert.Equal(t, telemetrytypes.FieldContextSpan, spec.GroupBy[0].TelemetryFieldKey.FieldContext)
+ }
+ if assert.Equal(t, 5, len(spec.Aggregations)) {
+ assert.Equal(t, "p50(duration_nano)", spec.Aggregations[0].Expression)
+ assert.Equal(t, "p50", spec.Aggregations[0].Alias)
+ assert.Equal(t, "p95(duration_nano)", spec.Aggregations[1].Expression)
+ assert.Equal(t, "p95", spec.Aggregations[1].Alias)
+ assert.Equal(t, "p99(duration_nano)", spec.Aggregations[2].Expression)
+ assert.Equal(t, "p99", spec.Aggregations[2].Alias)
+ assert.Equal(t, "count()", spec.Aggregations[3].Expression)
+ assert.Equal(t, "numCalls", spec.Aggregations[3].Alias)
+ assert.Equal(t, "countIf(status_code = 2)", spec.Aggregations[4].Expression)
+ assert.Equal(t, "errorCount", spec.Aggregations[4].Alias)
+ }
+ if assert.Equal(t, 1, len(spec.Order)) {
+ assert.Equal(t, "p99", spec.Order[0].Key.TelemetryFieldKey.Name)
+ assert.Equal(t, qbtypes.OrderDirectionDesc, spec.Order[0].Direction)
+ }
+ assert.Equal(t, 50, spec.Limit)
+ }
+ },
+ },
+ {
+ name: "missing service -> error",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "2"},
+ wantErr: "service is required",
+ },
+ {
+ name: "invalid limit low",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "2", Service: "s", Limit: 0},
+ wantErr: "limit must be between 1 and 5000",
+ },
+ {
+ name: "invalid limit high",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "2", Service: "s", Limit: 5001},
+ wantErr: "limit must be between 1 and 5000",
+ },
+ {
+ name: "invalid start",
+ req: servicetypesv1.OperationsRequest{Start: "abc", End: "2", Service: "s"},
+ wantErr: "invalid start time",
+ },
+ {
+ name: "invalid end",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "abc", Service: "s"},
+ wantErr: "invalid end time",
+ },
+ {
+ name: "start not before end",
+ req: servicetypesv1.OperationsRequest{Start: "2", End: "2", Service: "s"},
+ wantErr: "start must be before end",
+ },
+ {
+ name: "invalid tag in top ops -> error",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "frontend",
+ Limit: 10,
+ Tags: []servicetypesv1.TagFilterItem{{Key: "", Operator: "in", StringValues: []string{"x"}}},
+ },
+ wantErr: "key is required",
+ },
+ {
+ name: "invalid tag: in but no values -> error (top ops)",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "frontend",
+ Tags: []servicetypesv1.TagFilterItem{{Key: "env", Operator: "in"}},
+ Limit: 10,
+ },
+ wantErr: "at least one of stringValues, boolValues, or numberValues must be populated",
+ },
+ {
+ name: "valid tag in top ops -> ok",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "frontend",
+ Tags: []servicetypesv1.TagFilterItem{{Key: "deployment.environment", Operator: "in", StringValues: []string{"prod"}}},
+ Limit: 5,
+ },
+ assertQ: func(t *testing.T, qr *qbtypes.QueryRangeRequest) {
+ qe := qr.CompositeQuery.Queries[0]
+ spec := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ assert.Contains(t, spec.Filter.Expression, "service.name IN $1")
+ assert.Contains(t, spec.Filter.Expression, "deployment.environment IN $2")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ qr, err := m.buildTopOpsQueryRangeRequest(&tt.req)
+ if tt.wantErr != "" {
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ return
+ }
+ assert.NoError(t, err)
+ if tt.assertQ != nil {
+ tt.assertQ(t, qr)
+ }
+ })
+ }
+}
+
+func TestMapTopOpsQueryRangeResp(t *testing.T) {
+ m := &module{}
+
+ nameGroup := &qbtypes.ColumnDescriptor{
+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "name"},
+ Type: qbtypes.ColumnTypeGroup,
+ }
+ agg := func(idx int64) *qbtypes.ColumnDescriptor {
+ return &qbtypes.ColumnDescriptor{AggregationIndex: idx, Type: qbtypes.ColumnTypeAggregation}
+ }
+
+ tests := []struct {
+ name string
+ resp *qbtypes.QueryRangeResponse
+ want []servicetypesv1.OperationItem
+ }{
+ {
+ name: "empty results -> empty slice",
+ resp: &qbtypes.QueryRangeResponse{Type: qbtypes.RequestTypeScalar, Data: qbtypes.QueryData{Results: []any{}}},
+ want: []servicetypesv1.OperationItem{},
+ },
+ {
+ name: "non-scalar result -> empty slice",
+ resp: &qbtypes.QueryRangeResponse{Type: qbtypes.RequestTypeScalar, Data: qbtypes.QueryData{Results: []any{"x"}}},
+ want: []servicetypesv1.OperationItem{},
+ },
+ {
+ name: "single row maps correctly",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{Results: []any{&qbtypes.ScalarData{
+ QueryName: "A",
+ Columns: []*qbtypes.ColumnDescriptor{nameGroup, agg(0), agg(1), agg(2), agg(3), agg(4)},
+ Data: [][]any{{"opA", float64(10), float64(20), float64(30), uint64(100), uint64(7)}},
+ }}},
+ },
+ want: []servicetypesv1.OperationItem{{
+ Name: "opA",
+ P50: 10,
+ P95: 20,
+ P99: 30,
+ NumCalls: 100,
+ ErrorCount: 7,
+ }},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := m.mapTopOpsQueryRangeResp(tt.resp)
+ assert.Equal(t, tt.want, got)
+ })
+ }
+}
+
+func TestBuildEntryPointOpsQueryRangeRequest(t *testing.T) {
+ m := &module{}
+
+ tests := []struct {
+ name string
+ req servicetypesv1.OperationsRequest
+ wantErr string
+ assertQ func(t *testing.T, qr *qbtypes.QueryRangeRequest)
+ }{
+ {
+ name: "service only -> scope present, no extra filters",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "cartservice",
+ // no tags
+ Limit: 10,
+ },
+ assertQ: func(t *testing.T, qr *qbtypes.QueryRangeRequest) {
+ if assert.Equal(t, 1, len(qr.CompositeQuery.Queries)) {
+ qe := qr.CompositeQuery.Queries[0]
+ spec, ok := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ if !ok {
+ t.Fatalf("unexpected spec type: %T", qe.Spec)
+ }
+ assert.NotNil(t, spec.Filter)
+ expr := spec.Filter.Expression
+ assert.Contains(t, expr, "service.name IN $1")
+ assert.Contains(t, expr, "isRoot = true OR isEntryPoint = true")
+ // only one variable should exist
+ if assert.Len(t, qr.Variables, 1) {
+ v := qr.Variables["1"]
+ vals, _ := v.Value.([]any)
+ if assert.Equal(t, 1, len(vals)) {
+ assert.Equal(t, "cartservice", vals[0])
+ }
+ }
+ // groupBy is name (span)
+ if assert.Equal(t, 1, len(spec.GroupBy)) {
+ assert.Equal(t, "name", spec.GroupBy[0].TelemetryFieldKey.Name)
+ assert.Equal(t, telemetrytypes.FieldContextSpan, spec.GroupBy[0].TelemetryFieldKey.FieldContext)
+ }
+ }
+ },
+ },
+ {
+ name: "with filters and scope present",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "3000000000",
+ Service: "frontend",
+ Tags: []servicetypesv1.TagFilterItem{
+ {Key: "deployment.environment", Operator: "NotIn", StringValues: []string{"prod", "staging"}},
+ {Key: "http.method", Operator: "in", StringValues: []string{"GET"}},
+ },
+ Limit: 25,
+ },
+ assertQ: func(t *testing.T, qr *qbtypes.QueryRangeRequest) {
+ if assert.Equal(t, 1, len(qr.CompositeQuery.Queries)) {
+ qe := qr.CompositeQuery.Queries[0]
+ spec, ok := qe.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ if !ok {
+ t.Fatalf("unexpected spec type: %T", qe.Spec)
+ }
+ assert.NotNil(t, spec.Filter)
+ expr := spec.Filter.Expression
+ assert.Contains(t, expr, "service.name IN $1")
+ assert.Contains(t, expr, "deployment.environment NOT IN $2")
+ assert.Contains(t, expr, "http.method IN $3")
+ assert.Contains(t, expr, "isRoot = true OR isEntryPoint = true")
+ if assert.Equal(t, 1, len(spec.GroupBy)) {
+ assert.Equal(t, "name", spec.GroupBy[0].TelemetryFieldKey.Name)
+ assert.Equal(t, telemetrytypes.FieldContextSpan, spec.GroupBy[0].TelemetryFieldKey.FieldContext)
+ }
+ if assert.Equal(t, 5, len(spec.Aggregations)) {
+ assert.Equal(t, "p50(duration_nano)", spec.Aggregations[0].Expression)
+ assert.Equal(t, "p50", spec.Aggregations[0].Alias)
+ assert.Equal(t, "p95(duration_nano)", spec.Aggregations[1].Expression)
+ assert.Equal(t, "p95", spec.Aggregations[1].Alias)
+ assert.Equal(t, "p99(duration_nano)", spec.Aggregations[2].Expression)
+ assert.Equal(t, "p99", spec.Aggregations[2].Alias)
+ assert.Equal(t, "count()", spec.Aggregations[3].Expression)
+ assert.Equal(t, "numCalls", spec.Aggregations[3].Alias)
+ assert.Equal(t, "countIf(status_code = 2)", spec.Aggregations[4].Expression)
+ assert.Equal(t, "errorCount", spec.Aggregations[4].Alias)
+ }
+ if assert.Equal(t, 1, len(spec.Order)) {
+ assert.Equal(t, "p99", spec.Order[0].Key.TelemetryFieldKey.Name)
+ assert.Equal(t, qbtypes.OrderDirectionDesc, spec.Order[0].Direction)
+ }
+ assert.Equal(t, 25, spec.Limit)
+ }
+ },
+ },
+ {
+ name: "missing service -> error",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "2"},
+ wantErr: "service is required",
+ },
+ {
+ name: "invalid start",
+ req: servicetypesv1.OperationsRequest{Start: "abc", End: "2", Service: "s"},
+ wantErr: "invalid start time",
+ },
+ {
+ name: "invalid end",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "abc", Service: "s"},
+ wantErr: "invalid end time",
+ },
+ {
+ name: "start not before end",
+ req: servicetypesv1.OperationsRequest{Start: "2", End: "2", Service: "s"},
+ wantErr: "start must be before end",
+ },
+ {
+ name: "invalid limit low",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "2", Service: "s", Limit: 0},
+ wantErr: "limit must be between 1 and 5000",
+ },
+ {
+ name: "invalid limit high",
+ req: servicetypesv1.OperationsRequest{Start: "1", End: "2", Service: "s", Limit: 5001},
+ wantErr: "limit must be between 1 and 5000",
+ },
+ {
+ name: "invalid tag in entry point ops -> error",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "cartservice",
+ Limit: 10,
+ Tags: []servicetypesv1.TagFilterItem{{Key: "", Operator: "notin", StringValues: []string{"x"}}},
+ },
+ wantErr: "key is required",
+ },
+ {
+ name: "invalid tag: notin but no values -> error (entry ops)",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "cartservice",
+ Limit: 10,
+ Tags: []servicetypesv1.TagFilterItem{{Key: "env", Operator: "notin"}},
+ },
+ wantErr: "at least one of stringValues, boolValues, or numberValues must be populated",
+ },
+ {
+ name: "valid tag in entry point ops -> ok",
+ req: servicetypesv1.OperationsRequest{
+ Start: "1000000000",
+ End: "2000000000",
+ Service: "cartservice",
+ Tags: []servicetypesv1.TagFilterItem{{Key: "deployment.environment", Operator: "notin", StringValues: []string{"prod"}}},
+ Limit: 10,
+ },
+ assertQ: func(t *testing.T, qr *qbtypes.QueryRangeRequest) {
+ spec := qr.CompositeQuery.Queries[0].Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
+ assert.Contains(t, spec.Filter.Expression, "service.name IN $1")
+ assert.Contains(t, spec.Filter.Expression, "deployment.environment NOT IN $2")
+ assert.Contains(t, spec.Filter.Expression, "isRoot = true OR isEntryPoint = true")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ qr, err := m.buildEntryPointOpsQueryRangeRequest(&tt.req)
+ if tt.wantErr != "" {
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ return
+ }
+ assert.NoError(t, err)
+ if tt.assertQ != nil {
+ tt.assertQ(t, qr)
+ }
+ })
+ }
+}
+
+func TestMapEntryPointOpsQueryRangeResp(t *testing.T) {
+ m := &module{}
+
+ nameGroup := &qbtypes.ColumnDescriptor{
+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "name"},
+ Type: qbtypes.ColumnTypeGroup,
+ }
+ agg := func(idx int64) *qbtypes.ColumnDescriptor {
+ return &qbtypes.ColumnDescriptor{AggregationIndex: idx, Type: qbtypes.ColumnTypeAggregation}
+ }
+
+ tests := []struct {
+ name string
+ resp *qbtypes.QueryRangeResponse
+ want []servicetypesv1.OperationItem
+ }{
+ {
+ name: "empty results -> empty slice",
+ resp: &qbtypes.QueryRangeResponse{Type: qbtypes.RequestTypeScalar, Data: qbtypes.QueryData{Results: []any{}}},
+ want: []servicetypesv1.OperationItem{},
+ },
+ {
+ name: "non-scalar result -> empty slice",
+ resp: &qbtypes.QueryRangeResponse{Type: qbtypes.RequestTypeScalar, Data: qbtypes.QueryData{Results: []any{"x"}}},
+ want: []servicetypesv1.OperationItem{},
+ },
+ {
+ name: "single row maps correctly",
+ resp: &qbtypes.QueryRangeResponse{
+ Type: qbtypes.RequestTypeScalar,
+ Data: qbtypes.QueryData{Results: []any{&qbtypes.ScalarData{
+ QueryName: "A",
+ Columns: []*qbtypes.ColumnDescriptor{nameGroup, agg(0), agg(1), agg(2), agg(3), agg(4)},
+ Data: [][]any{{"op-entry", float64(5), float64(15), float64(25), uint64(12), uint64(1)}},
+ }}},
+ },
+ want: []servicetypesv1.OperationItem{{
+ Name: "op-entry",
+ P50: 5,
+ P95: 15,
+ P99: 25,
+ NumCalls: 12,
+ ErrorCount: 1,
+ }},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := m.mapEntryPointOpsQueryRangeResp(tt.resp)
+ assert.Equal(t, tt.want, got)
+ })
+ }
+}
diff --git a/pkg/modules/services/services.go b/pkg/modules/services/services.go
new file mode 100644
index 0000000000..191c41ad48
--- /dev/null
+++ b/pkg/modules/services/services.go
@@ -0,0 +1,25 @@
+package services
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/types/servicetypes/servicetypesv1"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+// Handler exposes HTTP handler for services_qbv5
+type Handler interface {
+ Get(http.ResponseWriter, *http.Request)
+ GetTopOperations(http.ResponseWriter, *http.Request)
+ GetEntryPointOperations(http.ResponseWriter, *http.Request)
+}
+
+// Module represents the services QBv5 module interface
+type Module interface {
+ Get(ctx context.Context, orgID valuer.UUID, req *servicetypesv1.Request) ([]*servicetypesv1.ResponseItem, error)
+ FetchTopLevelOperations(ctx context.Context, start time.Time, services []string) (map[string][]string, error)
+ GetTopOperations(ctx context.Context, orgID valuer.UUID, req *servicetypesv1.OperationsRequest) ([]servicetypesv1.OperationItem, error)
+ GetEntryPointOperations(ctx context.Context, orgID valuer.UUID, req *servicetypesv1.OperationsRequest) ([]servicetypesv1.OperationItem, error)
+}
diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go
index d6615c9224..ad896188fb 100644
--- a/pkg/query-service/app/http_handler.go
+++ b/pkg/query-service/app/http_handler.go
@@ -532,10 +532,15 @@ func (aH *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {
router.HandleFunc("/api/v1/explorer/views/{viewId}", am.EditAccess(aH.Signoz.Handlers.SavedView.Delete)).Methods(http.MethodDelete)
router.HandleFunc("/api/v1/event", am.ViewAccess(aH.registerEvent)).Methods(http.MethodPost)
- router.HandleFunc("/api/v1/services", am.ViewAccess(aH.getServices)).Methods(http.MethodPost)
+ router.HandleFunc("/api/v1/services", am.ViewAccess(aH.getServices)).Methods(http.MethodPost) // Deprecated Usage, use the below endpoint /v2/services
+ router.HandleFunc("/api/v2/services", am.ViewAccess(aH.Signoz.Handlers.Services.Get)).Methods(http.MethodPost)
router.HandleFunc("/api/v1/services/list", am.ViewAccess(aH.getServicesList)).Methods(http.MethodGet)
+
+ router.HandleFunc("/api/v2/service/top_operations", am.ViewAccess(aH.Signoz.Handlers.Services.GetTopOperations)).Methods(http.MethodPost)
router.HandleFunc("/api/v1/service/top_operations", am.ViewAccess(aH.getTopOperations)).Methods(http.MethodPost)
router.HandleFunc("/api/v1/service/top_level_operations", am.ViewAccess(aH.getServicesTopLevelOps)).Methods(http.MethodPost)
+
+ router.HandleFunc("/api/v2/service/entry_point_operations", am.ViewAccess(aH.Signoz.Handlers.Services.GetEntryPointOperations)).Methods(http.MethodPost)
router.HandleFunc("/api/v1/service/entry_point_operations", am.ViewAccess(aH.getEntryPointOps)).Methods(http.MethodPost)
router.HandleFunc("/api/v1/traces/{traceId}", am.ViewAccess(aH.SearchTraces)).Methods(http.MethodGet)
router.HandleFunc("/api/v1/usage", am.ViewAccess(aH.getUsage)).Methods(http.MethodGet)
diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.go
index ae1461a613..891a4e41c2 100644
--- a/pkg/signoz/handler.go
+++ b/pkg/signoz/handler.go
@@ -18,6 +18,8 @@ import (
"github.com/SigNoz/signoz/pkg/modules/rawdataexport/implrawdataexport"
"github.com/SigNoz/signoz/pkg/modules/savedview"
"github.com/SigNoz/signoz/pkg/modules/savedview/implsavedview"
+ "github.com/SigNoz/signoz/pkg/modules/services"
+ "github.com/SigNoz/signoz/pkg/modules/services/implservices"
"github.com/SigNoz/signoz/pkg/modules/session"
"github.com/SigNoz/signoz/pkg/modules/session/implsession"
"github.com/SigNoz/signoz/pkg/modules/spanpercentile"
@@ -41,6 +43,7 @@ type Handlers struct {
AuthDomain authdomain.Handler
Session session.Handler
SpanPercentile spanpercentile.Handler
+ Services services.Handler
}
func NewHandlers(modules Modules, providerSettings factory.ProviderSettings) Handlers {
@@ -56,6 +59,7 @@ func NewHandlers(modules Modules, providerSettings factory.ProviderSettings) Han
RawDataExport: implrawdataexport.NewHandler(modules.RawDataExport),
AuthDomain: implauthdomain.NewHandler(modules.AuthDomain),
Session: implsession.NewHandler(modules.Session),
+ Services: implservices.NewHandler(modules.Services),
SpanPercentile: implspanpercentile.NewHandler(modules.SpanPercentile),
}
}
diff --git a/pkg/signoz/handler_test.go b/pkg/signoz/handler_test.go
index f3d98f3af6..afe0ccdc83 100644
--- a/pkg/signoz/handler_test.go
+++ b/pkg/signoz/handler_test.go
@@ -35,7 +35,7 @@ func TestNewHandlers(t *testing.T) {
require.NoError(t, err)
tokenizer := tokenizertest.New()
emailing := emailingtest.New()
- modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil)
+ modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil)
handlers := NewHandlers(modules, providerSettings)
diff --git a/pkg/signoz/module.go b/pkg/signoz/module.go
index dbeb98460d..4ea45d2fc0 100644
--- a/pkg/signoz/module.go
+++ b/pkg/signoz/module.go
@@ -22,6 +22,8 @@ import (
"github.com/SigNoz/signoz/pkg/modules/rawdataexport/implrawdataexport"
"github.com/SigNoz/signoz/pkg/modules/savedview"
"github.com/SigNoz/signoz/pkg/modules/savedview/implsavedview"
+ "github.com/SigNoz/signoz/pkg/modules/services"
+ "github.com/SigNoz/signoz/pkg/modules/services/implservices"
"github.com/SigNoz/signoz/pkg/modules/session"
"github.com/SigNoz/signoz/pkg/modules/session/implsession"
"github.com/SigNoz/signoz/pkg/modules/spanpercentile"
@@ -32,6 +34,7 @@ import (
"github.com/SigNoz/signoz/pkg/modules/user/impluser"
"github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/tokenizer"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/preferencetypes"
@@ -51,6 +54,7 @@ type Modules struct {
RawDataExport rawdataexport.Module
AuthDomain authdomain.Module
Session session.Module
+ Services services.Module
SpanPercentile spanpercentile.Module
}
@@ -63,6 +67,7 @@ func NewModules(
alertmanager alertmanager.Alertmanager,
analytics analytics.Analytics,
querier querier.Querier,
+ telemetryStore telemetrystore.TelemetryStore,
authNs map[authtypes.AuthNProvider]authn.AuthN,
) Modules {
quickfilter := implquickfilter.NewModule(implquickfilter.NewStore(sqlstore))
@@ -85,5 +90,6 @@ func NewModules(
AuthDomain: implauthdomain.NewModule(implauthdomain.NewStore(sqlstore)),
Session: implsession.NewModule(providerSettings, authNs, user, userGetter, implauthdomain.NewModule(implauthdomain.NewStore(sqlstore)), tokenizer, orgGetter),
SpanPercentile: implspanpercentile.NewModule(querier, providerSettings),
+ Services: implservices.NewModule(querier, telemetryStore),
}
}
diff --git a/pkg/signoz/module_test.go b/pkg/signoz/module_test.go
index 8112a047ef..6298ebcc7c 100644
--- a/pkg/signoz/module_test.go
+++ b/pkg/signoz/module_test.go
@@ -35,7 +35,7 @@ func TestNewModules(t *testing.T) {
require.NoError(t, err)
tokenizer := tokenizertest.New()
emailing := emailingtest.New()
- modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil)
+ modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil)
reflectVal := reflect.ValueOf(modules)
for i := 0; i < reflectVal.NumField(); i++ {
diff --git a/pkg/signoz/signoz.go b/pkg/signoz/signoz.go
index 2635e2a24f..c8b16b3f5f 100644
--- a/pkg/signoz/signoz.go
+++ b/pkg/signoz/signoz.go
@@ -300,7 +300,7 @@ func New(
}
// Initialize all modules
- modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, analytics, querier, authNs)
+ modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, analytics, querier, telemetrystore, authNs)
// Initialize all handlers for the modules
handlers := NewHandlers(modules, providerSettings)
diff --git a/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go b/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go
new file mode 100644
index 0000000000..474265e799
--- /dev/null
+++ b/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go
@@ -0,0 +1,55 @@
+package servicetypesv1
+
+// Request mirrors the /services API input shape
+type Request struct {
+ // Start and End are epoch nanoseconds encoded as strings
+ Start string `json:"start"`
+ End string `json:"end"`
+ Tags []TagFilterItem `json:"tags"`
+}
+
+type TagFilterItem struct {
+ Key string `json:"Key"`
+ Operator string `json:"Operator"`
+ StringValues []string `json:"StringValues"`
+ NumberValues []float64 `json:"NumberValues"`
+ BoolValues []bool `json:"BoolValues"`
+ TagType string `json:"TagType"`
+}
+
+// ResponseItem mirrors model.ServiceItem
+type ResponseItem struct {
+ ServiceName string `json:"serviceName"`
+ Percentile99 float64 `json:"p99"`
+ AvgDuration float64 `json:"avgDuration"`
+ NumCalls uint64 `json:"numCalls"`
+ CallRate float64 `json:"callRate"`
+ NumErrors uint64 `json:"numErrors"`
+ ErrorRate float64 `json:"errorRate"`
+ Num4XX uint64 `json:"num4XX"`
+ FourXXRate float64 `json:"fourXXRate"`
+ DataWarning DataWarning `json:"dataWarning"`
+}
+
+type DataWarning struct {
+ TopLevelOps []string `json:"topLevelOps"`
+}
+
+// OperationsRequest is the common request for both top_operations and entry_point_operations
+type OperationsRequest struct {
+ Start string `json:"start"`
+ End string `json:"end"`
+ Service string `json:"service"`
+ Tags []TagFilterItem `json:"tags"`
+ Limit int `json:"limit,omitempty"`
+}
+
+// OperationItem is the common response item shape for both APIs
+type OperationItem struct {
+ Name string `json:"name"`
+ P50 float64 `json:"p50"`
+ P95 float64 `json:"p95"`
+ P99 float64 `json:"p99"`
+ NumCalls uint64 `json:"numCalls"`
+ ErrorCount uint64 `json:"errorCount"`
+}