SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
chore: register querier routes in apiserver (#10370)
Pandey92b07d15ea9a
diff --git a/cmd/community/server.go b/cmd/community/server.goindex 75c93cf7cd..c49649d7c4 100644--- a/cmd/community/server.go+++ b/cmd/community/server.go@@ -85,6 +85,9 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) efunc(_ licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config] {return noopgateway.NewProviderFactory()},+ func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {+ return querier.NewHandler(ps, q, a)+ },)if err != nil {logger.ErrorContext(ctx, "failed to create signoz", "error", err)diff --git a/cmd/enterprise/server.go b/cmd/enterprise/server.goindex fff12967e2..11afa99ea7 100644--- a/cmd/enterprise/server.go+++ b/cmd/enterprise/server.go@@ -9,6 +9,7 @@ import ("github.com/SigNoz/signoz/ee/authn/callbackauthn/oidccallbackauthn""github.com/SigNoz/signoz/ee/authn/callbackauthn/samlcallbackauthn""github.com/SigNoz/signoz/ee/authz/openfgaauthz"+ eequerier "github.com/SigNoz/signoz/ee/querier""github.com/SigNoz/signoz/ee/authz/openfgaschema""github.com/SigNoz/signoz/ee/gateway/httpgateway"enterpriselicensing "github.com/SigNoz/signoz/ee/licensing"@@ -124,6 +125,10 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) efunc(licensing licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config] {return httpgateway.NewProviderFactory(licensing)},+ func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {+ communityHandler := querier.NewHandler(ps, q, a)+ return eequerier.NewHandler(ps, q, communityHandler)+ },)if err != nil {diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 8e03b18db1..d4dbe89342 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -3223,12 +3223,29 @@ paths:schema:$ref: '#/components/schemas/RenderErrorResponse'description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden"500":content:application/json:schema:$ref: '#/components/schemas/RenderErrorResponse'description: Internal Server Error+ security:+ - api_key:+ - VIEWER+ - tokenizer:+ - VIEWERsummary: Promote and index pathstags:- logs@@ -3253,12 +3270,29 @@ paths:schema:$ref: '#/components/schemas/RenderErrorResponse'description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden"500":content:application/json:schema:$ref: '#/components/schemas/RenderErrorResponse'description: Internal Server Error+ security:+ - api_key:+ - EDITOR+ - tokenizer:+ - EDITORsummary: Promote and index pathstags:- logs@@ -6186,4 +6220,58 @@ paths:- VIEWERsummary: Query rangetags:- - query+ - querier+ /api/v5/substitute_vars:+ post:+ deprecated: false+ description: Replace variables in a query+ operationId: ReplaceVariables+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Querybuildertypesv5QueryRangeRequest'+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/Querybuildertypesv5QueryRangeRequest'+ status:+ type: string+ type: object+ description: OK+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - VIEWER+ - tokenizer:+ - VIEWER+ summary: Replace variables+ tags:+ - querierdiff --git a/docs/contributing/go/handler.md b/docs/contributing/go/handler.mdindex b606308b23..91a2d50431 100644--- a/docs/contributing/go/handler.md+++ b/docs/contributing/go/handler.md@@ -190,43 +190,44 @@ type OpenAPIExample struct {}```-For reference, see `pkg/querier/openapi.go` which defines some examples for the `/api/v5/query_range` endpoint:+For reference, see `pkg/apiserver/signozapiserver/querier.go` which defines examples inline for the `/api/v5/query_range` endpoint:```go-var QueryRangeV5OpenAPIDef = handler.OpenAPIDef{- ID: "QueryRangeV5",- Tags: []string{"query"},- Summary: "Query range",- Description: "Execute a composite query over a time range.",- Request: new(qbtypes.QueryRangeRequest),- RequestExamples: queryRangeV5Examples, // []handler.OpenAPIExample- // ...-}--var queryRangeV5Examples = []handler.OpenAPIExample{- {- Name: "traces_time_series",- Summary: "Time series: count spans grouped by service",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "traces",- // ...+if err := router.Handle("/api/v5/query_range", handler.New(provider.authZ.ViewAccess(provider.querierHandler.QueryRange), handler.OpenAPIDef{+ ID: "QueryRangeV5",+ Tags: []string{"querier"},+ Summary: "Query range",+ Description: "Execute a composite query over a time range.",+ Request: new(qbtypes.QueryRangeRequest),+ RequestContentType: "application/json",+ RequestExamples: []handler.OpenAPIExample{+ {+ Name: "traces_time_series",+ Summary: "Time series: count spans grouped by service",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "traces",+ // ...+ },},},},},},+ // ... more examples},- // ... more examples+ // ...+})).Methods(http.MethodPost).GetError(); err != nil {+ return err}```@@ -338,4 +339,4 @@ func (Step) JSONSchema() (jsonschema.Schema, error) {- **Add `required:"true"`** on fields where the key must be present in the JSON (this is about key presence, not about the zero value).- **Add `nullable:"true"`** on fields that can be `null`. Pay special attention to slices and maps -- in Go these default to `nil` which serializes to `null`. If the field should always be an array, initialize it and do not mark it nullable.- **Implement `Enum()`** on every type that has a fixed set of acceptable values so the JSON schema generates proper `enum` constraints.-- **Add request examples** via `RequestExamples` in `OpenAPIDef` for any non-trivial endpoint. See `pkg/querier/openapi.go` for reference.+- **Add request examples** via `RequestExamples` in `OpenAPIDef` for any non-trivial endpoint. See `pkg/apiserver/signozapiserver/querier.go` for reference.diff --git a/ee/querier/handler.go b/ee/querier/handler.gonew file mode 100644index 0000000000..c6f5dc4abf--- /dev/null+++ b/ee/querier/handler.go@@ -0,0 +1,178 @@+package querier++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "runtime/debug"++ anomalyV2 "github.com/SigNoz/signoz/ee/anomaly"+ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/http/render"+ "github.com/SigNoz/signoz/pkg/querier"+ "github.com/SigNoz/signoz/pkg/types/authtypes"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/valuer"+)++type handler struct {+ set factory.ProviderSettings+ querier querier.Querier+ community querier.Handler+}++func NewHandler(set factory.ProviderSettings, querier querier.Querier, community querier.Handler) querier.Handler {+ return &handler{+ set: set,+ querier: querier,+ community: community,+ }+}++func (h *handler) QueryRange(rw http.ResponseWriter, req *http.Request) {+ bodyBytes, err := io.ReadAll(req.Body)+ if err != nil {+ render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to read request body: %v", err))+ return+ }+ req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))++ ctx := req.Context()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ var queryRangeRequest qbtypes.QueryRangeRequest+ if err := json.NewDecoder(req.Body).Decode(&queryRangeRequest); err != nil {+ render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to decode request body: %v", err))+ return+ }++ defer func() {+ if r := recover(); r != nil {+ stackTrace := string(debug.Stack())++ queryJSON, _ := json.Marshal(queryRangeRequest)++ h.set.Logger.ErrorContext(ctx, "panic in QueryRange",+ "error", r,+ "user", claims.UserID,+ "payload", string(queryJSON),+ "stacktrace", stackTrace,+ )++ render.Error(rw, errors.NewInternalf(+ errors.CodeInternal,+ "Something went wrong on our end. It's not you, it's us. Our team is notified about it. Reach out to support if issue persists.",+ ))+ }+ }()++ if err := queryRangeRequest.Validate(); err != nil {+ render.Error(rw, err)+ return+ }++ orgID, err := valuer.NewUUID(claims.OrgID)+ if err != nil {+ render.Error(rw, err)+ return+ }++ if anomalyQuery, ok := queryRangeRequest.IsAnomalyRequest(); ok {+ anomalies, err := h.handleAnomalyQuery(ctx, orgID, anomalyQuery, queryRangeRequest)+ if err != nil {+ render.Error(rw, errors.NewInternalf(errors.CodeInternal, "failed to get anomalies: %v", err))+ return+ }++ results := []any{}+ for _, item := range anomalies.Results {+ results = append(results, item)+ }++ // Build step intervals from the anomaly query+ stepIntervals := make(map[string]uint64)+ if anomalyQuery.StepInterval.Duration > 0 {+ stepIntervals[anomalyQuery.Name] = uint64(anomalyQuery.StepInterval.Duration.Seconds())+ }++ finalResp := &qbtypes.QueryRangeResponse{+ Type: queryRangeRequest.RequestType,+ Data: qbtypes.QueryData{+ Results: results,+ },+ Meta: qbtypes.ExecStats{+ StepIntervals: stepIntervals,+ },+ }++ render.Success(rw, http.StatusOK, finalResp)+ return+ }++ // regular query range request, delegate to community handler+ req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))+ h.community.QueryRange(rw, req)+}++func (h *handler) QueryRawStream(rw http.ResponseWriter, req *http.Request) {+ h.community.QueryRawStream(rw, req)+}++func (h *handler) ReplaceVariables(rw http.ResponseWriter, req *http.Request) {+ h.community.ReplaceVariables(rw, req)+}++func extractSeasonality(anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]) anomalyV2.Seasonality {+ for _, fn := range anomalyQuery.Functions {+ if fn.Name == qbtypes.FunctionNameAnomaly {+ for _, arg := range fn.Args {+ if arg.Name == "seasonality" {+ if seasonalityStr, ok := arg.Value.(string); ok {+ switch seasonalityStr {+ case "weekly":+ return anomalyV2.SeasonalityWeekly+ case "hourly":+ return anomalyV2.SeasonalityHourly+ }+ }+ }+ }+ }+ }+ return anomalyV2.SeasonalityDaily // default+}++func (h *handler) createAnomalyProvider(seasonality anomalyV2.Seasonality) anomalyV2.Provider {+ switch seasonality {+ case anomalyV2.SeasonalityWeekly:+ return anomalyV2.NewWeeklyProvider(+ anomalyV2.WithQuerier[*anomalyV2.WeeklyProvider](h.querier),+ anomalyV2.WithLogger[*anomalyV2.WeeklyProvider](h.set.Logger),+ )+ case anomalyV2.SeasonalityHourly:+ return anomalyV2.NewHourlyProvider(+ anomalyV2.WithQuerier[*anomalyV2.HourlyProvider](h.querier),+ anomalyV2.WithLogger[*anomalyV2.HourlyProvider](h.set.Logger),+ )+ default:+ return anomalyV2.NewDailyProvider(+ anomalyV2.WithQuerier[*anomalyV2.DailyProvider](h.querier),+ anomalyV2.WithLogger[*anomalyV2.DailyProvider](h.set.Logger),+ )+ }+}++func (h *handler) handleAnomalyQuery(ctx context.Context, orgID valuer.UUID, anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation], queryRangeRequest qbtypes.QueryRangeRequest) (*anomalyV2.AnomaliesResponse, error) {+ seasonality := extractSeasonality(anomalyQuery)+ provider := h.createAnomalyProvider(seasonality)++ return provider.GetAnomalies(ctx, orgID, &anomalyV2.AnomaliesRequest{Params: queryRangeRequest})+}diff --git a/ee/query-service/app/api/api.go b/ee/query-service/app/api/api.goindex 64295d19bf..45de8cc5d8 100644--- a/ee/query-service/app/api/api.go+++ b/ee/query-service/app/api/api.go@@ -10,9 +10,7 @@ import ("github.com/SigNoz/signoz/ee/query-service/usage""github.com/SigNoz/signoz/pkg/alertmanager""github.com/SigNoz/signoz/pkg/global"- "github.com/SigNoz/signoz/pkg/http/handler""github.com/SigNoz/signoz/pkg/http/middleware"- querierAPI "github.com/SigNoz/signoz/pkg/querier"baseapp "github.com/SigNoz/signoz/pkg/query-service/app""github.com/SigNoz/signoz/pkg/query-service/app/cloudintegrations""github.com/SigNoz/signoz/pkg/query-service/app/integrations"@@ -57,7 +55,6 @@ func NewAPIHandler(opts APIHandlerOptions, signoz *signoz.SigNoz, config signoz.AlertmanagerAPI: alertmanager.NewAPI(signoz.Alertmanager),LicensingAPI: httplicensing.NewLicensingAPI(signoz.Licensing),Signoz: signoz,- QuerierAPI: querierAPI.NewAPI(signoz.Instrumentation.ToProviderSettings(), signoz.Querier, signoz.Analytics),QueryParserAPI: queryparser.NewAPI(signoz.Instrumentation.ToProviderSettings(), signoz.QueryParser),}, config)@@ -106,14 +103,6 @@ func (ah *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {// v4router.HandleFunc("/api/v4/query_range", am.ViewAccess(ah.queryRangeV4)).Methods(http.MethodPost)- // v5- router.Handle("/api/v5/query_range", handler.New(- am.ViewAccess(ah.queryRangeV5),- querierAPI.QueryRangeV5OpenAPIDef,- )).Methods(http.MethodPost)-- router.HandleFunc("/api/v5/substitute_vars", am.ViewAccess(ah.QuerierAPI.ReplaceVariables)).Methods(http.MethodPost)-// Gatewayrouter.PathPrefix(gateway.RoutePrefix).HandlerFunc(am.EditAccess(ah.ServeGatewayHTTP))diff --git a/ee/query-service/app/api/queryrange.go b/ee/query-service/app/api/queryrange.goindex 3357692cd3..06ba8eb405 100644--- a/ee/query-service/app/api/queryrange.go+++ b/ee/query-service/app/api/queryrange.go@@ -2,16 +2,11 @@ package apiimport ("bytes"- "context"- "encoding/json""fmt""io""net/http"- "runtime/debug"- anomalyV2 "github.com/SigNoz/signoz/ee/anomaly""github.com/SigNoz/signoz/ee/query-service/anomaly"- "github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/http/render"baseapp "github.com/SigNoz/signoz/pkg/query-service/app""github.com/SigNoz/signoz/pkg/query-service/app/queryBuilder"@@ -20,8 +15,6 @@ import ("github.com/SigNoz/signoz/pkg/types/authtypes""github.com/SigNoz/signoz/pkg/valuer""go.uber.org/zap"-- qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5")func (aH *APIHandler) queryRangeV4(w http.ResponseWriter, r *http.Request) {@@ -144,140 +137,3 @@ func (aH *APIHandler) queryRangeV4(w http.ResponseWriter, r *http.Request) {}}-func extractSeasonality(anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]) anomalyV2.Seasonality {- for _, fn := range anomalyQuery.Functions {- if fn.Name == qbtypes.FunctionNameAnomaly {- for _, arg := range fn.Args {- if arg.Name == "seasonality" {- if seasonalityStr, ok := arg.Value.(string); ok {- switch seasonalityStr {- case "weekly":- return anomalyV2.SeasonalityWeekly- case "hourly":- return anomalyV2.SeasonalityHourly- }- }- }- }- }- }- return anomalyV2.SeasonalityDaily // default-}--func createAnomalyProvider(aH *APIHandler, seasonality anomalyV2.Seasonality) anomalyV2.Provider {- switch seasonality {- case anomalyV2.SeasonalityWeekly:- return anomalyV2.NewWeeklyProvider(- anomalyV2.WithQuerier[*anomalyV2.WeeklyProvider](aH.Signoz.Querier),- anomalyV2.WithLogger[*anomalyV2.WeeklyProvider](aH.Signoz.Instrumentation.Logger()),- )- case anomalyV2.SeasonalityHourly:- return anomalyV2.NewHourlyProvider(- anomalyV2.WithQuerier[*anomalyV2.HourlyProvider](aH.Signoz.Querier),- anomalyV2.WithLogger[*anomalyV2.HourlyProvider](aH.Signoz.Instrumentation.Logger()),- )- default:- return anomalyV2.NewDailyProvider(- anomalyV2.WithQuerier[*anomalyV2.DailyProvider](aH.Signoz.Querier),- anomalyV2.WithLogger[*anomalyV2.DailyProvider](aH.Signoz.Instrumentation.Logger()),- )- }-}--func (aH *APIHandler) handleAnomalyQuery(ctx context.Context, orgID valuer.UUID, anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation], queryRangeRequest qbtypes.QueryRangeRequest) (*anomalyV2.AnomaliesResponse, error) {- seasonality := extractSeasonality(anomalyQuery)- provider := createAnomalyProvider(aH, seasonality)-- return provider.GetAnomalies(ctx, orgID, &anomalyV2.AnomaliesRequest{Params: queryRangeRequest})-}--func (aH *APIHandler) queryRangeV5(rw http.ResponseWriter, req *http.Request) {-- bodyBytes, err := io.ReadAll(req.Body)- if err != nil {- render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to read request body: %v", err))- return- }- req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))-- ctx := req.Context()-- claims, err := authtypes.ClaimsFromContext(ctx)- if err != nil {- render.Error(rw, err)- return- }-- var queryRangeRequest qbtypes.QueryRangeRequest- if err := json.NewDecoder(req.Body).Decode(&queryRangeRequest); err != nil {- render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to decode request body: %v", err))- return- }-- defer func() {- if r := recover(); r != nil {- stackTrace := string(debug.Stack())-- queryJSON, _ := json.Marshal(queryRangeRequest)-- aH.Signoz.Instrumentation.Logger().ErrorContext(ctx, "panic in QueryRange",- "error", r,- "user", claims.UserID,- "payload", string(queryJSON),- "stacktrace", stackTrace,- )-- render.Error(rw, errors.NewInternalf(- errors.CodeInternal,- "Something went wrong on our end. It's not you, it's us. Our team is notified about it. Reach out to support if issue persists.",- ))- }- }()-- if err := queryRangeRequest.Validate(); err != nil {- render.Error(rw, err)- return- }-- orgID, err := valuer.NewUUID(claims.OrgID)- if err != nil {- render.Error(rw, err)- return- }-- if anomalyQuery, ok := queryRangeRequest.IsAnomalyRequest(); ok {- anomalies, err := aH.handleAnomalyQuery(ctx, orgID, anomalyQuery, queryRangeRequest)- if err != nil {- render.Error(rw, errors.NewInternalf(errors.CodeInternal, "failed to get anomalies: %v", err))- return- }-- results := []any{}- for _, item := range anomalies.Results {- results = append(results, item)- }-- // Build step intervals from the anomaly query- stepIntervals := make(map[string]uint64)- if anomalyQuery.StepInterval.Duration > 0 {- stepIntervals[anomalyQuery.Name] = uint64(anomalyQuery.StepInterval.Duration.Seconds())- }-- finalResp := &qbtypes.QueryRangeResponse{- Type: queryRangeRequest.RequestType,- Data: qbtypes.QueryData{- Results: results,- },- Meta: qbtypes.ExecStats{- StepIntervals: stepIntervals,- },- }-- render.Success(rw, http.StatusOK, finalResp)- return- } else {- // regular query range request, let the querier handle it- req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))- aH.QuerierAPI.QueryRange(rw, req)- }-}diff --git a/ee/query-service/app/server.go b/ee/query-service/app/server.goindex 10da27ac0c..c270f6589d 100644--- a/ee/query-service/app/server.go+++ b/ee/query-service/app/server.go@@ -240,7 +240,6 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*hapiHandler.RegisterQueryRangeV3Routes(r, am)apiHandler.RegisterInfraMetricsRoutes(r, am)apiHandler.RegisterQueryRangeV4Routes(r, am)- apiHandler.RegisterQueryRangeV5Routes(r, am)apiHandler.RegisterWebSocketPaths(r, am)apiHandler.RegisterMessagingQueuesRoutes(r, am)apiHandler.RegisterThirdPartyApiRoutes(r, am)diff --git a/frontend/src/api/generated/services/query/index.ts b/frontend/src/api/generated/services/querier/index.tssimilarity index 55%rename from frontend/src/api/generated/services/query/index.tsrename to frontend/src/api/generated/services/querier/index.tsindex 6315e3910f..0ae8c40c88 100644--- a/frontend/src/api/generated/services/query/index.ts+++ b/frontend/src/api/generated/services/querier/index.ts@@ -16,6 +16,7 @@ import type {Querybuildertypesv5QueryRangeRequestDTO,QueryRangeV5200,RenderErrorResponseDTO,+ ReplaceVariables200,} from '../sigNoz.schemas';type AwaitedInput<T> = PromiseLike<T> | T;@@ -105,3 +106,86 @@ export const useQueryRangeV5 = <return useMutation(mutationOptions);};+/**+ * Replace variables in a query+ * @summary Replace variables+ */+export const replaceVariables = (+ querybuildertypesv5QueryRangeRequestDTO: Querybuildertypesv5QueryRangeRequestDTO,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<ReplaceVariables200>({+ url: `/api/v5/substitute_vars`,+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ data: querybuildertypesv5QueryRangeRequestDTO,+ signal,+ });+};++export const getReplaceVariablesMutationOptions = <+ TError = RenderErrorResponseDTO,+ TContext = unknown+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof replaceVariables>>,+ TError,+ { data: Querybuildertypesv5QueryRangeRequestDTO },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof replaceVariables>>,+ TError,+ { data: Querybuildertypesv5QueryRangeRequestDTO },+ TContext+> => {+ const mutationKey = ['replaceVariables'];+ const { mutation: mutationOptions } = options+ ? options.mutation &&+ 'mutationKey' in options.mutation &&+ options.mutation.mutationKey+ ? options+ : { ...options, mutation: { ...options.mutation, mutationKey } }+ : { mutation: { mutationKey } };++ const mutationFn: MutationFunction<+ Awaited<ReturnType<typeof replaceVariables>>,+ { data: Querybuildertypesv5QueryRangeRequestDTO }+ > = (props) => {+ const { data } = props ?? {};++ return replaceVariables(data);+ };++ return { mutationFn, ...mutationOptions };+};++export type ReplaceVariablesMutationResult = NonNullable<+ Awaited<ReturnType<typeof replaceVariables>>+>;+export type ReplaceVariablesMutationBody = Querybuildertypesv5QueryRangeRequestDTO;+export type ReplaceVariablesMutationError = RenderErrorResponseDTO;++/**+ * @summary Replace variables+ */+export const useReplaceVariables = <+ TError = RenderErrorResponseDTO,+ TContext = unknown+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof replaceVariables>>,+ TError,+ { data: Querybuildertypesv5QueryRangeRequestDTO },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof replaceVariables>>,+ TError,+ { data: Querybuildertypesv5QueryRangeRequestDTO },+ TContext+> => {+ const mutationOptions = getReplaceVariablesMutationOptions(options);++ return useMutation(mutationOptions);+};diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 85ef8b5df1..06338e34b5 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -3229,3 +3229,11 @@ export type QueryRangeV5200 = {*/status?: string;};++export type ReplaceVariables200 = {+ data?: Querybuildertypesv5QueryRangeRequestDTO;+ /**+ * @type string+ */+ status?: string;+};diff --git a/pkg/apiserver/signozapiserver/promote.go b/pkg/apiserver/signozapiserver/promote.goindex 8fc25dd7ee..277398721b 100644--- a/pkg/apiserver/signozapiserver/promote.go+++ b/pkg/apiserver/signozapiserver/promote.go@@ -4,6 +4,7 @@ import ("net/http""github.com/SigNoz/signoz/pkg/http/handler"+ "github.com/SigNoz/signoz/pkg/types""github.com/SigNoz/signoz/pkg/types/promotetypes""github.com/gorilla/mux")@@ -20,6 +21,7 @@ func (provider *provider) addPromoteRoutes(router *mux.Router) error {ResponseContentType: "",SuccessStatusCode: http.StatusCreated,ErrorStatusCodes: []int{http.StatusBadRequest},+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),})).Methods(http.MethodPost).GetError(); err != nil {return err}@@ -35,6 +37,7 @@ func (provider *provider) addPromoteRoutes(router *mux.Router) error {ResponseContentType: "",SuccessStatusCode: http.StatusOK,ErrorStatusCodes: []int{http.StatusBadRequest},+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),})).Methods(http.MethodGet).GetError(); err != nil {return err}diff --git a/pkg/apiserver/signozapiserver/provider.go b/pkg/apiserver/signozapiserver/provider.goindex 474b8ecf23..58f23bd842 100644--- a/pkg/apiserver/signozapiserver/provider.go+++ b/pkg/apiserver/signozapiserver/provider.go@@ -20,6 +20,7 @@ import ("github.com/SigNoz/signoz/pkg/modules/promote""github.com/SigNoz/signoz/pkg/modules/session""github.com/SigNoz/signoz/pkg/modules/user"+ "github.com/SigNoz/signoz/pkg/querier""github.com/SigNoz/signoz/pkg/types""github.com/SigNoz/signoz/pkg/types/ctxtypes""github.com/SigNoz/signoz/pkg/zeus"@@ -46,6 +47,7 @@ type provider struct {fieldsHandler fields.HandlerauthzHandler authz.HandlerzeusHandler zeus.Handler+ querierHandler querier.Handler}func NewFactory(@@ -66,6 +68,7 @@ func NewFactory(fieldsHandler fields.Handler,authzHandler authz.Handler,zeusHandler zeus.Handler,+ querierHandler querier.Handler,) factory.ProviderFactory[apiserver.APIServer, apiserver.Config] {return factory.NewProviderFactory(factory.MustNewName("signoz"), func(ctx context.Context, providerSettings factory.ProviderSettings, config apiserver.Config) (apiserver.APIServer, error) {return newProvider(@@ -89,6 +92,7 @@ func NewFactory(fieldsHandler,authzHandler,zeusHandler,+ querierHandler,)})}@@ -114,6 +118,7 @@ func newProvider(fieldsHandler fields.Handler,authzHandler authz.Handler,zeusHandler zeus.Handler,+ querierHandler querier.Handler,) (apiserver.APIServer, error) {settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/apiserver/signozapiserver")router := mux.NewRouter().UseEncodedPath()@@ -137,6 +142,7 @@ func newProvider(fieldsHandler: fieldsHandler,authzHandler: authzHandler,zeusHandler: zeusHandler,+ querierHandler: querierHandler,}provider.authZ = middleware.NewAuthZ(settings.Logger(), orgGetter, authz)@@ -209,6 +215,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {return err}+ if err := provider.addQuerierRoutes(router); err != nil {+ return err+ }+return nil}diff --git a/pkg/apiserver/signozapiserver/querier.go b/pkg/apiserver/signozapiserver/querier.gonew file mode 100644index 0000000000..b9d082e7bd--- /dev/null+++ b/pkg/apiserver/signozapiserver/querier.go@@ -0,0 +1,471 @@+package signozapiserver++import (+ "net/http"++ "github.com/SigNoz/signoz/pkg/http/handler"+ "github.com/SigNoz/signoz/pkg/types"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/gorilla/mux"+)++func (provider *provider) addQuerierRoutes(router *mux.Router) error {+ if err := router.Handle("/api/v5/query_range", handler.New(provider.authZ.ViewAccess(provider.querierHandler.QueryRange), handler.OpenAPIDef{+ ID: "QueryRangeV5",+ Tags: []string{"querier"},+ Summary: "Query range",+ Description: "Execute a composite query over a time range. Supports builder queries (traces, logs, metrics), formulas, trace operators, PromQL, and ClickHouse SQL.",+ Request: new(qbtypes.QueryRangeRequest),+ RequestContentType: "application/json",+ RequestExamples: []handler.OpenAPIExample{+ {+ Name: "traces_time_series",+ Summary: "Time series: count spans grouped by service",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "traces",+ "aggregations": []any{+ map[string]any{"expression": "count()", "alias": "span_count"},+ },+ "stepInterval": "60s",+ "filter": map[string]any{"expression": "service.name = 'frontend'"},+ "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},+ "order": []any{map[string]any{"key": map[string]any{"name": "span_count"}, "direction": "desc"}},+ "limit": 10,+ },+ },+ },+ },+ },+ },+ {+ Name: "logs_time_series",+ Summary: "Time series: count error logs grouped by service",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "logs",+ "aggregations": []any{+ map[string]any{"expression": "count()", "alias": "log_count"},+ },+ "stepInterval": "60s",+ "filter": map[string]any{"expression": "severity_text = 'ERROR'"},+ "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},+ "order": []any{map[string]any{"key": map[string]any{"name": "log_count"}, "direction": "desc"}},+ "limit": 10,+ },+ },+ },+ },+ },+ },+ {+ Name: "metrics_gauge_time_series",+ Summary: "Time series: latest gauge value averaged across series",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "metrics",+ "aggregations": []any{+ map[string]any{"metricName": "system.cpu.utilization", "timeAggregation": "latest", "spaceAggregation": "avg"},+ },+ "stepInterval": "60s",+ "groupBy": []any{map[string]any{"name": "host.name", "fieldContext": "resource"}},+ },+ },+ },+ },+ },+ },+ {+ Name: "metrics_rate_time_series",+ Summary: "Time series: rate of cumulative counter",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "metrics",+ "aggregations": []any{+ map[string]any{"metricName": "http.server.duration.count", "timeAggregation": "rate", "spaceAggregation": "sum"},+ },+ "stepInterval": 120,+ "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},+ },+ },+ },+ },+ },+ },+ {+ Name: "metrics_histogram_time_series",+ Summary: "Time series: p99 latency from histogram",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "metrics",+ "aggregations": []any{+ map[string]any{"metricName": "http.server.duration.bucket", "spaceAggregation": "p99"},+ },+ "stepInterval": "60s",+ "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},+ },+ },+ },+ },+ },+ },+ {+ Name: "logs_raw",+ Summary: "Raw: fetch raw log records",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "raw",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "logs",+ "filter": map[string]any{"expression": "severity_text = 'ERROR'"},+ "selectFields": []any{+ map[string]any{"name": "body", "fieldContext": "log"},+ map[string]any{"name": "service.name", "fieldContext": "resource"},+ },+ "order": []any{+ map[string]any{"key": map[string]any{"name": "timestamp", "fieldContext": "log"}, "direction": "desc"},+ map[string]any{"key": map[string]any{"name": "id"}, "direction": "desc"},+ },+ "limit": 50,+ "offset": 0,+ },+ },+ },+ },+ },+ },+ {+ Name: "traces_raw",+ Summary: "Raw: fetch raw span records",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "raw",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "traces",+ "filter": map[string]any{"expression": "service.name = 'frontend' AND has_error = true"},+ "selectFields": []any{+ map[string]any{"name": "name", "fieldContext": "span"},+ map[string]any{"name": "duration_nano", "fieldContext": "span"},+ },+ "order": []any{+ map[string]any{"key": map[string]any{"name": "timestamp", "fieldContext": "span"}, "direction": "desc"},+ },+ "limit": 100,+ },+ },+ },+ },+ },+ },+ {+ Name: "traces_scalar",+ Summary: "Scalar: total span count",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "scalar",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "traces",+ "aggregations": []any{+ map[string]any{"expression": "count()", "alias": "span_count"},+ },+ "filter": map[string]any{"expression": "service.name = 'frontend'"},+ },+ },+ },+ },+ },+ },+ {+ Name: "logs_scalar",+ Summary: "Scalar: total error log count",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "scalar",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "logs",+ "aggregations": []any{+ map[string]any{"expression": "count()", "alias": "error_count"},+ },+ "filter": map[string]any{"expression": "severity_text = 'ERROR'"},+ },+ },+ },+ },+ },+ },+ {+ Name: "metrics_scalar",+ Summary: "Scalar: single reduced metric value",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "scalar",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "metrics",+ "aggregations": []any{+ map[string]any{"metricName": "http.server.duration.count", "timeAggregation": "rate", "spaceAggregation": "sum", "reduceTo": "sum"},+ },+ "stepInterval": "60s",+ },+ },+ },+ },+ },+ },+ {+ Name: "formula",+ Summary: "Formula: error rate from two trace queries",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "A",+ "signal": "traces",+ "aggregations": []any{map[string]any{"expression": "countIf(has_error = true)"}},+ "stepInterval": "60s",+ "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},+ },+ },+ map[string]any{+ "type": "builder_query",+ "spec": map[string]any{+ "name": "B",+ "signal": "traces",+ "aggregations": []any{map[string]any{"expression": "count()"}},+ "stepInterval": "60s",+ "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},+ },+ },+ map[string]any{+ "type": "builder_formula",+ "spec": map[string]any{+ "name": "error_rate",+ "expression": "A / B * 100",+ },+ },+ },+ },+ },+ },+ {+ Name: "promql",+ Summary: "PromQL: request rate with UTF-8 metric name",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "promql",+ "spec": map[string]any{+ "name": "request_rate",+ "query": "sum(rate({\"http.server.duration.count\"}[5m])) by (\"service.name\")",+ "step": 60,+ },+ },+ },+ },+ },+ },+ {+ Name: "clickhouse_sql_traces_time_series",+ Summary: "ClickHouse SQL: traces time series with resource filter",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "time_series",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "clickhouse_sql",+ "spec": map[string]any{+ "name": "span_rate",+ "query": "WITH __resource_filter AS (" ++ " SELECT fingerprint FROM signoz_traces.distributed_traces_v3_resource" ++ " WHERE seen_at_ts_bucket_start >= $start_timestamp - 1800 AND seen_at_ts_bucket_start <= $end_timestamp" ++ " ) SELECT toStartOfInterval(timestamp, INTERVAL 60 SECOND) AS ts, count() AS value" ++ " FROM signoz_traces.distributed_signoz_index_v3" ++ " WHERE resource_fingerprint GLOBAL IN (SELECT fingerprint FROM __resource_filter)" ++ " AND timestamp >= $start_datetime AND timestamp <= $end_datetime" ++ " AND ts_bucket_start >= $start_timestamp - 1800 AND ts_bucket_start <= $end_timestamp" ++ " GROUP BY ts ORDER BY ts",+ },+ },+ },+ },+ },+ },+ {+ Name: "clickhouse_sql_logs_raw",+ Summary: "ClickHouse SQL: raw logs with resource filter",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "raw",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "clickhouse_sql",+ "spec": map[string]any{+ "name": "recent_errors",+ "query": "WITH __resource_filter AS (" ++ " SELECT fingerprint FROM signoz_logs.distributed_logs_v2_resource" ++ " WHERE seen_at_ts_bucket_start >= $start_timestamp - 1800 AND seen_at_ts_bucket_start <= $end_timestamp" ++ " ) SELECT timestamp, body" ++ " FROM signoz_logs.distributed_logs_v2" ++ " WHERE resource_fingerprint GLOBAL IN (SELECT fingerprint FROM __resource_filter)" ++ " AND timestamp >= $start_timestamp_nano AND timestamp <= $end_timestamp_nano" ++ " AND ts_bucket_start >= $start_timestamp - 1800 AND ts_bucket_start <= $end_timestamp" ++ " AND severity_text = 'ERROR'" ++ " ORDER BY timestamp DESC LIMIT 100",+ },+ },+ },+ },+ },+ },+ {+ Name: "clickhouse_sql_traces_scalar",+ Summary: "ClickHouse SQL: scalar aggregate with resource filter",+ Value: map[string]any{+ "schemaVersion": "v1",+ "start": 1640995200000,+ "end": 1640998800000,+ "requestType": "scalar",+ "compositeQuery": map[string]any{+ "queries": []any{+ map[string]any{+ "type": "clickhouse_sql",+ "spec": map[string]any{+ "name": "total_spans",+ "query": "WITH __resource_filter AS (" ++ " SELECT fingerprint FROM signoz_traces.distributed_traces_v3_resource" ++ " WHERE seen_at_ts_bucket_start >= $start_timestamp - 1800 AND seen_at_ts_bucket_start <= $end_timestamp" ++ " ) SELECT count() AS value" ++ " FROM signoz_traces.distributed_signoz_index_v3" ++ " WHERE resource_fingerprint GLOBAL IN (SELECT fingerprint FROM __resource_filter)" ++ " AND timestamp >= $start_datetime AND timestamp <= $end_datetime" ++ " AND ts_bucket_start >= $start_timestamp - 1800 AND ts_bucket_start <= $end_timestamp",+ },+ },+ },+ },+ },+ },+ },+ Response: new(qbtypes.QueryRangeResponse),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),+ })).Methods(http.MethodPost).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v5/substitute_vars", handler.New(provider.authZ.ViewAccess(provider.querierHandler.ReplaceVariables), handler.OpenAPIDef{+ ID: "ReplaceVariables",+ Tags: []string{"querier"},+ Summary: "Replace variables",+ Description: "Replace variables in a query",+ Request: new(qbtypes.QueryRangeRequest),+ RequestContentType: "application/json",+ Response: new(qbtypes.QueryRangeRequest),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),+ })).Methods(http.MethodPost).GetError(); err != nil {+ return err+ }++ return nil+}diff --git a/pkg/querier/api.go b/pkg/querier/api.goindex d7248050c0..7049b099e4 100644--- a/pkg/querier/api.go+++ b/pkg/querier/api.go@@ -21,18 +21,17 @@ import ("github.com/SigNoz/signoz/pkg/variables")-type API struct {+type handler struct {set factory.ProviderSettingsanalytics analytics.Analyticsquerier Querier}-func NewAPI(set factory.ProviderSettings, querier Querier, analytics analytics.Analytics) *API {- return &API{set: set, querier: querier, analytics: analytics}+func NewHandler(set factory.ProviderSettings, querier Querier, analytics analytics.Analytics) Handler {+ return &handler{set: set, querier: querier, analytics: analytics}}-func (a *API) QueryRange(rw http.ResponseWriter, req *http.Request) {-+func (handler *handler) QueryRange(rw http.ResponseWriter, req *http.Request) {ctx := req.Context()claims, err := authtypes.ClaimsFromContext(ctx)@@ -53,7 +52,7 @@ func (a *API) QueryRange(rw http.ResponseWriter, req *http.Request) {queryJSON, _ := json.Marshal(queryRangeRequest)- a.set.Logger.ErrorContext(ctx, "panic in QueryRange",+ handler.set.Logger.ErrorContext(ctx, "panic in QueryRange","error", r,"user", claims.UserID,"payload", string(queryJSON),@@ -79,17 +78,17 @@ func (a *API) QueryRange(rw http.ResponseWriter, req *http.Request) {return}- queryRangeResponse, err := a.querier.QueryRange(ctx, orgID, &queryRangeRequest)+ queryRangeResponse, err := handler.querier.QueryRange(ctx, orgID, &queryRangeRequest)if err != nil {render.Error(rw, err)return}- a.logEvent(req.Context(), req.Header.Get("Referer"), queryRangeResponse.QBEvent)+ handler.logEvent(req.Context(), req.Header.Get("Referer"), queryRangeResponse.QBEvent)render.Success(rw, http.StatusOK, queryRangeResponse)}-func (a *API) QueryRawStream(rw http.ResponseWriter, req *http.Request) {+func (handler *handler) QueryRawStream(rw http.ResponseWriter, req *http.Request) {ctx := req.Context()// get the param from url and add it to body@@ -153,7 +152,7 @@ func (a *API) QueryRawStream(rw http.ResponseWriter, req *http.Request) {queryJSON, _ := json.Marshal(queryRangeRequest)- a.set.Logger.ErrorContext(ctx, "panic in QueryRawStream",+ handler.set.Logger.ErrorContext(ctx, "panic in QueryRawStream","error", r,"user", claims.UserID,"payload", string(queryJSON),@@ -193,7 +192,7 @@ func (a *API) QueryRawStream(rw http.ResponseWriter, req *http.Request) {flusher.Flush()client := &qbtypes.RawStream{Name: req.RemoteAddr, Logs: make(chan *qbtypes.RawRow, 1000), Done: make(chan *bool), Error: make(chan error)}- go a.querier.QueryRawStream(ctx, orgID, &queryRangeRequest, client)+ go handler.querier.QueryRawStream(ctx, orgID, &queryRangeRequest, client)for {select {@@ -220,7 +219,7 @@ func (a *API) QueryRawStream(rw http.ResponseWriter, req *http.Request) {// TODO(srikanthccv): everything done here can be done on frontend as well// For the time being I am adding a helper function-func (a *API) ReplaceVariables(rw http.ResponseWriter, req *http.Request) {+func (handler *handler) ReplaceVariables(rw http.ResponseWriter, req *http.Request) {var queryRangeRequest qbtypes.QueryRangeRequestif err := json.NewDecoder(req.Body).Decode(&queryRangeRequest); err != nil {@@ -272,7 +271,7 @@ func (a *API) ReplaceVariables(rw http.ResponseWriter, req *http.Request) {render.Success(rw, http.StatusOK, queryRangeRequest)}-func (a *API) logEvent(ctx context.Context, referrer string, event *qbtypes.QBEvent) {+func (handler *handler) logEvent(ctx context.Context, referrer string, event *qbtypes.QBEvent) {claims, err := authtypes.ClaimsFromContext(ctx)if err != nil {return@@ -305,8 +304,9 @@ func (a *API) logEvent(ctx context.Context, referrer string, event *qbtypes.QBEv}if !event.HasData {- a.analytics.TrackUser(ctx, claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", properties)+ handler.analytics.TrackUser(ctx, claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", properties)return}- a.analytics.TrackUser(ctx, claims.OrgID, claims.UserID, "Telemetry Query Returned Results", properties)++ handler.analytics.TrackUser(ctx, claims.OrgID, claims.UserID, "Telemetry Query Returned Results", properties)}diff --git a/pkg/querier/interfaces.go b/pkg/querier/interfaces.goindex b1e5005cf0..ce64f1e2fe 100644--- a/pkg/querier/interfaces.go+++ b/pkg/querier/interfaces.go@@ -2,6 +2,7 @@ package querierimport ("context"+ "net/http"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/valuer"@@ -20,3 +21,9 @@ type BucketCache interface {// store fresh buckets for future hitsPut(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result)}++type Handler interface {+ QueryRange(rw http.ResponseWriter, req *http.Request)+ QueryRawStream(rw http.ResponseWriter, req *http.Request)+ ReplaceVariables(rw http.ResponseWriter, req *http.Request)+}diff --git a/pkg/querier/openapi.go b/pkg/querier/openapi.goindex f597270063..f8d6aa6e85 100644--- a/pkg/querier/openapi.go+++ b/pkg/querier/openapi.go@@ -1,454 +1 @@package querier--import (- "net/http"-- "github.com/SigNoz/signoz/pkg/http/handler"- qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"- "github.com/SigNoz/signoz/pkg/types/ctxtypes"-)--// QueryRangeV5OpenAPIDef is the OpenAPI definition for the /api/v5/query_range endpoint.-var QueryRangeV5OpenAPIDef = handler.OpenAPIDef{- ID: "QueryRangeV5",- Tags: []string{"query"},- Summary: "Query range",- Description: "Execute a composite query over a time range. Supports builder queries (traces, logs, metrics), formulas, trace operators, PromQL, and ClickHouse SQL.",- Request: new(qbtypes.QueryRangeRequest),- RequestContentType: "application/json",- RequestExamples: queryRangeV5Examples,- Response: new(qbtypes.QueryRangeResponse),- ResponseContentType: "application/json",- SuccessStatusCode: http.StatusOK,- ErrorStatusCodes: []int{http.StatusBadRequest},- SecuritySchemes: []handler.OpenAPISecurityScheme{- {Name: ctxtypes.AuthTypeAPIKey.StringValue(), Scopes: []string{"VIEWER"}},- {Name: ctxtypes.AuthTypeTokenizer.StringValue(), Scopes: []string{"VIEWER"}},- },-}--var queryRangeV5Examples = []handler.OpenAPIExample{- {- Name: "traces_time_series",- Summary: "Time series: count spans grouped by service",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "traces",- "aggregations": []any{- map[string]any{"expression": "count()", "alias": "span_count"},- },- "stepInterval": "60s",- "filter": map[string]any{"expression": "service.name = 'frontend'"},- "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},- "order": []any{map[string]any{"key": map[string]any{"name": "span_count"}, "direction": "desc"}},- "limit": 10,- },- },- },- },- },- },- {- Name: "logs_time_series",- Summary: "Time series: count error logs grouped by service",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "logs",- "aggregations": []any{- map[string]any{"expression": "count()", "alias": "log_count"},- },- "stepInterval": "60s",- "filter": map[string]any{"expression": "severity_text = 'ERROR'"},- "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},- "order": []any{map[string]any{"key": map[string]any{"name": "log_count"}, "direction": "desc"}},- "limit": 10,- },- },- },- },- },- },- {- Name: "metrics_gauge_time_series",- Summary: "Time series: latest gauge value averaged across series",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "metrics",- "aggregations": []any{- map[string]any{"metricName": "system.cpu.utilization", "timeAggregation": "latest", "spaceAggregation": "avg"},- },- "stepInterval": "60s",- "groupBy": []any{map[string]any{"name": "host.name", "fieldContext": "resource"}},- },- },- },- },- },- },- {- Name: "metrics_rate_time_series",- Summary: "Time series: rate of cumulative counter",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "metrics",- "aggregations": []any{- map[string]any{"metricName": "http.server.duration.count", "timeAggregation": "rate", "spaceAggregation": "sum"},- },- "stepInterval": 120,- "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},- },- },- },- },- },- },- {- Name: "metrics_histogram_time_series",- Summary: "Time series: p99 latency from histogram",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "metrics",- "aggregations": []any{- map[string]any{"metricName": "http.server.duration.bucket", "spaceAggregation": "p99"},- },- "stepInterval": "60s",- "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},- },- },- },- },- },- },- {- Name: "logs_raw",- Summary: "Raw: fetch raw log records",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "raw",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "logs",- "filter": map[string]any{"expression": "severity_text = 'ERROR'"},- "selectFields": []any{- map[string]any{"name": "body", "fieldContext": "log"},- map[string]any{"name": "service.name", "fieldContext": "resource"},- },- "order": []any{- map[string]any{"key": map[string]any{"name": "timestamp", "fieldContext": "log"}, "direction": "desc"},- map[string]any{"key": map[string]any{"name": "id"}, "direction": "desc"},- },- "limit": 50,- "offset": 0,- },- },- },- },- },- },- {- Name: "traces_raw",- Summary: "Raw: fetch raw span records",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "raw",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "traces",- "filter": map[string]any{"expression": "service.name = 'frontend' AND has_error = true"},- "selectFields": []any{- map[string]any{"name": "name", "fieldContext": "span"},- map[string]any{"name": "duration_nano", "fieldContext": "span"},- },- "order": []any{- map[string]any{"key": map[string]any{"name": "timestamp", "fieldContext": "span"}, "direction": "desc"},- },- "limit": 100,- },- },- },- },- },- },- {- Name: "traces_scalar",- Summary: "Scalar: total span count",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "scalar",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "traces",- "aggregations": []any{- map[string]any{"expression": "count()", "alias": "span_count"},- },- "filter": map[string]any{"expression": "service.name = 'frontend'"},- },- },- },- },- },- },- {- Name: "logs_scalar",- Summary: "Scalar: total error log count",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "scalar",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "logs",- "aggregations": []any{- map[string]any{"expression": "count()", "alias": "error_count"},- },- "filter": map[string]any{"expression": "severity_text = 'ERROR'"},- },- },- },- },- },- },- {- Name: "metrics_scalar",- Summary: "Scalar: single reduced metric value",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "scalar",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "metrics",- "aggregations": []any{- map[string]any{"metricName": "http.server.duration.count", "timeAggregation": "rate", "spaceAggregation": "sum", "reduceTo": "sum"},- },- "stepInterval": "60s",- },- },- },- },- },- },- {- Name: "formula",- Summary: "Formula: error rate from two trace queries",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "A",- "signal": "traces",- "aggregations": []any{map[string]any{"expression": "countIf(has_error = true)"}},- "stepInterval": "60s",- "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},- },- },- map[string]any{- "type": "builder_query",- "spec": map[string]any{- "name": "B",- "signal": "traces",- "aggregations": []any{map[string]any{"expression": "count()"}},- "stepInterval": "60s",- "groupBy": []any{map[string]any{"name": "service.name", "fieldContext": "resource"}},- },- },- map[string]any{- "type": "builder_formula",- "spec": map[string]any{- "name": "error_rate",- "expression": "A / B * 100",- },- },- },- },- },- },- {- Name: "promql",- Summary: "PromQL: request rate with UTF-8 metric name",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "promql",- "spec": map[string]any{- "name": "request_rate",- "query": "sum(rate({\"http.server.duration.count\"}[5m])) by (\"service.name\")",- "step": 60,- },- },- },- },- },- },- {- Name: "clickhouse_sql_traces_time_series",- Summary: "ClickHouse SQL: traces time series with resource filter",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "time_series",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "clickhouse_sql",- "spec": map[string]any{- "name": "span_rate",- "query": "WITH __resource_filter AS (" +- " SELECT fingerprint FROM signoz_traces.distributed_traces_v3_resource" +- " WHERE seen_at_ts_bucket_start >= $start_timestamp - 1800 AND seen_at_ts_bucket_start <= $end_timestamp" +- " ) SELECT toStartOfInterval(timestamp, INTERVAL 60 SECOND) AS ts, count() AS value" +- " FROM signoz_traces.distributed_signoz_index_v3" +- " WHERE resource_fingerprint GLOBAL IN (SELECT fingerprint FROM __resource_filter)" +- " AND timestamp >= $start_datetime AND timestamp <= $end_datetime" +- " AND ts_bucket_start >= $start_timestamp - 1800 AND ts_bucket_start <= $end_timestamp" +- " GROUP BY ts ORDER BY ts",- },- },- },- },- },- },- {- Name: "clickhouse_sql_logs_raw",- Summary: "ClickHouse SQL: raw logs with resource filter",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "raw",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "clickhouse_sql",- "spec": map[string]any{- "name": "recent_errors",- "query": "WITH __resource_filter AS (" +- " SELECT fingerprint FROM signoz_logs.distributed_logs_v2_resource" +- " WHERE seen_at_ts_bucket_start >= $start_timestamp - 1800 AND seen_at_ts_bucket_start <= $end_timestamp" +- " ) SELECT timestamp, body" +- " FROM signoz_logs.distributed_logs_v2" +- " WHERE resource_fingerprint GLOBAL IN (SELECT fingerprint FROM __resource_filter)" +- " AND timestamp >= $start_timestamp_nano AND timestamp <= $end_timestamp_nano" +- " AND ts_bucket_start >= $start_timestamp - 1800 AND ts_bucket_start <= $end_timestamp" +- " AND severity_text = 'ERROR'" +- " ORDER BY timestamp DESC LIMIT 100",- },- },- },- },- },- },- {- Name: "clickhouse_sql_traces_scalar",- Summary: "ClickHouse SQL: scalar aggregate with resource filter",- Value: map[string]any{- "schemaVersion": "v1",- "start": 1640995200000,- "end": 1640998800000,- "requestType": "scalar",- "compositeQuery": map[string]any{- "queries": []any{- map[string]any{- "type": "clickhouse_sql",- "spec": map[string]any{- "name": "total_spans",- "query": "WITH __resource_filter AS (" +- " SELECT fingerprint FROM signoz_traces.distributed_traces_v3_resource" +- " WHERE seen_at_ts_bucket_start >= $start_timestamp - 1800 AND seen_at_ts_bucket_start <= $end_timestamp" +- " ) SELECT count() AS value" +- " FROM signoz_traces.distributed_signoz_index_v3" +- " WHERE resource_fingerprint GLOBAL IN (SELECT fingerprint FROM __resource_filter)" +- " AND timestamp >= $start_datetime AND timestamp <= $end_datetime" +- " AND ts_bucket_start >= $start_timestamp - 1800 AND ts_bucket_start <= $end_timestamp",- },- },- },- },- },- },-}diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.goindex 489dda3d89..f55aa99434 100644--- a/pkg/query-service/app/http_handler.go+++ b/pkg/query-service/app/http_handler.go@@ -79,8 +79,6 @@ import ("github.com/SigNoz/signoz/pkg/query-service/model""github.com/SigNoz/signoz/pkg/query-service/rules""github.com/SigNoz/signoz/pkg/version"-- querierAPI "github.com/SigNoz/signoz/pkg/querier")type status string@@ -145,8 +143,6 @@ type APIHandler struct {LicensingAPI licensing.API- QuerierAPI *querierAPI.API-QueryParserAPI *queryparser.APISignoz *signoz.SigNoz@@ -175,8 +171,6 @@ type APIHandlerOpts struct {LicensingAPI licensing.API- QuerierAPI *querierAPI.API-QueryParserAPI *queryparser.APISignoz *signoz.SigNoz@@ -239,7 +233,6 @@ func NewAPIHandler(opts APIHandlerOpts, config signoz.Config) (*APIHandler, erroAlertmanagerAPI: opts.AlertmanagerAPI,LicensingAPI: opts.LicensingAPI,Signoz: opts.Signoz,- QuerierAPI: opts.QuerierAPI,QueryParserAPI: opts.QueryParserAPI,}@@ -396,7 +389,7 @@ func (aH *APIHandler) RegisterQueryRangeV3Routes(router *mux.Router, am *middlewsubRouter.HandleFunc("/query_progress", am.ViewAccess(aH.GetQueryProgressUpdates)).Methods(http.MethodGet)// live logs- subRouter.HandleFunc("/logs/livetail", am.ViewAccess(aH.QuerierAPI.QueryRawStream)).Methods(http.MethodGet)+ subRouter.HandleFunc("/logs/livetail", am.ViewAccess(aH.Signoz.Handlers.QuerierHandler.QueryRawStream)).Methods(http.MethodGet)}func (aH *APIHandler) RegisterInfraMetricsRoutes(router *mux.Router, am *middleware.AuthZ) {@@ -470,12 +463,6 @@ func (aH *APIHandler) RegisterQueryRangeV4Routes(router *mux.Router, am *middlewsubRouter.HandleFunc("/metric/metric_metadata", am.ViewAccess(aH.getMetricMetadata)).Methods(http.MethodGet)}-func (aH *APIHandler) RegisterQueryRangeV5Routes(router *mux.Router, am *middleware.AuthZ) {- subRouter := router.PathPrefix("/api/v5").Subrouter()- subRouter.HandleFunc("/query_range", am.ViewAccess(aH.QuerierAPI.QueryRange)).Methods(http.MethodPost)- subRouter.HandleFunc("/substitute_vars", am.ViewAccess(aH.QuerierAPI.ReplaceVariables)).Methods(http.MethodPost)-}-// todo(remove): Implemented at render package (github.com/SigNoz/signoz/pkg/http/render) with the new error structurefunc (aH *APIHandler) Respond(w http.ResponseWriter, data interface{}) {writeHttpResponse(w, data)diff --git a/pkg/query-service/app/server.go b/pkg/query-service/app/server.goindex 8060d6c8a9..965f2080ea 100644--- a/pkg/query-service/app/server.go+++ b/pkg/query-service/app/server.go@@ -23,7 +23,6 @@ import ("github.com/SigNoz/signoz/pkg/modules/organization""github.com/SigNoz/signoz/pkg/prometheus""github.com/SigNoz/signoz/pkg/querier"- querierAPI "github.com/SigNoz/signoz/pkg/querier""github.com/SigNoz/signoz/pkg/query-service/agentConf""github.com/SigNoz/signoz/pkg/query-service/app/clickhouseReader""github.com/SigNoz/signoz/pkg/query-service/app/cloudintegrations"@@ -133,7 +132,6 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {AlertmanagerAPI: alertmanager.NewAPI(signoz.Alertmanager),LicensingAPI: nooplicensing.NewLicenseAPI(),Signoz: signoz,- QuerierAPI: querierAPI.NewAPI(signoz.Instrumentation.ToProviderSettings(), signoz.Querier, signoz.Analytics),QueryParserAPI: queryparser.NewAPI(signoz.Instrumentation.ToProviderSettings(), signoz.QueryParser),}, config)if err != nil {@@ -217,7 +215,6 @@ func (s *Server) createPublicServer(api *APIHandler, web web.Web) (*http.Server,api.RegisterInfraMetricsRoutes(r, am)api.RegisterWebSocketPaths(r, am)api.RegisterQueryRangeV4Routes(r, am)- api.RegisterQueryRangeV5Routes(r, am)api.RegisterMessagingQueuesRoutes(r, am)api.RegisterThirdPartyApiRoutes(r, am)api.MetricExplorerRoutes(r, am)diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.goindex ccbf740ce0..b35ddbac8b 100644--- a/pkg/signoz/handler.go+++ b/pkg/signoz/handler.go@@ -1,6 +1,7 @@package signozimport (+ "github.com/SigNoz/signoz/pkg/analytics""github.com/SigNoz/signoz/pkg/authz""github.com/SigNoz/signoz/pkg/authz/signozauthzapi""github.com/SigNoz/signoz/pkg/factory"@@ -50,12 +51,14 @@ type Handlers struct {Fields fields.HandlerAuthzHandler authz.HandlerZeusHandler zeus.Handler+ QuerierHandler querier.Handler}func NewHandlers(modules Modules,providerSettings factory.ProviderSettings,- querier querier.Querier,+ analytics analytics.Analytics,+ querierHandler querier.Handler,licensing licensing.Licensing,global global.Global,flaggerService flagger.Flagger,@@ -80,5 +83,6 @@ func NewHandlers(Fields: implfields.NewHandler(providerSettings, telemetryMetadataStore),AuthzHandler: signozauthzapi.NewHandler(authz),ZeusHandler: zeus.NewHandler(zeusService, licensing),+ QuerierHandler: querierHandler,}}diff --git a/pkg/signoz/handler_test.go b/pkg/signoz/handler_test.goindex 66df95b016..f67f53f8c6 100644--- a/pkg/signoz/handler_test.go+++ b/pkg/signoz/handler_test.go@@ -13,6 +13,7 @@ import ("github.com/SigNoz/signoz/pkg/factory/factorytest""github.com/SigNoz/signoz/pkg/modules/dashboard/impldashboard""github.com/SigNoz/signoz/pkg/modules/organization/implorganization"+ "github.com/SigNoz/signoz/pkg/querier""github.com/SigNoz/signoz/pkg/queryparser""github.com/SigNoz/signoz/pkg/sharder""github.com/SigNoz/signoz/pkg/sharder/noopsharder"@@ -42,7 +43,8 @@ func TestNewHandlers(t *testing.T) {dashboardModule := impldashboard.NewModule(impldashboard.NewStore(sqlstore), providerSettings, nil, orgGetter, queryParser)modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, nil, nil, nil, nil, nil, nil, nil, queryParser, Config{}, dashboardModule)- handlers := NewHandlers(modules, providerSettings, nil, nil, nil, nil, nil, nil, nil, nil)+ querierHandler := querier.NewHandler(providerSettings, nil, nil)+ handlers := NewHandlers(modules, providerSettings, nil, querierHandler, nil, nil, nil, nil, nil, nil, nil)reflectVal := reflect.ValueOf(handlers)for i := 0; i < reflectVal.NumField(); i++ {f := reflectVal.Field(i)diff --git a/pkg/signoz/openapi.go b/pkg/signoz/openapi.goindex 7caae4223b..93aeacc3f8 100644--- a/pkg/signoz/openapi.go+++ b/pkg/signoz/openapi.go@@ -4,7 +4,6 @@ import ("bytes""context""encoding/json"- "net/http""os""reflect"@@ -27,7 +26,6 @@ import ("github.com/SigNoz/signoz/pkg/modules/user""github.com/SigNoz/signoz/pkg/querier""github.com/SigNoz/signoz/pkg/types/ctxtypes"- "github.com/gorilla/mux""github.com/SigNoz/signoz/pkg/zeus""github.com/swaggest/jsonschema-go""github.com/swaggest/openapi-go"@@ -60,15 +58,12 @@ func NewOpenAPI(ctx context.Context, instrumentation instrumentation.Instrumentastruct{ fields.Handler }{},struct{ authz.Handler }{},struct{ zeus.Handler }{},+ struct{ querier.Handler }{},).New(ctx, instrumentation.ToProviderSettings(), apiserver.Config{})if err != nil {return nil, err}- // Register routes that live outside the APIServer modules- // so they are discovered by the OpenAPI walker.- registerQueryRoutes(apiserver.Router())-reflector := openapi3.NewReflector()reflector.JSONSchemaReflector().DefaultOptions = append(reflector.JSONSchemaReflector().DefaultOptions, jsonschema.InterceptDefName(func(t reflect.Type, defaultDefName string) string {if defaultDefName == "RenderSuccessResponse" {@@ -159,10 +154,3 @@ func convertJSONNumbers(v interface{}) {}}}--func registerQueryRoutes(router *mux.Router) {- router.Handle("/api/v5/query_range", handler.New(- func(http.ResponseWriter, *http.Request) {},- querier.QueryRangeV5OpenAPIDef,- )).Methods(http.MethodPost)-}diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex 6fc1246dde..24b493fd8f 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -253,6 +253,7 @@ func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.Auhandlers.Fields,handlers.AuthzHandler,handlers.ZeusHandler,+ handlers.QuerierHandler,),)}diff --git a/pkg/signoz/signoz.go b/pkg/signoz/signoz.goindex 51d6de90a4..1e9c3e65fe 100644--- a/pkg/signoz/signoz.go+++ b/pkg/signoz/signoz.go@@ -90,6 +90,7 @@ func New(authzCallback func(context.Context, sqlstore.SQLStore, licensing.Licensing, dashboard.Module) factory.ProviderFactory[authz.AuthZ, authz.Config],dashboardModuleCallback func(sqlstore.SQLStore, factory.ProviderSettings, analytics.Analytics, organization.Getter, queryparser.QueryParser, querier.Querier, licensing.Licensing) dashboard.Module,gatewayProviderFactory func(licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config],+ querierHandlerCallback func(factory.ProviderSettings, querier.Querier, analytics.Analytics) querier.Handler,) (*SigNoz, error) {// Initialize instrumentationinstrumentation, err := instrumentation.New(ctx, config.Instrumentation, version.Info, "signoz")@@ -391,8 +392,11 @@ func New(userService := impluser.NewService(providerSettings, impluser.NewStore(sqlstore, providerSettings), modules.User, orgGetter, authz, config.User.Root)+ // Initialize the querier handler via callback (allows EE to decorate with anomaly detection)+ querierHandler := querierHandlerCallback(providerSettings, querier, analytics)+// Initialize all handlers for the modules- handlers := NewHandlers(modules, providerSettings, querier, licensing, global, flagger, gateway, telemetryMetadataStore, authz, zeus)+ handlers := NewHandlers(modules, providerSettings, analytics, querierHandler, licensing, global, flagger, gateway, telemetryMetadataStore, authz, zeus)// Initialize the API serverapiserver, err := factory.NewProviderFromNamedMap(