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(lint): enable godot and staticcheck (#10775)

Vikrant Gupta2163e1ce41b2
diff --git a/.golangci.yml b/.golangci.yml
index b076724dd7..40d071b12f 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -6,12 +6,14 @@ linters:
- depguard
- errcheck
- forbidigo
+ - godot
- govet
- iface
- ineffassign
- misspell
- nilnil
- sloglint
+ - staticcheck
- wastedassign
- unparam
- unused
diff --git a/ee/anomaly/hourly.go b/ee/anomaly/hourly.go
index 95a21bdaa5..d1aaca14d7 100644
--- a/ee/anomaly/hourly.go
+++ b/ee/anomaly/hourly.go
@@ -16,7 +16,7 @@ func (hp *HourlyProvider) GetBaseSeasonalProvider() *BaseSeasonalProvider {
return &hp.BaseSeasonalProvider
}
-// NewHourlyProvider now uses the generic option type
+// NewHourlyProvider now uses the generic option type.
func NewHourlyProvider(opts ...GenericProviderOption[*HourlyProvider]) *HourlyProvider {
hp := &HourlyProvider{
BaseSeasonalProvider: BaseSeasonalProvider{},
diff --git a/ee/anomaly/params.go b/ee/anomaly/params.go
index 9a1aa8a71c..58a47b2ffa 100644
--- a/ee/anomaly/params.go
+++ b/ee/anomaly/params.go
@@ -47,7 +47,7 @@ type AnomaliesResponse struct {
// | |
// (rounded value for past peiod) + (seasonal growth)
//
-// score = abs(value - prediction) / stddev (current_season_query)
+// score = abs(value - prediction) / stddev (current_season_query).
type anomalyQueryParams struct {
// CurrentPeriodQuery is the query range params for period user is looking at or eval window
// Example: (now-5m, now), (now-30m, now), (now-1h, now)
diff --git a/ee/anomaly/seasonal.go b/ee/anomaly/seasonal.go
index 8753289ad8..875a9f2b8c 100644
--- a/ee/anomaly/seasonal.go
+++ b/ee/anomaly/seasonal.go
@@ -18,12 +18,12 @@ var (
movingAvgWindowSize = 7
)
-// BaseProvider is an interface that includes common methods for all provider types
+// BaseProvider is an interface that includes common methods for all provider types.
type BaseProvider interface {
GetBaseSeasonalProvider() *BaseSeasonalProvider
}
-// GenericProviderOption is a generic type for provider options
+// GenericProviderOption is a generic type for provider options.
type GenericProviderOption[T BaseProvider] func(T)
func WithQuerier[T BaseProvider](querier querier.Querier) GenericProviderOption[T] {
@@ -121,7 +121,7 @@ func (p *BaseSeasonalProvider) getResults(ctx context.Context, orgID valuer.UUID
}
// getMatchingSeries gets the matching series from the query result
-// for the given series
+// for the given series.
func (p *BaseSeasonalProvider) getMatchingSeries(_ context.Context, queryResult *qbtypes.TimeSeriesData, series *qbtypes.TimeSeries) *qbtypes.TimeSeries {
if queryResult == nil || len(queryResult.Aggregations) == 0 || len(queryResult.Aggregations[0].Series) == 0 {
return nil
@@ -155,13 +155,14 @@ func (p *BaseSeasonalProvider) getStdDev(series *qbtypes.TimeSeries) float64 {
avg := p.getAvg(series)
var sum float64
for _, smpl := range series.Values {
- sum += math.Pow(smpl.Value-avg, 2)
+ d := smpl.Value - avg
+ sum += d * d
}
return math.Sqrt(sum / float64(len(series.Values)))
}
// getMovingAvg gets the moving average for the given series
-// for the given window size and start index
+// for the given window size and start index.
func (p *BaseSeasonalProvider) getMovingAvg(series *qbtypes.TimeSeries, movingAvgWindowSize, startIdx int) float64 {
if series == nil || len(series.Values) == 0 {
return 0
@@ -236,7 +237,7 @@ func (p *BaseSeasonalProvider) getPredictedSeries(
// getBounds gets the upper and lower bounds for the given series
// for the given z score threshold
// moving avg of the previous period series + z score threshold * std dev of the series
-// moving avg of the previous period series - z score threshold * std dev of the series
+// moving avg of the previous period series - z score threshold * std dev of the series.
func (p *BaseSeasonalProvider) getBounds(
series, predictedSeries, weekSeries *qbtypes.TimeSeries,
zScoreThreshold float64,
@@ -269,7 +270,7 @@ func (p *BaseSeasonalProvider) getBounds(
// getExpectedValue gets the expected value for the given series
// for the given index
-// prevSeriesAvg + currentSeasonSeriesAvg - mean of past season series, past2 season series and past3 season series
+// prevSeriesAvg + currentSeasonSeriesAvg - mean of past season series, past2 season series and past3 season series.
func (p *BaseSeasonalProvider) getExpectedValue(
_, prevSeries, currentSeasonSeries, pastSeasonSeries, past2SeasonSeries, past3SeasonSeries *qbtypes.TimeSeries, idx int,
) float64 {
@@ -283,7 +284,7 @@ func (p *BaseSeasonalProvider) getExpectedValue(
// getScore gets the anomaly score for the given series
// for the given index
-// (value - expectedValue) / std dev of the series
+// (value - expectedValue) / std dev of the series.
func (p *BaseSeasonalProvider) getScore(
series, prevSeries, weekSeries, weekPrevSeries, past2SeasonSeries, past3SeasonSeries *qbtypes.TimeSeries, value float64, idx int,
) float64 {
@@ -296,7 +297,7 @@ func (p *BaseSeasonalProvider) getScore(
// getAnomalyScores gets the anomaly scores for the given series
// for the given index
-// (value - expectedValue) / std dev of the series
+// (value - expectedValue) / std dev of the series.
func (p *BaseSeasonalProvider) getAnomalyScores(
series, prevSeries, currentSeasonSeries, pastSeasonSeries, past2SeasonSeries, past3SeasonSeries *qbtypes.TimeSeries,
) *qbtypes.TimeSeries {
diff --git a/ee/licensing/config.go b/ee/licensing/config.go
index 8fc87c0ba1..8359ef2b12 100644
--- a/ee/licensing/config.go
+++ b/ee/licensing/config.go
@@ -13,7 +13,7 @@ var (
once sync.Once
)
-// initializes the licensing configuration
+// Config initializes the licensing configuration.
func Config(pollInterval time.Duration, failureThreshold int) licensing.Config {
once.Do(func() {
config = licensing.Config{PollInterval: pollInterval, FailureThreshold: failureThreshold}
diff --git a/ee/querier/handler.go b/ee/querier/handler.go
index 31ced99b99..fd52a7e9fd 100644
--- a/ee/querier/handler.go
+++ b/ee/querier/handler.go
@@ -79,7 +79,7 @@ func (h *handler) QueryRange(rw http.ResponseWriter, req *http.Request) {
// 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())
+ stepIntervals[anomalyQuery.Name] = uint64(anomalyQuery.StepInterval.Seconds())
}
finalResp := &qbtypes.QueryRangeResponse{
diff --git a/ee/sqlstore/postgressqlstore/dialect.go b/ee/sqlstore/postgressqlstore/dialect.go
index 4f6987bda7..04f5ba5316 100644
--- a/ee/sqlstore/postgressqlstore/dialect.go
+++ b/ee/sqlstore/postgressqlstore/dialect.go
@@ -336,9 +336,10 @@ func (dialect *dialect) UpdatePrimaryKey(ctx context.Context, bun bun.IDB, oldMo
}
fkReference := ""
- if reference == Org {
+ switch reference {
+ case Org:
fkReference = OrgReference
- } else if reference == User {
+ case User:
fkReference = UserReference
}
@@ -392,9 +393,10 @@ func (dialect *dialect) AddPrimaryKey(ctx context.Context, bun bun.IDB, oldModel
}
fkReference := ""
- if reference == Org {
+ switch reference {
+ case Org:
fkReference = OrgReference
- } else if reference == User {
+ case User:
fkReference = UserReference
}
diff --git a/ee/zeus/config.go b/ee/zeus/config.go
index 2a81e55608..3a4775d2d4 100644
--- a/ee/zeus/config.go
+++ b/ee/zeus/config.go
@@ -19,7 +19,7 @@ var (
once sync.Once
)
-// initializes the Zeus configuration
+// initializes the Zeus configuration.
func Config() zeus.Config {
once.Do(func() {
parsedURL, err := neturl.Parse(url)
diff --git a/ee/zeus/httpzeus/provider.go b/ee/zeus/httpzeus/provider.go
index 83abdc013d..76248edfe1 100644
--- a/ee/zeus/httpzeus/provider.go
+++ b/ee/zeus/httpzeus/provider.go
@@ -189,7 +189,7 @@ func (provider *Provider) do(ctx context.Context, url *url.URL, method string, k
return nil, provider.errFromStatusCode(response.StatusCode, errorMessage)
}
-// This can be taken down to the client package
+// This can be taken down to the client package.
func (provider *Provider) errFromStatusCode(statusCode int, errorMessage string) error {
switch statusCode {
case http.StatusBadRequest:
diff --git a/pkg/alertmanager/alertmanagerserver/dispatcher.go b/pkg/alertmanager/alertmanagerserver/dispatcher.go
index ef4d03c670..f7bb629f19 100644
--- a/pkg/alertmanager/alertmanagerserver/dispatcher.go
+++ b/pkg/alertmanager/alertmanagerserver/dispatcher.go
@@ -47,7 +47,7 @@ type Dispatcher struct {
receiverRoutes map[string]*dispatch.Route
}
-// We use the upstream Limits interface from Prometheus
+// We use the upstream Limits interface from Prometheus.
type Limits = dispatch.Limits
// NewDispatcher returns a new Dispatcher.
@@ -273,7 +273,7 @@ type notifyFunc func(context.Context, ...*types.Alert) bool
// processAlert determines in which aggregation group the alert falls
// and inserts it.
-// no data alert will only have ruleId and no data label
+// no data alert will only have ruleId and no data label.
func (d *Dispatcher) processAlert(alert *types.Alert, route *dispatch.Route) {
ruleId := getRuleIDFromAlert(alert)
config, err := d.notificationManager.GetNotificationConfig(d.orgID, ruleId)
@@ -510,7 +510,7 @@ func (ag *aggrGroup) flush(notify func(...*types.Alert) bool) {
}
}
-// unlimitedLimits provides unlimited aggregation groups for SigNoz
+// unlimitedLimits provides unlimited aggregation groups for SigNoz.
type unlimitedLimits struct{}
func (u *unlimitedLimits) MaxNumberOfAggregationGroups() int { return 0 }
diff --git a/pkg/alertmanager/alertmanagerserver/server_e2e_test.go b/pkg/alertmanager/alertmanagerserver/server_e2e_test.go
index 56788da3e5..508fe9721f 100644
--- a/pkg/alertmanager/alertmanagerserver/server_e2e_test.go
+++ b/pkg/alertmanager/alertmanagerserver/server_e2e_test.go
@@ -169,19 +169,20 @@ func TestEndToEndAlertManagerFlow(t *testing.T) {
require.Len(t, alerts, 3, "Expected 3 active alerts")
for _, alert := range alerts {
- require.Equal(t, "high-cpu-usage", alert.Alert.Labels["ruleId"])
- require.NotEmpty(t, alert.Alert.Labels["severity"])
- require.Contains(t, []string{"critical", "warning"}, alert.Alert.Labels["severity"])
- require.Equal(t, "prod-cluster", alert.Alert.Labels["cluster"])
- require.NotEmpty(t, alert.Alert.Labels["instance"])
+ require.Equal(t, "high-cpu-usage", alert.Labels["ruleId"])
+ require.NotEmpty(t, alert.Labels["severity"])
+ require.Contains(t, []string{"critical", "warning"}, alert.Labels["severity"])
+ require.Equal(t, "prod-cluster", alert.Labels["cluster"])
+ require.NotEmpty(t, alert.Labels["instance"])
}
criticalAlerts := 0
warningAlerts := 0
for _, alert := range alerts {
- if alert.Alert.Labels["severity"] == "critical" {
+ switch alert.Labels["severity"] {
+ case "critical":
criticalAlerts++
- } else if alert.Alert.Labels["severity"] == "warning" {
+ case "warning":
warningAlerts++
}
}
diff --git a/pkg/alertmanager/alertmanagerserver/server_test.go b/pkg/alertmanager/alertmanagerserver/server_test.go
index 8121f35caf..4c36a4f869 100644
--- a/pkg/alertmanager/alertmanagerserver/server_test.go
+++ b/pkg/alertmanager/alertmanagerserver/server_test.go
@@ -124,7 +124,7 @@ func TestServerPutAlerts(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, 1, len(gettableAlerts))
- assert.Equal(t, gettableAlerts[0].Alert.Labels["alertname"], "test-alert")
+ assert.Equal(t, gettableAlerts[0].Labels["alertname"], "test-alert")
assert.NoError(t, server.Stop(context.Background()))
}
diff --git a/pkg/alertmanager/alertmanagerserver/telemetry.go b/pkg/alertmanager/alertmanagerserver/telemetry.go
index 1ad1d0f555..1cc3f26380 100644
--- a/pkg/alertmanager/alertmanagerserver/telemetry.go
+++ b/pkg/alertmanager/alertmanagerserver/telemetry.go
@@ -9,7 +9,7 @@ type DispatcherMetrics struct {
}
// NewDispatcherMetrics returns a new registered DispatchMetrics.
-// todo(aniketio-ctrl): change prom metrics to otel metrics
+// todo(aniketio-ctrl): change prom metrics to otel metrics.
func NewDispatcherMetrics(registerLimitMetrics bool, r prometheus.Registerer) *DispatcherMetrics {
m := DispatcherMetrics{
aggrGroups: prometheus.NewGauge(
diff --git a/pkg/alertmanager/nfmanager/nfmanagertest/provider.go b/pkg/alertmanager/nfmanager/nfmanagertest/provider.go
index f003c4454d..4a6a8a72d1 100644
--- a/pkg/alertmanager/nfmanager/nfmanagertest/provider.go
+++ b/pkg/alertmanager/nfmanager/nfmanagertest/provider.go
@@ -9,7 +9,7 @@ import (
"github.com/prometheus/common/model"
)
-// MockNotificationManager is a simple mock implementation of NotificationManager
+// MockNotificationManager is a simple mock implementation of NotificationManager.
type MockNotificationManager struct {
configs map[string]*alertmanagertypes.NotificationConfig
routes map[string]*alertmanagertypes.RoutePolicy
@@ -17,7 +17,7 @@ type MockNotificationManager struct {
errors map[string]error
}
-// NewMock creates a new mock notification manager
+// NewMock creates a new mock notification manager.
func NewMock() *MockNotificationManager {
return &MockNotificationManager{
configs: make(map[string]*alertmanagertypes.NotificationConfig),
diff --git a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go b/pkg/alertmanager/nfmanager/rulebasednotification/provider.go
index e487304b66..ffe696f988 100644
--- a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go
+++ b/pkg/alertmanager/nfmanager/rulebasednotification/provider.go
@@ -216,7 +216,7 @@ func (r *provider) Match(ctx context.Context, orgID string, ruleID string, set m
// the nested structure takes precedence. That means we will replace an existing leaf at any
// intermediate path with a map so we can materialize the deeper structure.
// TODO(srikanthccv): we need a better solution to handle this, remove the following
-// when we update the expr to support dotted keys
+// when we update the expr to support dotted keys.
func (r *provider) convertLabelSetToEnv(ctx context.Context, labelSet model.LabelSet) map[string]interface{} {
env := make(map[string]interface{})
diff --git a/pkg/alertmanager/signozalertmanager/provider.go b/pkg/alertmanager/signozalertmanager/provider.go
index 1a35813083..92ef7e3fe1 100644
--- a/pkg/alertmanager/signozalertmanager/provider.go
+++ b/pkg/alertmanager/signozalertmanager/provider.go
@@ -217,7 +217,7 @@ func (provider *provider) GetConfig(ctx context.Context, orgID string) (*alertma
}
func (provider *provider) SetDefaultConfig(ctx context.Context, orgID string) error {
- config, err := alertmanagertypes.NewDefaultConfig(provider.config.Signoz.Config.Global, provider.config.Signoz.Config.Route, orgID)
+ config, err := alertmanagertypes.NewDefaultConfig(provider.config.Signoz.Global, provider.config.Signoz.Route, orgID)
if err != nil {
return err
}
diff --git a/pkg/authn/callbackauthn/googlecallbackauthn/authn.go b/pkg/authn/callbackauthn/googlecallbackauthn/authn.go
index 2f04ffd528..f7c3cd7150 100644
--- a/pkg/authn/callbackauthn/googlecallbackauthn/authn.go
+++ b/pkg/authn/callbackauthn/googlecallbackauthn/authn.go
@@ -210,7 +210,7 @@ func (a *AuthN) fetchGoogleWorkspaceGroups(ctx context.Context, userEmail string
return a.getGroups(ctx, adminService, userEmail, config.FetchTransitiveGroupMembership, checkedGroups)
}
-// Recursive method
+// Recursive method.
func (a *AuthN) getGroups(ctx context.Context, adminService *admin.Service, userEmail string, fetchTransitive bool, checkedGroups map[string]struct{}) ([]string, error) {
var userGroups []string
var pageToken string
diff --git a/pkg/config/conf.go b/pkg/config/conf.go
index f890849d4b..982e4bb0bc 100644
--- a/pkg/config/conf.go
+++ b/pkg/config/conf.go
@@ -27,7 +27,7 @@ func NewConf() *Conf {
// NewConfFromMap creates a new Conf instance from a map.
func NewConfFromMap(m map[string]any) (*Conf, error) {
conf := NewConf()
- if err := conf.Koanf.Load(confmap.Provider(m, KoanfDelimiter), nil); err != nil {
+ if err := conf.Load(confmap.Provider(m, KoanfDelimiter), nil); err != nil {
return nil, err
}
@@ -74,7 +74,7 @@ func (conf *Conf) Unmarshal(path string, input any, tags ...string) error {
Result: input,
}
- err := conf.Koanf.UnmarshalWithConf(path, input, koanf.UnmarshalConf{Tag: tag, DecoderConfig: dc})
+ err := conf.UnmarshalWithConf(path, input, koanf.UnmarshalConf{Tag: tag, DecoderConfig: dc})
if err != nil {
return err
}
@@ -93,7 +93,7 @@ func (conf *Conf) Set(key string, input any) error {
}
newConf := NewConf()
- if err := newConf.Koanf.Load(confmap.Provider(m, KoanfDelimiter), nil); err != nil {
+ if err := newConf.Load(confmap.Provider(m, KoanfDelimiter), nil); err != nil {
return err
}
diff --git a/pkg/contextlinks/alert_link_visitor.go b/pkg/contextlinks/alert_link_visitor.go
index 09714553e9..6462db063b 100644
--- a/pkg/contextlinks/alert_link_visitor.go
+++ b/pkg/contextlinks/alert_link_visitor.go
@@ -40,7 +40,7 @@ type WhereClauseRewriter struct {
// In this case, the Severity text will appear in the `labels` if it were part of the group
// by clause, in which case we replace it with the actual value for the notification
// i.e Severity text = WARN
-// If the Severity text is not part of the group by clause, then we add it as it is
+// If the Severity text is not part of the group by clause, then we add it as it is.
func PrepareFilterExpression(labels map[string]string, whereClause string, groupByItems []qbtypes.GroupByKey) string {
if whereClause == "" && len(labels) == 0 {
return ""
@@ -100,12 +100,12 @@ func PrepareFilterExpression(labels map[string]string, whereClause string, group
return rewrittenClause
}
-// Visit implements the visitor for the query rule
+// Visit implements the visitor for the query rule.
func (r *WhereClauseRewriter) Visit(tree antlr.ParseTree) interface{} {
return tree.Accept(r)
}
-// VisitQuery visits the query node
+// VisitQuery visits the query node.
func (r *WhereClauseRewriter) VisitQuery(ctx *parser.QueryContext) interface{} {
if ctx.Expression() != nil {
ctx.Expression().Accept(r)
@@ -113,7 +113,7 @@ func (r *WhereClauseRewriter) VisitQuery(ctx *parser.QueryContext) interface{} {
return nil
}
-// VisitExpression visits the expression node
+// VisitExpression visits the expression node.
func (r *WhereClauseRewriter) VisitExpression(ctx *parser.ExpressionContext) interface{} {
if ctx.OrExpression() != nil {
ctx.OrExpression().Accept(r)
@@ -121,7 +121,7 @@ func (r *WhereClauseRewriter) VisitExpression(ctx *parser.ExpressionContext) int
return nil
}
-// VisitOrExpression visits OR expressions
+// VisitOrExpression visits OR expressions.
func (r *WhereClauseRewriter) VisitOrExpression(ctx *parser.OrExpressionContext) interface{} {
for i, andExpr := range ctx.AllAndExpression() {
if i > 0 {
@@ -132,7 +132,7 @@ func (r *WhereClauseRewriter) VisitOrExpression(ctx *parser.OrExpressionContext)
return nil
}
-// VisitAndExpression visits AND expressions
+// VisitAndExpression visits AND expressions.
func (r *WhereClauseRewriter) VisitAndExpression(ctx *parser.AndExpressionContext) interface{} {
unaryExprs := ctx.AllUnaryExpression()
for i, unaryExpr := range unaryExprs {
@@ -150,7 +150,7 @@ func (r *WhereClauseRewriter) VisitAndExpression(ctx *parser.AndExpressionContex
return nil
}
-// VisitUnaryExpression visits unary expressions (with optional NOT)
+// VisitUnaryExpression visits unary expressions (with optional NOT).
func (r *WhereClauseRewriter) VisitUnaryExpression(ctx *parser.UnaryExpressionContext) interface{} {
if ctx.NOT() != nil {
r.rewritten.WriteString("NOT ")
@@ -161,7 +161,7 @@ func (r *WhereClauseRewriter) VisitUnaryExpression(ctx *parser.UnaryExpressionCo
return nil
}
-// VisitPrimary visits primary expressions
+// VisitPrimary visits primary expressions.
func (r *WhereClauseRewriter) VisitPrimary(ctx *parser.PrimaryContext) interface{} {
if ctx.LPAREN() != nil && ctx.RPAREN() != nil {
r.rewritten.WriteString("(")
@@ -183,7 +183,7 @@ func (r *WhereClauseRewriter) VisitPrimary(ctx *parser.PrimaryContext) interface
return nil
}
-// VisitComparison visits comparison expressions
+// VisitComparison visits comparison expressions.
func (r *WhereClauseRewriter) VisitComparison(ctx *parser.ComparisonContext) interface{} {
if ctx.Key() == nil {
return nil
@@ -304,7 +304,7 @@ func (r *WhereClauseRewriter) VisitComparison(ctx *parser.ComparisonContext) int
return nil
}
-// VisitInClause visits IN clauses
+// VisitInClause visits IN clauses.
func (r *WhereClauseRewriter) VisitInClause(ctx *parser.InClauseContext) interface{} {
r.rewritten.WriteString("IN ")
if ctx.LPAREN() != nil {
@@ -325,7 +325,7 @@ func (r *WhereClauseRewriter) VisitInClause(ctx *parser.InClauseContext) interfa
return nil
}
-// VisitNotInClause visits NOT IN clauses
+// VisitNotInClause visits NOT IN clauses.
func (r *WhereClauseRewriter) VisitNotInClause(ctx *parser.NotInClauseContext) interface{} {
r.rewritten.WriteString("NOT IN ")
if ctx.LPAREN() != nil {
@@ -346,7 +346,7 @@ func (r *WhereClauseRewriter) VisitNotInClause(ctx *parser.NotInClauseContext) i
return nil
}
-// VisitValueList visits value lists
+// VisitValueList visits value lists.
func (r *WhereClauseRewriter) VisitValueList(ctx *parser.ValueListContext) interface{} {
values := ctx.AllValue()
for i, val := range values {
@@ -358,13 +358,13 @@ func (r *WhereClauseRewriter) VisitValueList(ctx *parser.ValueListContext) inter
return nil
}
-// VisitFullText visits full text expressions
+// VisitFullText visits full text expressions.
func (r *WhereClauseRewriter) VisitFullText(ctx *parser.FullTextContext) interface{} {
r.rewritten.WriteString(ctx.GetText())
return nil
}
-// VisitFunctionCall visits function calls
+// VisitFunctionCall visits function calls.
func (r *WhereClauseRewriter) VisitFunctionCall(ctx *parser.FunctionCallContext) interface{} {
// Write function name
if ctx.HAS() != nil {
@@ -385,7 +385,7 @@ func (r *WhereClauseRewriter) VisitFunctionCall(ctx *parser.FunctionCallContext)
return nil
}
-// VisitFunctionParamList visits function parameter lists
+// VisitFunctionParamList visits function parameter lists.
func (r *WhereClauseRewriter) VisitFunctionParamList(ctx *parser.FunctionParamListContext) interface{} {
params := ctx.AllFunctionParam()
for i, param := range params {
@@ -397,7 +397,7 @@ func (r *WhereClauseRewriter) VisitFunctionParamList(ctx *parser.FunctionParamLi
return nil
}
-// VisitFunctionParam visits function parameters
+// VisitFunctionParam visits function parameters.
func (r *WhereClauseRewriter) VisitFunctionParam(ctx *parser.FunctionParamContext) interface{} {
if ctx.Key() != nil {
ctx.Key().Accept(r)
@@ -409,7 +409,7 @@ func (r *WhereClauseRewriter) VisitFunctionParam(ctx *parser.FunctionParamContex
return nil
}
-// VisitArray visits array expressions
+// VisitArray visits array expressions.
func (r *WhereClauseRewriter) VisitArray(ctx *parser.ArrayContext) interface{} {
r.rewritten.WriteString("[")
if ctx.ValueList() != nil {
@@ -419,13 +419,13 @@ func (r *WhereClauseRewriter) VisitArray(ctx *parser.ArrayContext) interface{} {
return nil
}
-// VisitValue visits value expressions
+// VisitValue visits value expressions.
func (r *WhereClauseRewriter) VisitValue(ctx *parser.ValueContext) interface{} {
r.rewritten.WriteString(ctx.GetText())
return nil
}
-// VisitKey visits key expressions
+// VisitKey visits key expressions.
func (r *WhereClauseRewriter) VisitKey(ctx *parser.KeyContext) interface{} {
r.keysSeen[ctx.GetText()] = struct{}{}
r.rewritten.WriteString(ctx.GetText())
@@ -438,7 +438,7 @@ func (r *WhereClauseRewriter) isKeyInWhereClause(key string) bool {
}
// escapeValueIfNeeded adds single quotes to string values and escapes single quotes within them
-// Numeric and boolean values are returned as-is
+// Numeric and boolean values are returned as-is.
func escapeValueIfNeeded(value string) string {
// Check if it's a number
if _, err := fmt.Sscanf(value, "%f", new(float64)); err == nil {
diff --git a/pkg/contextlinks/links.go b/pkg/contextlinks/links.go
index 8497cb55de..006ee79f38 100644
--- a/pkg/contextlinks/links.go
+++ b/pkg/contextlinks/links.go
@@ -146,7 +146,7 @@ func PrepareLinksToLogs(start, end time.Time, filterItems []v3.FilterItem) strin
// In this case, the Severity text will appear in the `lbls` if it were part of the group
// by clause, in which case we replace it with the actual value for the notification
// i.e Severity text = WARN
-// If the Severity text is not part of the group by clause, then we add it as it is
+// If the Severity text is not part of the group by clause, then we add it as it is.
func PrepareFilters(labels map[string]string, whereClauseItems []v3.FilterItem, groupByItems []v3.AttributeKey, keys map[string]v3.AttributeKey) []v3.FilterItem {
filterItems := make([]v3.FilterItem, 0)
diff --git a/pkg/contextlinks/types.go b/pkg/contextlinks/types.go
index 516f7c0c06..323fabf086 100644
--- a/pkg/contextlinks/types.go
+++ b/pkg/contextlinks/types.go
@@ -5,7 +5,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/ruletypes"
)
-// TODO(srikanthccv): Fix the URL management
+// TODO(srikanthccv): Fix the URL management.
type URLShareableTimeRange struct {
Start int64 `json:"start"`
End int64 `json:"end"`
diff --git a/pkg/errors/errors.go b/pkg/errors/errors.go
index 99933cac3b..2d5db55a53 100644
--- a/pkg/errors/errors.go
+++ b/pkg/errors/errors.go
@@ -155,7 +155,7 @@ func (b *base) WithAdditional(a ...string) *base {
// Otherwise, it returns TypeInternal, the original error string
// and the error itself.
//
-//lint:ignore ST1008 we want to return arguments in the 'TCMEUA' order of the struct
+//nolint:staticcheck // ST1008: intentional return order matching struct field order (TCMEUA)
func Unwrapb(cause error) (typ, Code, string, error, string, []string) {
base, ok := cause.(*base)
if ok {
diff --git a/pkg/errors/type.go b/pkg/errors/type.go
index 246c1f53d6..cd4560eecf 100644
--- a/pkg/errors/type.go
+++ b/pkg/errors/type.go
@@ -16,7 +16,7 @@ var (
TypeLicenseUnavailable = typ{"license-unavailable"}
)
-// Defines custom error types
+// Defines custom error types.
type typ struct{ s string }
func (t typ) String() string {
diff --git a/pkg/flagger/flagger.go b/pkg/flagger/flagger.go
index 9b78203543..ef2840698f 100644
--- a/pkg/flagger/flagger.go
+++ b/pkg/flagger/flagger.go
@@ -115,7 +115,7 @@ func (f *flagger) Boolean(ctx context.Context, flag featuretypes.Name, evalCtx f
for _, client := range f.clients {
value, err := client.BooleanValue(ctx, flag.String(), defaultValue, evalCtx.Ctx())
if err != nil {
- f.settings.Logger().ErrorContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Name()))
+ f.settings.Logger().ErrorContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Domain()))
continue
}
@@ -148,7 +148,7 @@ func (f *flagger) String(ctx context.Context, flag featuretypes.Name, evalCtx fe
for _, client := range f.clients {
value, err := client.StringValue(ctx, flag.String(), defaultValue, evalCtx.Ctx())
if err != nil {
- f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Name()))
+ f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Domain()))
continue
}
@@ -181,7 +181,7 @@ func (f *flagger) Float(ctx context.Context, flag featuretypes.Name, evalCtx fea
for _, client := range f.clients {
value, err := client.FloatValue(ctx, flag.String(), defaultValue, evalCtx.Ctx())
if err != nil {
- f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Name()))
+ f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Domain()))
continue
}
@@ -214,7 +214,7 @@ func (f *flagger) Int(ctx context.Context, flag featuretypes.Name, evalCtx featu
for _, client := range f.clients {
value, err := client.IntValue(ctx, flag.String(), defaultValue, evalCtx.Ctx())
if err != nil {
- f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Name()))
+ f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Domain()))
continue
}
@@ -247,7 +247,7 @@ func (f *flagger) Object(ctx context.Context, flag featuretypes.Name, evalCtx fe
for _, client := range f.clients {
value, err := client.ObjectValue(ctx, flag.String(), defaultValue, evalCtx.Ctx())
if err != nil {
- f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Name()))
+ f.settings.Logger().WarnContext(ctx, "failed to get value from client", errors.Attr(err), slog.Any("flag", flag), slog.String("client", client.Metadata().Domain()))
continue
}
diff --git a/pkg/http/handler/openapi.go b/pkg/http/handler/openapi.go
index 6dcad932c7..cbf777129a 100644
--- a/pkg/http/handler/openapi.go
+++ b/pkg/http/handler/openapi.go
@@ -17,7 +17,7 @@ type OpenAPIExample struct {
Value any
}
-// Def is the definition of an OpenAPI operation
+// Def is the definition of an OpenAPI operation.
type OpenAPIDef struct {
ID string
Tags []string
@@ -40,7 +40,7 @@ type OpenAPISecurityScheme struct {
Scopes []string
}
-// Collector is a collector for OpenAPI operations
+// OpenAPICollector is a collector for OpenAPI operations.
type OpenAPICollector struct {
collector *openapi.Collector
}
diff --git a/pkg/http/middleware/middleware.go b/pkg/http/middleware/middleware.go
index 6313089aa4..9660faccfb 100644
--- a/pkg/http/middleware/middleware.go
+++ b/pkg/http/middleware/middleware.go
@@ -6,15 +6,15 @@ const (
pkgname string = "go.signoz.io/pkg/http/middleware"
)
-// Wrapper is an interface implemented by all middlewares
+// Wrapper is an interface implemented by all middlewares.
type Wrapper interface {
Wrap(http.Handler) http.Handler
}
-// WrapperFunc is to Wrapper as http.HandlerFunc is to http.Handler
+// WrapperFunc is to Wrapper as http.HandlerFunc is to http.Handler.
type WrapperFunc func(http.Handler) http.Handler
-// WrapperFunc implements Wrapper
+// WrapperFunc implements Wrapper.
func (m WrapperFunc) Wrap(next http.Handler) http.Handler {
return m(next)
}
diff --git a/pkg/http/middleware/response.go b/pkg/http/middleware/response.go
index 8c781db165..b161afb0f9 100644
--- a/pkg/http/middleware/response.go
+++ b/pkg/http/middleware/response.go
@@ -46,7 +46,7 @@ type nonFlushingBadResponseLoggingWriter struct {
writeError error // The error returned when downstream Write() fails.
}
-// Extends nonFlushingBadResponseLoggingWriter that implements http.Flusher
+// Extends nonFlushingBadResponseLoggingWriter that implements http.Flusher.
type flushingBadResponseLoggingWriter struct {
nonFlushingBadResponseLoggingWriter
f http.Flusher
diff --git a/pkg/http/render/status.go b/pkg/http/render/status.go
index 64dce27645..d22e711de9 100644
--- a/pkg/http/render/status.go
+++ b/pkg/http/render/status.go
@@ -5,7 +5,7 @@ var (
StatusError = status{"error"}
)
-// Defines custom error types
+// Defines custom error types.
type status struct{ s string }
func (s status) String() string {
diff --git a/pkg/instrumentation/instrumentation.go b/pkg/instrumentation/instrumentation.go
index b8471ddd45..a483352527 100644
--- a/pkg/instrumentation/instrumentation.go
+++ b/pkg/instrumentation/instrumentation.go
@@ -25,7 +25,7 @@ type Instrumentation interface {
ToProviderSettings() factory.ProviderSettings
}
-// conversion functions required for using zap interface with underlying slog provider
+// ZapToSlogConverter defines conversion functions required for using zap interface with underlying slog provider.
type ZapToSlogConverter interface {
FieldsToAttributes(fields []zap.Field) []any
}
diff --git a/pkg/instrumentation/loghandler/loghandler.go b/pkg/instrumentation/loghandler/loghandler.go
index 2a3a90f925..ea698e902f 100644
--- a/pkg/instrumentation/loghandler/loghandler.go
+++ b/pkg/instrumentation/loghandler/loghandler.go
@@ -5,10 +5,10 @@ import (
"log/slog"
)
-// LogHandlerFunc is to LogHandler as http.HandlerFunc is to http.Handler
+// LogHandlerFunc is to LogHandler as http.HandlerFunc is to http.Handler.
type LogHandlerFunc func(ctx context.Context, r slog.Record) error
-// LogHandlerFunc implements LogHandler
+// LogHandlerFunc implements LogHandler.
func (m LogHandlerFunc) Handle(ctx context.Context, r slog.Record) error {
return m(ctx, r)
}
@@ -17,7 +17,7 @@ type LogHandler interface {
Handle(ctx context.Context, r slog.Record) error
}
-// Wrapper is an interface implemented by all log handlers
+// Wrapper is an interface implemented by all log handlers.
type Wrapper interface {
Wrap(LogHandler) LogHandler
}
diff --git a/pkg/instrumentation/metric.go b/pkg/instrumentation/metric.go
index 199608c36b..0ab9bd7d00 100644
--- a/pkg/instrumentation/metric.go
+++ b/pkg/instrumentation/metric.go
@@ -22,7 +22,7 @@ import (
)
// readerWithServer wraps a metric reader with an HTTP server for proper shutdown
-// This mirrors the upstream contrib/config implementation
+// This mirrors the upstream contrib/config implementation.
type readerWithServer struct {
sdkmetric.Reader
server *http.Server
@@ -36,7 +36,7 @@ func (rws readerWithServer) Shutdown(ctx context.Context) error {
}
// prometheusReaderWithCustomRegistry creates a Prometheus metric reader using a custom registry
-// This is based on the upstream contrib/config implementation but allows passing a custom registry
+// This is based on the upstream contrib/config implementation but allows passing a custom registry.
func prometheusReaderWithCustomRegistry(ctx context.Context, prometheusConfig *contribsdkconfig.Prometheus, customRegistry *prometheus.Registry) (sdkmetric.Reader, error) {
var opts []otelprom.Option
if prometheusConfig.Host == nil {
@@ -49,10 +49,10 @@ func prometheusReaderWithCustomRegistry(ctx context.Context, prometheusConfig *c
opts = append(opts, otelprom.WithoutScopeInfo())
}
if prometheusConfig.WithoutTypeSuffix != nil && *prometheusConfig.WithoutTypeSuffix {
- opts = append(opts, otelprom.WithoutCounterSuffixes())
+ opts = append(opts, otelprom.WithoutCounterSuffixes()) //nolint:staticcheck // SA1019: WithTranslationStrategy does not provide equivalent per-option granularity
}
if prometheusConfig.WithoutUnits != nil && *prometheusConfig.WithoutUnits {
- opts = append(opts, otelprom.WithoutUnits())
+ opts = append(opts, otelprom.WithoutUnits()) //nolint:staticcheck // SA1019: WithTranslationStrategy does not provide equivalent per-option granularity
}
if prometheusConfig.WithResourceConstantLabels != nil {
if prometheusConfig.WithResourceConstantLabels.Included != nil {
@@ -109,11 +109,11 @@ func prometheusReaderWithCustomRegistry(ctx context.Context, prometheusConfig *c
type shutdownFunc func(context.Context) error
-// noopShutdown is a no-op shutdown function
+// noopShutdown is a no-op shutdown function.
func noopShutdown(context.Context) error { return nil }
// meterProviderWithCustomRegistry creates a meter provider using contrib config approach
-// but with custom Prometheus registry injection
+// but with custom Prometheus registry injection.
func meterProviderWithCustomRegistry(ctx context.Context, meterProviderConfig *contribsdkconfig.MeterProvider, res *resource.Resource, customRegistry *prometheus.Registry) (metric.MeterProvider, shutdownFunc, error) {
if meterProviderConfig == nil {
return noop.NewMeterProvider(), noopShutdown, nil
@@ -140,7 +140,7 @@ func meterProviderWithCustomRegistry(ctx context.Context, meterProviderConfig *c
return mp, mp.Shutdown, nil
}
-// metricReaderWithCustomRegistry creates metric readers with custom Prometheus registry support
+// metricReaderWithCustomRegistry creates metric readers with custom Prometheus registry support.
func metricReaderWithCustomRegistry(ctx context.Context, r contribsdkconfig.MetricReader, customRegistry *prometheus.Registry) (sdkmetric.Reader, error) {
if r.Periodic != nil && r.Pull != nil {
return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "must not specify multiple metric reader type")
@@ -152,7 +152,7 @@ func metricReaderWithCustomRegistry(ctx context.Context, r contribsdkconfig.Metr
return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "no valid metric reader")
}
-// pullReaderWithCustomRegistry creates pull readers with custom Prometheus registry support
+// pullReaderWithCustomRegistry creates pull readers with custom Prometheus registry support.
func pullReaderWithCustomRegistry(ctx context.Context, exporter contribsdkconfig.MetricExporter, customRegistry *prometheus.Registry) (sdkmetric.Reader, error) {
if exporter.Prometheus != nil {
return prometheusReaderWithCustomRegistry(ctx, exporter.Prometheus, customRegistry)
diff --git a/pkg/modules/apdex/implapdex/module.go b/pkg/modules/apdex/implapdex/module.go
index 3012e4ba36..64378deee3 100644
--- a/pkg/modules/apdex/implapdex/module.go
+++ b/pkg/modules/apdex/implapdex/module.go
@@ -63,7 +63,7 @@ func (module *module) Get(ctx context.Context, orgID string, services []string)
func (module *module) Set(ctx context.Context, orgID string, apdexSettings *apdextypes.Settings) error {
apdexSettings.OrgID = orgID
- apdexSettings.Identifiable.ID = valuer.GenerateUUID()
+ apdexSettings.ID = valuer.GenerateUUID()
_, err := module.
sqlstore.
diff --git a/pkg/modules/dashboard/impldashboard/module.go b/pkg/modules/dashboard/impldashboard/module.go
index e5a68a3a49..22f2ddc129 100644
--- a/pkg/modules/dashboard/impldashboard/module.go
+++ b/pkg/modules/dashboard/impldashboard/module.go
@@ -14,7 +14,6 @@ import (
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
- "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/valuer"
)
@@ -211,7 +210,7 @@ func (module *module) MustGetManagedRoleTransactions() map[string][]*authtypes.T
return nil
}
-// not supported
+// CreatePublic is not supported.
func (module *module) CreatePublic(ctx context.Context, orgID valuer.UUID, publicDashboard *dashboardtypes.PublicDashboard) error {
return errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
}
@@ -224,7 +223,7 @@ func (module *module) GetDashboardByPublicID(_ context.Context, _ valuer.UUID) (
return nil, errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
}
-func (module *module) GetPublicWidgetQueryRange(context.Context, valuer.UUID, uint64, uint64, uint64) (*querybuildertypesv5.QueryRangeResponse, error) {
+func (module *module) GetPublicWidgetQueryRange(context.Context, valuer.UUID, uint64, uint64, uint64) (*qbtypes.QueryRangeResponse, error) {
return nil, errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
}
@@ -240,7 +239,7 @@ func (module *module) DeletePublic(_ context.Context, _ valuer.UUID, _ valuer.UU
return errors.Newf(errors.TypeUnsupported, dashboardtypes.ErrCodePublicDashboardUnsupported, "not implemented")
}
-// checkBuilderQueriesForMetricNames checks builder.queryData[] for aggregations[].metricName
+// checkBuilderQueriesForMetricNames checks builder.queryData[] for aggregations[].metricName.
func (module *module) checkBuilderQueriesForMetricNames(query map[string]interface{}, metricNames []string, foundMetrics map[string]bool) {
builder, ok := query["builder"].(map[string]interface{})
if !ok {
@@ -287,7 +286,7 @@ func (module *module) checkBuilderQueriesForMetricNames(query map[string]interfa
}
}
-// checkClickHouseQueriesForMetricNames checks clickhouse_sql[] array for metric names in query strings
+// checkClickHouseQueriesForMetricNames checks clickhouse_sql[] array for metric names in query strings.
func (module *module) checkClickHouseQueriesForMetricNames(ctx context.Context, query map[string]interface{}, metricNames []string, foundMetrics map[string]bool) {
clickhouseSQL, ok := query["clickhouse_sql"].([]interface{})
if !ok {
@@ -322,7 +321,7 @@ func (module *module) checkClickHouseQueriesForMetricNames(ctx context.Context,
}
}
-// checkPromQLQueriesForMetricNames checks promql[] array for metric names in query strings
+// checkPromQLQueriesForMetricNames checks promql[] array for metric names in query strings.
func (module *module) checkPromQLQueriesForMetricNames(ctx context.Context, query map[string]interface{}, metricNames []string, foundMetrics map[string]bool) {
promQL, ok := query["promql"].([]interface{})
if !ok {
diff --git a/pkg/modules/metricsexplorer/implmetricsexplorer/helpers.go b/pkg/modules/metricsexplorer/implmetricsexplorer/helpers.go
index a889fd4727..9bb46627d1 100644
--- a/pkg/modules/metricsexplorer/implmetricsexplorer/helpers.go
+++ b/pkg/modules/metricsexplorer/implmetricsexplorer/helpers.go
@@ -9,7 +9,7 @@ import (
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
-// used for mapping the sqlColumns via orderBy
+// used for mapping the sqlColumns via orderBy.
const (
sqlColumnTimeSeries = "timeseries"
sqlColumnSamples = "samples"
diff --git a/pkg/modules/metricsexplorer/implmetricsexplorer/module.go b/pkg/modules/metricsexplorer/implmetricsexplorer/module.go
index 47cdfcce74..419e01af6a 100644
--- a/pkg/modules/metricsexplorer/implmetricsexplorer/module.go
+++ b/pkg/modules/metricsexplorer/implmetricsexplorer/module.go
@@ -60,7 +60,7 @@ func NewModule(ts telemetrystore.TelemetryStore, telemetryMetadataStore telemetr
}
}
-// TODO(srikanthccv): use metadata store to fetch metric metadata
+// TODO(srikanthccv): use metadata store to fetch metric metadata.
func (m *module) ListMetrics(ctx context.Context, orgID valuer.UUID, params *metricsexplorertypes.ListMetricsParams) (*metricsexplorertypes.ListMetricsResponse, error) {
ctx = m.withMetricsExplorerContext(ctx, "ListMetrics")
diff --git a/pkg/modules/quickfilter/implquickfilter/module.go b/pkg/modules/quickfilter/implquickfilter/module.go
index b1ebc9117f..092bb01881 100644
--- a/pkg/modules/quickfilter/implquickfilter/module.go
+++ b/pkg/modules/quickfilter/implquickfilter/module.go
@@ -19,7 +19,7 @@ func NewModule(store quickfiltertypes.QuickFilterStore) quickfilter.Module {
return &module{store: store}
}
-// GetQuickFilters returns all quick filters for an organization
+// GetQuickFilters returns all quick filters for an organization.
func (module *module) GetQuickFilters(ctx context.Context, orgID valuer.UUID) ([]*quickfiltertypes.SignalFilters, error) {
storedFilters, err := module.store.Get(ctx, orgID)
if err != nil {
@@ -38,7 +38,7 @@ func (module *module) GetQuickFilters(ctx context.Context, orgID valuer.UUID) ([
return result, nil
}
-// GetSignalFilters returns quick filters for a specific signal in an organization
+// GetSignalFilters returns quick filters for a specific signal in an organization.
func (m *module) GetSignalFilters(ctx context.Context, orgID valuer.UUID, signal quickfiltertypes.Signal) (*quickfiltertypes.SignalFilters, error) {
storedFilter, err := m.store.GetBySignal(ctx, orgID, signal.StringValue())
if err != nil {
@@ -62,7 +62,7 @@ func (m *module) GetSignalFilters(ctx context.Context, orgID valuer.UUID, signal
return signalFilter, nil
}
-// UpdateQuickFilters updates quick filters for a specific signal in an organization
+// UpdateQuickFilters updates quick filters for a specific signal in an organization.
func (module *module) UpdateQuickFilters(ctx context.Context, orgID valuer.UUID, signal quickfiltertypes.Signal, filters []v3.AttributeKey) error {
// Validate each filter
for _, filter := range filters {
diff --git a/pkg/modules/rawdataexport/implrawdataexport/constants.go b/pkg/modules/rawdataexport/implrawdataexport/constants.go
index 7987d73557..d23ac7a2bb 100644
--- a/pkg/modules/rawdataexport/implrawdataexport/constants.go
+++ b/pkg/modules/rawdataexport/implrawdataexport/constants.go
@@ -5,14 +5,14 @@ import (
)
const (
- // Row Limits
+ // Row Limits.
MaxExportRowCountLimit = 50_000 // 50k
DefaultExportRowCountLimit = 10_000 // 10k
- // Data Limits
+ // Data Limits.
MaxExportBytesLimit = 10 * 1024 * 1024 * 1024 // 10 GB
- // Query Limits
+ // Query Limits.
ChunkSize = 5_000 // 5k
ClickhouseExportRawDataMaxThreads = 2
ClickhouseExportRawDataTimeout = 10 * time.Minute
diff --git a/pkg/modules/rawdataexport/implrawdataexport/handler.go b/pkg/modules/rawdataexport/implrawdataexport/handler.go
index 17d45cd4f0..1860a8dfaa 100644
--- a/pkg/modules/rawdataexport/implrawdataexport/handler.go
+++ b/pkg/modules/rawdataexport/implrawdataexport/handler.go
@@ -78,7 +78,7 @@ func (handler *handler) ExportRawData(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("X-Response-Complete", strconv.FormatBool(isComplete))
}
-// validateSpecForExport validates query specs
+// validateSpecForExport validates query specs.
func validateSpecForExport(req *qbtypes.QueryRangeRequest) error {
queries := req.CompositeQuery.Queries
@@ -256,7 +256,7 @@ func constructCSVHeaderFromQueryResponse(data map[string]any) []string {
// sanitizeForCSV sanitizes a string for CSV by prefixing a single quote if the first non-whitespace rune is '=', '+', '-', or '@'.
// Excel and sheets remove these leading single quote when displaying the cell content.
-// TODO: will revisit this in a future PR
+// TODO: will revisit this in a future PR.
func sanitizeForCSV(s string) string {
// Find first non-whitespace rune
i := 0
diff --git a/pkg/modules/services/implservices/module.go b/pkg/modules/services/implservices/module.go
index d9c82b9ae5..4ac7f2b929 100644
--- a/pkg/modules/services/implservices/module.go
+++ b/pkg/modules/services/implservices/module.go
@@ -34,7 +34,7 @@ func NewModule(q querier.Querier, ts telemetrystore.TelemetryStore) services.Mod
}
}
-// FetchTopLevelOperations returns top-level operations per service using db query
+// 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) {
ctx = m.withServicesContext(ctx, "FetchTopLevelOperations")
@@ -107,7 +107,7 @@ func (m *module) Get(ctx context.Context, orgUUID valuer.UUID, req *servicetypes
return items, nil
}
-// GetTopOperations implements services.Module for QBV5 based top ops
+// 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) {
ctx = m.withServicesContext(ctx, "GetTopOperations")
if req == nil {
@@ -128,7 +128,7 @@ func (m *module) GetTopOperations(ctx context.Context, orgUUID valuer.UUID, req
return items, nil
}
-// GetEntryPointOperations implements services.Module for QBV5 based entry point ops
+// 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) {
ctx = m.withServicesContext(ctx, "GetEntryPointOperations")
if req == nil {
@@ -240,7 +240,7 @@ func (m *module) mapQueryRangeRespToServices(resp *qbtypes.QueryRangeResponse, s
for i, c := range sd.Columns {
switch c.Type {
case qbtypes.ColumnTypeGroup:
- if c.TelemetryFieldKey.Name == "service.name" {
+ if c.Name == "service.name" {
serviceNameRespIndex = i
}
case qbtypes.ColumnTypeAggregation:
@@ -388,7 +388,7 @@ func (m *module) mapTopOpsQueryRangeResp(resp *qbtypes.QueryRangeResponse) []ser
for i, c := range sd.Columns {
switch c.Type {
case qbtypes.ColumnTypeGroup:
- if c.TelemetryFieldKey.Name == "name" {
+ if c.Name == "name" {
nameIdx = i
}
case qbtypes.ColumnTypeAggregation:
@@ -502,7 +502,7 @@ func (m *module) mapEntryPointOpsQueryRangeResp(resp *qbtypes.QueryRangeResponse
for i, c := range sd.Columns {
switch c.Type {
case qbtypes.ColumnTypeGroup:
- if c.TelemetryFieldKey.Name == "name" {
+ if c.Name == "name" {
nameIdx = i
}
case qbtypes.ColumnTypeAggregation:
diff --git a/pkg/modules/services/implservices/module_test.go b/pkg/modules/services/implservices/module_test.go
index e5ce9d0ee7..32922a6cd4 100644
--- a/pkg/modules/services/implservices/module_test.go
+++ b/pkg/modules/services/implservices/module_test.go
@@ -53,7 +53,7 @@ func TestBuildQueryRangeRequest(t *testing.T) {
// GroupBy should include service.name
if assert.Equal(t, 1, len(spec.GroupBy)) {
- assert.Equal(t, "service.name", spec.GroupBy[0].TelemetryFieldKey.Name)
+ assert.Equal(t, "service.name", spec.GroupBy[0].Name)
}
// Aggregations should match expected expressions and aliases
@@ -373,8 +373,8 @@ func TestBuildTopOpsQueryRangeRequest(t *testing.T) {
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)
+ assert.Equal(t, "name", spec.GroupBy[0].Name)
+ assert.Equal(t, telemetrytypes.FieldContextSpan, spec.GroupBy[0].FieldContext)
}
if assert.Equal(t, 5, len(spec.Aggregations)) {
assert.Equal(t, "p50(duration_nano)", spec.Aggregations[0].Expression)
@@ -389,7 +389,7 @@ func TestBuildTopOpsQueryRangeRequest(t *testing.T) {
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, "p99", spec.Order[0].Key.Name)
assert.Equal(t, qbtypes.OrderDirectionDesc, spec.Order[0].Direction)
}
assert.Equal(t, 50, spec.Limit)
@@ -576,8 +576,8 @@ func TestBuildEntryPointOpsQueryRangeRequest(t *testing.T) {
}
// 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)
+ assert.Equal(t, "name", spec.GroupBy[0].Name)
+ assert.Equal(t, telemetrytypes.FieldContextSpan, spec.GroupBy[0].FieldContext)
}
}
},
@@ -608,8 +608,8 @@ func TestBuildEntryPointOpsQueryRangeRequest(t *testing.T) {
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)
+ assert.Equal(t, "name", spec.GroupBy[0].Name)
+ assert.Equal(t, telemetrytypes.FieldContextSpan, spec.GroupBy[0].FieldContext)
}
if assert.Equal(t, 5, len(spec.Aggregations)) {
assert.Equal(t, "p50(duration_nano)", spec.Aggregations[0].Expression)
@@ -624,7 +624,7 @@ func TestBuildEntryPointOpsQueryRangeRequest(t *testing.T) {
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, "p99", spec.Order[0].Key.Name)
assert.Equal(t, qbtypes.OrderDirectionDesc, spec.Order[0].Direction)
}
assert.Equal(t, 25, spec.Limit)
diff --git a/pkg/modules/services/services.go b/pkg/modules/services/services.go
index 191c41ad48..4f15d4329c 100644
--- a/pkg/modules/services/services.go
+++ b/pkg/modules/services/services.go
@@ -9,14 +9,14 @@ import (
"github.com/SigNoz/signoz/pkg/valuer"
)
-// Handler exposes HTTP handler for services_qbv5
+// 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
+// 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)
diff --git a/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go b/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go
index 7cb2045bc5..55fda9e1a6 100644
--- a/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go
+++ b/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go
@@ -50,10 +50,10 @@ func TestBuildSpanPercentileQuery(t *testing.T) {
require.Equal(t, "service.name = 'test-service' AND name = 'test'", query.Filter.Expression)
require.Equal(t, 2, len(query.GroupBy))
- require.Equal(t, "service.name", query.GroupBy[0].TelemetryFieldKey.Name)
- require.Equal(t, telemetrytypes.FieldContextResource, query.GroupBy[0].TelemetryFieldKey.FieldContext)
- require.Equal(t, "name", query.GroupBy[1].TelemetryFieldKey.Name)
- require.Equal(t, telemetrytypes.FieldContextSpan, query.GroupBy[1].TelemetryFieldKey.FieldContext)
+ require.Equal(t, "service.name", query.GroupBy[0].Name)
+ require.Equal(t, telemetrytypes.FieldContextResource, query.GroupBy[0].FieldContext)
+ require.Equal(t, "name", query.GroupBy[1].Name)
+ require.Equal(t, telemetrytypes.FieldContextSpan, query.GroupBy[1].FieldContext)
require.Equal(t, qbtypes.RequestTypeScalar, result.RequestType)
}
@@ -128,12 +128,12 @@ func TestBuildSpanPercentileQueryWithResourceAttributes(t *testing.T) {
expectedGroupByCount := 2 + len(tc.request.ResourceAttributes)
require.Equal(t, expectedGroupByCount, len(query.GroupBy))
- require.Equal(t, "service.name", query.GroupBy[0].TelemetryFieldKey.Name)
- require.Equal(t, "name", query.GroupBy[1].TelemetryFieldKey.Name)
+ require.Equal(t, "service.name", query.GroupBy[0].Name)
+ require.Equal(t, "name", query.GroupBy[1].Name)
for i, key := range getSortedKeys(tc.request.ResourceAttributes) {
- require.Equal(t, key, query.GroupBy[2+i].TelemetryFieldKey.Name)
- require.Equal(t, telemetrytypes.FieldContextResource, query.GroupBy[2+i].TelemetryFieldKey.FieldContext)
+ require.Equal(t, key, query.GroupBy[2+i].Name)
+ require.Equal(t, telemetrytypes.FieldContextResource, query.GroupBy[2+i].FieldContext)
}
})
}
diff --git a/pkg/modules/tracefunnel/clickhouse_queries.go b/pkg/modules/tracefunnel/clickhouse_queries.go
index 14c1832868..409210c2df 100644
--- a/pkg/modules/tracefunnel/clickhouse_queries.go
+++ b/pkg/modules/tracefunnel/clickhouse_queries.go
@@ -5,7 +5,7 @@ import (
"strings"
)
-// BuildFunnelValidationQuery builds a validation query for n-step funnels
+// BuildFunnelValidationQuery builds a validation query for n-step funnels.
func BuildFunnelValidationQuery(
steps []struct {
ServiceName string
@@ -73,7 +73,7 @@ LIMIT 5;`
)
}
-// BuildFunnelOverviewQuery builds an overview query for n-step funnels
+// BuildFunnelOverviewQuery builds an overview query for n-step funnels.
func BuildFunnelOverviewQuery(
steps []struct {
ServiceName string
@@ -216,7 +216,7 @@ FROM totals;
)
}
-// BuildFunnelCountQuery builds a count query for n-step funnels
+// BuildFunnelCountQuery builds a count query for n-step funnels.
func BuildFunnelCountQuery(
steps []struct {
ServiceName string
@@ -313,7 +313,7 @@ FROM (
)
}
-// BuildFunnelStepOverviewQuery builds a step overview query for transitions between any specified steps
+// BuildFunnelStepOverviewQuery builds a step overview query for transitions between any specified steps.
func BuildFunnelStepOverviewQuery(
steps []struct {
ServiceName string
@@ -460,7 +460,7 @@ FROM (
)
}
-// BuildFunnelTopSlowTracesQuery builds a query to find the slowest traces between two funnel steps
+// BuildFunnelTopSlowTracesQuery builds a query to find the slowest traces between two funnel steps.
func BuildFunnelTopSlowTracesQuery(
containsErrorT1 int,
containsErrorT2 int,
@@ -536,7 +536,7 @@ LIMIT 5;
)
}
-// BuildFunnelTopSlowErrorTracesQuery builds a query to find the slowest error traces between two funnel steps
+// BuildFunnelTopSlowErrorTracesQuery builds a query to find the slowest error traces between two funnel steps.
func BuildFunnelTopSlowErrorTracesQuery(
containsErrorT1 int,
containsErrorT2 int,
diff --git a/pkg/modules/tracefunnel/impltracefunnel/module.go b/pkg/modules/tracefunnel/impltracefunnel/module.go
index dfb3bd4b6d..18f81ac75f 100644
--- a/pkg/modules/tracefunnel/impltracefunnel/module.go
+++ b/pkg/modules/tracefunnel/impltracefunnel/module.go
@@ -49,7 +49,7 @@ func (module *module) Create(ctx context.Context, timestamp int64, name string,
// Set created_by if CreatedByUser is present
if funnel.CreatedByUser != nil {
- funnel.CreatedBy = funnel.CreatedByUser.Identifiable.ID.String()
+ funnel.CreatedBy = funnel.CreatedByUser.ID.String()
}
err := module.store.Create(ctx, funnel)
@@ -61,18 +61,18 @@ func (module *module) Create(ctx context.Context, timestamp int64, name string,
return funnel, nil
}
-// Get gets a funnel by ID
+// Get gets a funnel by ID.
func (module *module) Get(ctx context.Context, funnelID valuer.UUID, orgID valuer.UUID) (*traceFunnels.StorableFunnel, error) {
return module.store.Get(ctx, funnelID, orgID)
}
-// Update updates a funnel
+// Update updates a funnel.
func (module *module) Update(ctx context.Context, funnel *traceFunnels.StorableFunnel, userID valuer.UUID) error {
funnel.UpdatedBy = userID.String()
return module.store.Update(ctx, funnel)
}
-// List lists all funnels for an organization
+// List lists all funnels for an organization.
func (module *module) List(ctx context.Context, orgID valuer.UUID) ([]*traceFunnels.StorableFunnel, error) {
funnels, err := module.store.List(ctx, orgID)
if err != nil {
@@ -82,12 +82,12 @@ func (module *module) List(ctx context.Context, orgID valuer.UUID) ([]*traceFunn
return funnels, nil
}
-// Delete deletes a funnel
+// Delete deletes a funnel.
func (module *module) Delete(ctx context.Context, funnelID valuer.UUID, orgID valuer.UUID) error {
return module.store.Delete(ctx, funnelID, orgID)
}
-// GetFunnelMetadata gets metadata for a funnel
+// GetFunnelMetadata gets metadata for a funnel.
func (module *module) GetFunnelMetadata(ctx context.Context, funnelID valuer.UUID, orgID valuer.UUID) (int64, int64, string, error) {
funnel, err := module.store.Get(ctx, funnelID, orgID)
if err != nil {
diff --git a/pkg/modules/tracefunnel/impltracefunnel/store.go b/pkg/modules/tracefunnel/impltracefunnel/store.go
index 4d0ec8818a..dfdf07ae97 100644
--- a/pkg/modules/tracefunnel/impltracefunnel/store.go
+++ b/pkg/modules/tracefunnel/impltracefunnel/store.go
@@ -58,7 +58,7 @@ func (store *store) Create(ctx context.Context, funnel *traceFunnels.StorableFun
return nil
}
-// Get retrieves a funnel by ID
+// Get retrieves a funnel by ID.
func (store *store) Get(ctx context.Context, uuid valuer.UUID, orgID valuer.UUID) (*traceFunnels.StorableFunnel, error) {
funnel := &traceFunnels.StorableFunnel{}
err := store.
@@ -75,7 +75,7 @@ func (store *store) Get(ctx context.Context, uuid valuer.UUID, orgID valuer.UUID
return funnel, nil
}
-// Update updates an existing funnel
+// Update updates an existing funnel.
func (store *store) Update(ctx context.Context, funnel *traceFunnels.StorableFunnel) error {
tx, err := store.sqlstore.BunDB().BeginTx(ctx, nil)
if err != nil {
@@ -119,7 +119,7 @@ func (store *store) Update(ctx context.Context, funnel *traceFunnels.StorableFun
return nil
}
-// List retrieves all funnels for a given organization
+// List retrieves all funnels for a given organization.
func (store *store) List(ctx context.Context, orgID valuer.UUID) ([]*traceFunnels.StorableFunnel, error) {
var funnels []*traceFunnels.StorableFunnel
err := store.
@@ -136,7 +136,7 @@ func (store *store) List(ctx context.Context, orgID valuer.UUID) ([]*traceFunnel
return funnels, nil
}
-// Delete removes a funnel by ID
+// Delete removes a funnel by ID.
func (store *store) Delete(ctx context.Context, funnelID valuer.UUID, orgID valuer.UUID) error {
_, err := store.
sqlstore.
diff --git a/pkg/modules/tracefunnel/impltracefunnel/store_duplicate_names_test.go b/pkg/modules/tracefunnel/impltracefunnel/store_duplicate_names_test.go
index fe82a01118..8994ad2854 100644
--- a/pkg/modules/tracefunnel/impltracefunnel/store_duplicate_names_test.go
+++ b/pkg/modules/tracefunnel/impltracefunnel/store_duplicate_names_test.go
@@ -12,7 +12,7 @@ import (
"github.com/stretchr/testify/mock"
)
-// Test that Create method properly validates duplicate names
+// Test that Create method properly validates duplicate names.
func TestModule_Create_DuplicateNameValidation(t *testing.T) {
mockStore := new(MockStore)
module := NewModule(mockStore)
@@ -37,7 +37,7 @@ func TestModule_Create_DuplicateNameValidation(t *testing.T) {
mockStore.AssertExpectations(t)
}
-// Test that Update method properly validates duplicate names
+// Test that Update method properly validates duplicate names.
func TestModule_Update_DuplicateNameValidation(t *testing.T) {
mockStore := new(MockStore)
module := NewModule(mockStore)
@@ -65,7 +65,7 @@ func TestModule_Update_DuplicateNameValidation(t *testing.T) {
mockStore.AssertExpectations(t)
}
-// MockStore for testing
+// MockStore for testing.
type MockStore struct {
mock.Mock
}
diff --git a/pkg/modules/tracefunnel/query.go b/pkg/modules/tracefunnel/query.go
index 3ced1bc205..9ff0a91e5d 100644
--- a/pkg/modules/tracefunnel/query.go
+++ b/pkg/modules/tracefunnel/query.go
@@ -9,7 +9,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/tracefunneltypes"
)
-// sanitizeClause adds AND prefix to non-empty clauses if not already present
+// sanitizeClause adds AND prefix to non-empty clauses if not already present.
func sanitizeClause(clause string) string {
if clause == "" {
return ""
@@ -267,7 +267,7 @@ func GetSlowestTraces(funnel *tracefunneltypes.StorableFunnel, timeRange tracefu
return &v3.ClickHouseQuery{Query: query}, nil
}
-// TODO: Showing traces with error which are slow makes little sense as a product. We should show the error spans directly in the funnel chart. Rather showing traces which has drop between steps will be more relevant
+// TODO: Showing traces with error which are slow makes little sense as a product. We should show the error spans directly in the funnel chart. Rather showing traces which has drop between steps will be more relevant.
func GetErroredTraces(funnel *tracefunneltypes.StorableFunnel, timeRange tracefunneltypes.TimeRange, stepStart, stepEnd int64) (*v3.ClickHouseQuery, error) {
funnelSteps := funnel.Steps
containsErrorT1 := 0
diff --git a/pkg/modules/tracefunnel/query_test.go b/pkg/modules/tracefunnel/query_test.go
index 369b2e46ca..3407efa320 100644
--- a/pkg/modules/tracefunnel/query_test.go
+++ b/pkg/modules/tracefunnel/query_test.go
@@ -263,7 +263,7 @@ func TestGetFunnelStepAnalyticsMultipleSteps(t *testing.T) {
}
}
-// Mock the tracev4.BuildTracesFilterQuery function since it's external
+// Mock the tracev4.BuildTracesFilterQuery function since it's external.
func init() {
// This would normally be handled by the actual implementation
// For testing purposes, we'll assume it returns an empty string
diff --git a/pkg/modules/tracefunnel/tracefunnel.go b/pkg/modules/tracefunnel/tracefunnel.go
index 13401ee5a4..423bf433d0 100644
--- a/pkg/modules/tracefunnel/tracefunnel.go
+++ b/pkg/modules/tracefunnel/tracefunnel.go
@@ -8,7 +8,7 @@ import (
traceFunnels "github.com/SigNoz/signoz/pkg/types/tracefunneltypes"
)
-// Module defines the interface for trace funnel operations
+// Module defines the interface for trace funnel operations.
type Module interface {
Create(ctx context.Context, timestamp int64, name string, userID valuer.UUID, orgID valuer.UUID) (*traceFunnels.StorableFunnel, error)
diff --git a/pkg/modules/user/impluser/getter.go b/pkg/modules/user/impluser/getter.go
index 8bc25e0587..854c4f5ea1 100644
--- a/pkg/modules/user/impluser/getter.go
+++ b/pkg/modules/user/impluser/getter.go
@@ -184,7 +184,7 @@ func (module *getter) GetFactorPasswordByUserID(ctx context.Context, userID valu
return factorPassword, nil
}
-// this function restricts that only one non-deleted user email can exist for an org ID, if found more, it throws an error
+// GetNonDeletedUserByEmailAndOrgID restricts that only one non-deleted user email can exist for an org ID, if found more, it throws an error.
func (module *getter) GetNonDeletedUserByEmailAndOrgID(ctx context.Context, email valuer.Email, orgID valuer.UUID) (*types.User, error) {
existingUsers, err := module.store.GetNonDeletedUsersByEmailAndOrgID(ctx, email, orgID)
if err != nil {
diff --git a/pkg/modules/user/impluser/setter.go b/pkg/modules/user/impluser/setter.go
index cc02cb6359..99bbc836ed 100644
--- a/pkg/modules/user/impluser/setter.go
+++ b/pkg/modules/user/impluser/setter.go
@@ -15,7 +15,6 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/modules/organization"
- "github.com/SigNoz/signoz/pkg/modules/user"
root "github.com/SigNoz/signoz/pkg/modules/user"
"github.com/SigNoz/signoz/pkg/tokenizer"
"github.com/SigNoz/signoz/pkg/types"
@@ -34,12 +33,12 @@ type setter struct {
orgSetter organization.Setter
authz authz.AuthZ
analytics analytics.Analytics
- config user.Config
+ config root.Config
getter root.Getter
}
// This module is a WIP, don't take inspiration from this.
-func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emailing.Emailing, providerSettings factory.ProviderSettings, orgSetter organization.Setter, authz authz.AuthZ, analytics analytics.Analytics, config user.Config, userRoleStore authtypes.UserRoleStore, getter root.Getter) root.Setter {
+func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emailing.Emailing, providerSettings factory.ProviderSettings, orgSetter organization.Setter, authz authz.AuthZ, analytics analytics.Analytics, config root.Config, userRoleStore authtypes.UserRoleStore, getter root.Getter) root.Setter {
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/modules/user/impluser")
return &setter{
store: store,
diff --git a/pkg/modules/user/impluser/store.go b/pkg/modules/user/impluser/store.go
index 38c42fef01..13be48145a 100644
--- a/pkg/modules/user/impluser/store.go
+++ b/pkg/modules/user/impluser/store.go
@@ -421,7 +421,7 @@ func (store *store) UpdatePassword(ctx context.Context, factorPassword *types.Fa
return nil
}
-// --- API KEY ---
+// CreateAPIKey creates a new API key.
func (store *store) CreateAPIKey(ctx context.Context, apiKey *types.StorableAPIKey) error {
_, err := store.sqlstore.BunDB().NewInsert().
Model(apiKey).
diff --git a/pkg/prometheus/clickhouseprometheus/client.go b/pkg/prometheus/clickhouseprometheus/client.go
index ba8ccfccc9..2446505b9a 100644
--- a/pkg/prometheus/clickhouseprometheus/client.go
+++ b/pkg/prometheus/clickhouseprometheus/client.go
@@ -129,8 +129,8 @@ func (c *client) ReadMultiple(ctx context.Context, queries []*prompb.Query, sort
func (client *client) queryToClickhouseQuery(_ context.Context, query *prompb.Query, metricName string, subQuery bool) (string, []any, error) {
var clickHouseQuery string
var conditions []string
- var argCount int = 0
- var selectString string = "fingerprint, any(labels)"
+ var argCount = 0
+ var selectString = "fingerprint, any(labels)"
if subQuery {
argCount = 1
selectString = "fingerprint"
@@ -143,10 +143,7 @@ func (client *client) queryToClickhouseQuery(_ context.Context, query *prompb.Qu
conditions = append(conditions, "temporality IN ['Cumulative', 'Unspecified']")
conditions = append(conditions, fmt.Sprintf("unix_milli >= %d AND unix_milli < %d", start, end))
- normalized := true
- if constants.IsDotMetricsEnabled {
- normalized = false
- }
+ normalized := !constants.IsDotMetricsEnabled
conditions = append(conditions, fmt.Sprintf("__normalized = %v", normalized))
diff --git a/pkg/prometheus/clickhouseprometheus/client_query_test.go b/pkg/prometheus/clickhouseprometheus/client_query_test.go
index 1be32a18f8..332caafb30 100644
--- a/pkg/prometheus/clickhouseprometheus/client_query_test.go
+++ b/pkg/prometheus/clickhouseprometheus/client_query_test.go
@@ -14,7 +14,7 @@ import (
"github.com/stretchr/testify/assert"
)
-// Test for querySamples method
+// Test for querySamples method.
func TestClient_QuerySamples(t *testing.T) {
ctx := context.Background()
cols := make([]cmock.ColumnType, 0)
diff --git a/pkg/querier/api.go b/pkg/querier/api.go
index 4dbc4d4172..a54b6db6bf 100644
--- a/pkg/querier/api.go
+++ b/pkg/querier/api.go
@@ -182,7 +182,7 @@ func (handler *handler) 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
+// For the time being I am adding a helper function.
func (handler *handler) ReplaceVariables(rw http.ResponseWriter, req *http.Request) {
var queryRangeRequest qbtypes.QueryRangeRequest
@@ -241,7 +241,7 @@ func (handler *handler) logEvent(ctx context.Context, referrer string, event *qb
return
}
- if !(event.LogsUsed || event.MetricsUsed || event.TracesUsed) {
+ if !event.LogsUsed && !event.MetricsUsed && !event.TracesUsed {
return
}
diff --git a/pkg/querier/bucket_cache.go b/pkg/querier/bucket_cache.go
index cc20cf2b1c..21fca3aa98 100644
--- a/pkg/querier/bucket_cache.go
+++ b/pkg/querier/bucket_cache.go
@@ -15,7 +15,7 @@ import (
"github.com/SigNoz/signoz/pkg/valuer"
)
-// bucketCache implements the BucketCache interface
+// bucketCache implements the BucketCache interface.
type bucketCache struct {
cache cache.Cache
logger *slog.Logger
@@ -25,7 +25,7 @@ type bucketCache struct {
var _ BucketCache = (*bucketCache)(nil)
-// NewBucketCache creates a new BucketCache implementation
+// NewBucketCache creates a new BucketCache implementation.
func NewBucketCache(settings factory.ProviderSettings, cache cache.Cache, cacheTTL time.Duration, fluxInterval time.Duration) BucketCache {
cacheSettings := factory.NewScopedProviderSettings(settings, "github.com/SigNoz/signoz/pkg/querier/bucket_cache")
return &bucketCache{
@@ -36,7 +36,7 @@ func NewBucketCache(settings factory.ProviderSettings, cache cache.Cache, cacheT
}
}
-// GetMissRanges returns cached data and missing time ranges
+// GetMissRanges returns cached data and missing time ranges.
func (bc *bucketCache) GetMissRanges(
ctx context.Context,
orgID valuer.UUID,
@@ -67,7 +67,7 @@ func (bc *bucketCache) GetMissRanges(
}
// Extract step interval if this is a builder query
- stepMs := uint64(step.Duration.Milliseconds())
+ stepMs := uint64(step.Milliseconds())
// Find missing ranges with step alignment
missing = bc.findMissingRangesWithStep(data.Buckets, startMs, endMs, stepMs)
@@ -93,7 +93,7 @@ func (bc *bucketCache) GetMissRanges(
return mergedResult, missing
}
-// Put stores fresh query results in the cache
+// Put stores fresh query results in the cache.
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result) {
// Get query window
startMs, endMs := q.Window()
@@ -138,7 +138,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
// Adjust start and end times to only cache complete intervals
cachableStartMs := startMs
- stepMs := uint64(step.Duration.Milliseconds())
+ stepMs := uint64(step.Milliseconds())
// If we have a step interval, adjust boundaries to only cache complete intervals
if stepMs > 0 {
@@ -191,14 +191,14 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
}
}
-// generateCacheKey creates a unique cache key based on query fingerprint
+// generateCacheKey creates a unique cache key based on query fingerprint.
func (bc *bucketCache) generateCacheKey(q qbtypes.Query) string {
fingerprint := q.Fingerprint()
return fmt.Sprintf("v5:query:%s", fingerprint)
}
-// findMissingRangesWithStep identifies time ranges not covered by cached buckets with step alignment
+// findMissingRangesWithStep identifies time ranges not covered by cached buckets with step alignment.
func (bc *bucketCache) findMissingRangesWithStep(buckets []*qbtypes.CachedBucket, startMs, endMs uint64, stepMs uint64) []*qbtypes.TimeRange {
// When step is 0 or window is too small to be cached, use simple algorithm
if stepMs == 0 || (startMs+stepMs) > endMs {
@@ -315,7 +315,7 @@ func (bc *bucketCache) findMissingRangesWithStep(buckets []*qbtypes.CachedBucket
return missing
}
-// findMissingRangesBasic is the simple algorithm without step alignment
+// findMissingRangesBasic is the simple algorithm without step alignment.
func (bc *bucketCache) findMissingRangesBasic(buckets []*qbtypes.CachedBucket, startMs, endMs uint64) []*qbtypes.TimeRange {
// Check if already sorted before sorting
needsSort := false
@@ -397,7 +397,7 @@ func (bc *bucketCache) findMissingRangesBasic(buckets []*qbtypes.CachedBucket, s
return missing
}
-// filterRelevantBuckets returns buckets that overlap with the requested time range
+// filterRelevantBuckets returns buckets that overlap with the requested time range.
func (bc *bucketCache) filterRelevantBuckets(buckets []*qbtypes.CachedBucket, startMs, endMs uint64) []*qbtypes.CachedBucket {
// Pre-allocate with estimated capacity
relevant := make([]*qbtypes.CachedBucket, 0, len(buckets))
@@ -423,7 +423,7 @@ func (bc *bucketCache) filterRelevantBuckets(buckets []*qbtypes.CachedBucket, st
return relevant
}
-// mergeBuckets combines multiple cached buckets into a single result
+// mergeBuckets combines multiple cached buckets into a single result.
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string) *qbtypes.Result {
if len(buckets) == 0 {
return &qbtypes.Result{}
@@ -456,7 +456,7 @@ func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.Cach
}
}
-// mergeTimeSeriesValues merges time series data from multiple buckets
+// mergeTimeSeriesValues merges time series data from multiple buckets.
func (bc *bucketCache) mergeTimeSeriesValues(ctx context.Context, buckets []*qbtypes.CachedBucket) *qbtypes.TimeSeriesData {
// Estimate capacity based on bucket count
estimatedSeries := len(buckets) * 10
@@ -557,7 +557,7 @@ func (bc *bucketCache) mergeTimeSeriesValues(ctx context.Context, buckets []*qbt
return result
}
-// isEmptyResult checks if a result is truly empty (no data exists) vs filtered empty (data was filtered out)
+// isEmptyResult checks if a result is truly empty (no data exists) vs filtered empty (data was filtered out).
func (bc *bucketCache) isEmptyResult(result *qbtypes.Result) (isEmpty bool, isFiltered bool) {
if result.Value == nil {
return true, false
@@ -607,7 +607,7 @@ func (bc *bucketCache) isEmptyResult(result *qbtypes.Result) (isEmpty bool, isFi
return true, false
}
-// resultToBuckets converts a query result into time-based buckets
+// resultToBuckets converts a query result into time-based buckets.
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs uint64) []*qbtypes.CachedBucket {
// Check if result is empty
isEmpty, isFiltered := bc.isEmptyResult(result)
@@ -640,7 +640,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
}
}
-// mergeAndDeduplicateBuckets combines and deduplicates bucket lists
+// mergeAndDeduplicateBuckets combines and deduplicates bucket lists.
func (bc *bucketCache) mergeAndDeduplicateBuckets(existing, fresh []*qbtypes.CachedBucket) []*qbtypes.CachedBucket {
// Create a map to deduplicate by time range
bucketMap := make(map[string]*qbtypes.CachedBucket)
@@ -677,7 +677,7 @@ func (bc *bucketCache) mergeAndDeduplicateBuckets(existing, fresh []*qbtypes.Cac
return result
}
-// deduplicateWarnings removes duplicate warnings
+// deduplicateWarnings removes duplicate warnings.
func (bc *bucketCache) deduplicateWarnings(warnings []string) []string {
if len(warnings) == 0 {
return nil
@@ -696,7 +696,7 @@ func (bc *bucketCache) deduplicateWarnings(warnings []string) []string {
return unique
}
-// trimResultToFluxBoundary trims the result to exclude data points beyond the flux boundary
+// trimResultToFluxBoundary trims the result to exclude data points beyond the flux boundary.
func (bc *bucketCache) trimResultToFluxBoundary(result *qbtypes.Result, fluxBoundary uint64) *qbtypes.Result {
trimmedResult := &qbtypes.Result{
Type: result.Type,
@@ -765,7 +765,7 @@ func max(a, b uint64) uint64 {
return b
}
-// filterResultToTimeRange filters the result to only include values within the requested time range
+// filterResultToTimeRange filters the result to only include values within the requested time range.
func (bc *bucketCache) filterResultToTimeRange(result *qbtypes.Result, startMs, endMs uint64) *qbtypes.Result {
if result == nil || result.Value == nil {
return result
diff --git a/pkg/querier/bucket_cache_bench_test.go b/pkg/querier/bucket_cache_bench_test.go
index 27b32e243b..78aebfd5a2 100644
--- a/pkg/querier/bucket_cache_bench_test.go
+++ b/pkg/querier/bucket_cache_bench_test.go
@@ -16,7 +16,7 @@ import (
"github.com/stretchr/testify/require"
)
-// BenchmarkBucketCache_GetMissRanges benchmarks the GetMissRanges operation
+// BenchmarkBucketCache_GetMissRanges benchmarks the GetMissRanges operation.
func BenchmarkBucketCache_GetMissRanges(b *testing.B) {
bc := createBenchmarkBucketCache(b)
ctx := context.Background()
@@ -76,7 +76,7 @@ func BenchmarkBucketCache_GetMissRanges(b *testing.B) {
}
}
-// BenchmarkBucketCache_Put benchmarks the Put operation
+// BenchmarkBucketCache_Put benchmarks the Put operation.
func BenchmarkBucketCache_Put(b *testing.B) {
bc := createBenchmarkBucketCache(b)
ctx := context.Background()
@@ -128,7 +128,7 @@ func BenchmarkBucketCache_Put(b *testing.B) {
}
}
-// BenchmarkBucketCache_MergeTimeSeriesValues benchmarks merging of time series data
+// BenchmarkBucketCache_MergeTimeSeriesValues benchmarks merging of time series data.
func BenchmarkBucketCache_MergeTimeSeriesValues(b *testing.B) {
bc := createBenchmarkBucketCache(b).(*bucketCache)
@@ -174,7 +174,7 @@ func BenchmarkBucketCache_MergeTimeSeriesValues(b *testing.B) {
}
}
-// BenchmarkBucketCache_FindMissingRangesWithStep benchmarks finding missing ranges
+// BenchmarkBucketCache_FindMissingRangesWithStep benchmarks finding missing ranges.
func BenchmarkBucketCache_FindMissingRangesWithStep(b *testing.B) {
bc := createBenchmarkBucketCache(b).(*bucketCache)
@@ -208,7 +208,7 @@ func BenchmarkBucketCache_FindMissingRangesWithStep(b *testing.B) {
}
}
-// BenchmarkGetUniqueSeriesKey benchmarks the series key generation
+// BenchmarkGetUniqueSeriesKey benchmarks the series key generation.
func BenchmarkGetUniqueSeriesKey(b *testing.B) {
testCases := []struct {
name string
@@ -245,7 +245,7 @@ func BenchmarkGetUniqueSeriesKey(b *testing.B) {
}
}
-// BenchmarkBucketCache_ConcurrentOperations benchmarks concurrent cache operations
+// BenchmarkBucketCache_ConcurrentOperations benchmarks concurrent cache operations.
func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
bc := createBenchmarkBucketCache(b)
ctx := context.Background()
@@ -300,7 +300,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
})
}
-// BenchmarkBucketCache_FilterResultToTimeRange benchmarks filtering results to time range
+// BenchmarkBucketCache_FilterResultToTimeRange benchmarks filtering results to time range.
func BenchmarkBucketCache_FilterResultToTimeRange(b *testing.B) {
bc := createBenchmarkBucketCache(b).(*bucketCache)
@@ -334,7 +334,7 @@ func BenchmarkBucketCache_FilterResultToTimeRange(b *testing.B) {
}
}
-// Helper function to create benchmark bucket cache
+// Helper function to create benchmark bucket cache.
func createBenchmarkBucketCache(tb testing.TB) BucketCache {
config := cache.Config{
Provider: "memory",
@@ -348,12 +348,12 @@ func createBenchmarkBucketCache(tb testing.TB) BucketCache {
return NewBucketCache(instrumentationtest.New().ToProviderSettings(), memCache, time.Hour, 5*time.Minute)
}
-// Helper function to create benchmark result
+// Helper function to create benchmark result.
func createBenchmarkResult(startMs, endMs uint64, step uint64) *qbtypes.Result {
return createBenchmarkResultWithSeries(startMs, endMs, step, 10, 100)
}
-// Helper function to create benchmark result with specific series and values
+// Helper function to create benchmark result with specific series and values.
func createBenchmarkResultWithSeries(startMs, endMs uint64, _ uint64, numSeries, numValuesPerSeries int) *qbtypes.Result {
series := make([]*qbtypes.TimeSeries, numSeries)
@@ -416,7 +416,7 @@ func createBenchmarkResultWithSeries(startMs, endMs uint64, _ uint64, numSeries,
}
}
-// Helper function to create buckets with specific gap patterns
+// Helper function to create buckets with specific gap patterns.
func createBucketsWithPattern(numBuckets int, pattern string) []*qbtypes.CachedBucket {
buckets := make([]*qbtypes.CachedBucket, 0, numBuckets)
diff --git a/pkg/querier/bucket_cache_test.go b/pkg/querier/bucket_cache_test.go
index 0b9280397f..c4cd6db9a8 100644
--- a/pkg/querier/bucket_cache_test.go
+++ b/pkg/querier/bucket_cache_test.go
@@ -21,7 +21,7 @@ const (
defaultFluxInterval = 5 * time.Minute
)
-// Helper function to create test cache
+// Helper function to create test cache.
func createTestCache(t *testing.T) cache.Cache {
config := cache.Config{
Provider: "memory",
@@ -35,7 +35,7 @@ func createTestCache(t *testing.T) cache.Cache {
return memCache
}
-// mockQuery implements the Query interface for testing
+// mockQuery implements the Query interface for testing.
type mockQuery struct {
fingerprint string
startMs uint64
@@ -67,7 +67,7 @@ func (m *mockQuery) Execute(ctx context.Context) (*qbtypes.Result, error) {
}, nil
}
-// createTestBucketCache creates a test bucket cache
+// createTestBucketCache creates a test bucket cache.
func createTestBucketCache(t *testing.T) *bucketCache {
memCache := createTestCache(t)
return NewBucketCache(instrumentationtest.New().ToProviderSettings(), memCache, cacheTTL, defaultFluxInterval).(*bucketCache)
diff --git a/pkg/querier/builder_query.go b/pkg/querier/builder_query.go
index be49bd9ccf..f8fb59bed0 100644
--- a/pkg/querier/builder_query.go
+++ b/pkg/querier/builder_query.go
@@ -215,7 +215,7 @@ func (q *builderQuery[T]) Execute(ctx context.Context) (*qbtypes.Result, error)
return result, nil
}
-// executeWithContext executes the query with query window and step context for partial value detection
+// executeWithContext executes the query with query window and step context for partial value detection.
func (q *builderQuery[T]) executeWithContext(ctx context.Context, query string, args []any) (*qbtypes.Result, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: q.spec.Signal.StringValue(),
diff --git a/pkg/querier/clickhouse_query.go b/pkg/querier/clickhouse_query.go
index f87613bcd8..bbce735120 100644
--- a/pkg/querier/clickhouse_query.go
+++ b/pkg/querier/clickhouse_query.go
@@ -61,7 +61,7 @@ func (q *chSQLQuery) Fingerprint() string {
func (q *chSQLQuery) Window() (uint64, uint64) { return q.fromMS, q.toMS }
-// TODO(srikanthccv): cleanup the templating logic
+// TODO(srikanthccv): cleanup the templating logic.
func (q *chSQLQuery) renderVars(query string, vars map[string]qbtypes.VariableItem, start, end uint64) (string, error) {
varsData := map[string]any{}
for k, v := range vars {
@@ -79,9 +79,9 @@ func (q *chSQLQuery) renderVars(query string, vars map[string]qbtypes.VariableIt
})
for _, k := range keys {
- query = strings.Replace(query, fmt.Sprintf("{{%s}}", k), fmt.Sprint(varsData[k]), -1)
- query = strings.Replace(query, fmt.Sprintf("[[%s]]", k), fmt.Sprint(varsData[k]), -1)
- query = strings.Replace(query, fmt.Sprintf("$%s", k), fmt.Sprint(varsData[k]), -1)
+ query = strings.ReplaceAll(query, fmt.Sprintf("{{%s}}", k), fmt.Sprint(varsData[k]))
+ query = strings.ReplaceAll(query, fmt.Sprintf("[[%s]]", k), fmt.Sprint(varsData[k]))
+ query = strings.ReplaceAll(query, fmt.Sprintf("$%s", k), fmt.Sprint(varsData[k]))
}
tmpl := template.New("clickhouse-query")
diff --git a/pkg/querier/config.go b/pkg/querier/config.go
index caeaffc39b..ab9fc9dd5d 100644
--- a/pkg/querier/config.go
+++ b/pkg/querier/config.go
@@ -7,7 +7,7 @@ import (
"github.com/SigNoz/signoz/pkg/factory"
)
-// Config represents the configuration for the querier
+// Config represents the configuration for the querier.
type Config struct {
// CacheTTL is the TTL for cached query results
CacheTTL time.Duration `yaml:"cache_ttl" mapstructure:"cache_ttl"`
@@ -17,7 +17,7 @@ type Config struct {
MaxConcurrentQueries int `yaml:"max_concurrent_queries" mapstructure:"max_concurrent_queries"`
}
-// NewConfigFactory creates a new config factory for querier
+// NewConfigFactory creates a new config factory for querier.
func NewConfigFactory() factory.ConfigFactory {
return factory.NewConfigFactory(factory.MustNewName("querier"), newConfig)
}
@@ -31,7 +31,7 @@ func newConfig() factory.Config {
}
}
-// Validate validates the configuration
+// Validate validates the configuration.
func (c Config) Validate() error {
if c.CacheTTL <= 0 {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "cache_ttl must be positive, got %v", c.CacheTTL)
diff --git a/pkg/querier/consume.go b/pkg/querier/consume.go
index 72ce085657..beeae9a65d 100644
--- a/pkg/querier/consume.go
+++ b/pkg/querier/consume.go
@@ -20,7 +20,7 @@ var (
aggRe = regexp.MustCompile(`^__result_(\d+)$`)
// legacyReservedColumnTargetAliases identifies result value from a user
// written clickhouse query. The column alias indcate which value is
- // to be considered as final result (or target)
+ // to be considered as final result (or target).
legacyReservedColumnTargetAliases = []string{"__result", "__value", "result", "res", "value"}
)
@@ -30,7 +30,7 @@ var (
// * Time-series - *qbtypes.TimeSeriesData
// * Scalar - *qbtypes.ScalarData
// * Raw - *qbtypes.RawData
-// * Distribution- *qbtypes.DistributionData
+// * Distribution- *qbtypes.DistributionData.
func consume(rows driver.Rows, kind qbtypes.RequestType, queryWindow *qbtypes.TimeRange, step qbtypes.Step, queryName string) (any, error) {
var (
payload any
@@ -69,7 +69,7 @@ func readAsTimeSeries(rows driver.Rows, queryWindow *qbtypes.TimeRange, step qbt
}
seriesMap := map[sKey]*qbtypes.TimeSeries{}
- stepMs := uint64(step.Duration.Milliseconds())
+ stepMs := uint64(step.Milliseconds())
// Helper function to check if a timestamp represents a partial value
isPartialValue := func(timestamp int64) bool {
@@ -431,7 +431,7 @@ func readAsRaw(rows driver.Rows, queryName string) (*qbtypes.RawData, error) {
}, nil
}
-// numericAsFloat converts numeric types to float64 efficiently
+// numericAsFloat converts numeric types to float64 efficiently.
func numericAsFloat(v any) float64 {
switch x := v.(type) {
case float64:
diff --git a/pkg/querier/format.go b/pkg/querier/format.go
index 0290ad6f77..8350f1e694 100644
--- a/pkg/querier/format.go
+++ b/pkg/querier/format.go
@@ -10,7 +10,7 @@ func toStrArrayString(strs ...string) string {
return fmt.Sprintf("[%s]", strings.Join(strs, ","))
}
-// formatValue formats the value to be used in clickhouse query
+// formatValue formats the value to be used in clickhouse query.
func formatValueForCH(v any) string {
// if it's pointer convert it to a value
v = getPointerValue(v)
@@ -149,7 +149,7 @@ func quoteEscapedString(str string) string {
return str
}
-// formatValueForProm formats the value to be used in promql
+// formatValueForProm formats the value to be used in promql.
func formatValueForProm(v any) string {
switch x := v.(type) {
case int:
diff --git a/pkg/querier/interfaces.go b/pkg/querier/interfaces.go
index ce64f1e2fe..11557556e2 100644
--- a/pkg/querier/interfaces.go
+++ b/pkg/querier/interfaces.go
@@ -8,13 +8,13 @@ import (
"github.com/SigNoz/signoz/pkg/valuer"
)
-// Querier interface defines the contract for querying data
+// Querier interface defines the contract for querying data.
type Querier interface {
QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest) (*qbtypes.QueryRangeResponse, error)
QueryRawStream(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest, client *qbtypes.RawStream)
}
-// BucketCache is the interface for bucket-based caching
+// BucketCache is the interface for bucket-based caching.
type BucketCache interface {
// cached portion + list of gaps to fetch
GetMissRanges(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step) (cached *qbtypes.Result, missing []*qbtypes.TimeRange)
diff --git a/pkg/querier/list_range.go b/pkg/querier/list_range.go
index b62f932ba0..48a129327f 100644
--- a/pkg/querier/list_range.go
+++ b/pkg/querier/list_range.go
@@ -6,7 +6,7 @@ const hourNanos = int64(3_600_000_000_000) // 1 h in ns
type tsRange struct{ fromNS, toNS uint64 }
-// slice the timerange into exponentially growing buckets
+// slice the timerange into exponentially growing buckets.
func makeBuckets(start, end uint64) []tsRange {
startNS := querybuilder.ToNanoSecs(start)
endNS := querybuilder.ToNanoSecs(end)
diff --git a/pkg/querier/pools.go b/pkg/querier/pools.go
index 6bfc5217e4..34b77ce343 100644
--- a/pkg/querier/pools.go
+++ b/pkg/querier/pools.go
@@ -6,9 +6,9 @@ import (
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
-// Pools for reducing allocations in hot paths
+// Pools for reducing allocations in hot paths.
var (
- // Pool for label slices
+ // Pool for label slices.
labelSlicePool = sync.Pool{
New: func() any {
s := make([]*qbtypes.Label, 0, 16)
@@ -16,7 +16,7 @@ var (
},
}
- // Pool for string slices used in label processing
+ // Pool for string slices used in label processing.
stringSlicePool = sync.Pool{
New: func() any {
s := make([]string, 0, 16)
@@ -24,7 +24,7 @@ var (
},
}
- // Pool for time series value slices
+ // Pool for time series value slices.
valueSlicePool = sync.Pool{
New: func() any {
s := make([]*qbtypes.TimeSeriesValue, 0, 100)
@@ -32,7 +32,7 @@ var (
},
}
- // Pool for aggregation value maps
+ // Pool for aggregation value maps.
aggValueMapPool = sync.Pool{
New: func() any {
m := make(map[int]float64, 4)
@@ -41,43 +41,43 @@ var (
}
)
-// GetLabelSlice gets a label slice from the pool
+// GetLabelSlice gets a label slice from the pool.
func GetLabelSlice() []*qbtypes.Label {
sp := labelSlicePool.Get().(*[]*qbtypes.Label)
return *sp
}
-// PutLabelSlice returns a label slice to the pool
+// PutLabelSlice returns a label slice to the pool.
func PutLabelSlice(s []*qbtypes.Label) {
s = s[:0] // Reset slice
labelSlicePool.Put(&s)
}
-// GetStringSlice gets a string slice from the pool
+// GetStringSlice gets a string slice from the pool.
func GetStringSlice() []string {
sp := stringSlicePool.Get().(*[]string)
return *sp
}
-// PutStringSlice returns a string slice to the pool
+// PutStringSlice returns a string slice to the pool.
func PutStringSlice(s []string) {
s = s[:0] // Reset slice
stringSlicePool.Put(&s)
}
-// GetValueSlice gets a time series value slice from the pool
+// GetValueSlice gets a time series value slice from the pool.
func GetValueSlice() []*qbtypes.TimeSeriesValue {
sp := valueSlicePool.Get().(*[]*qbtypes.TimeSeriesValue)
return *sp
}
-// PutValueSlice returns a time series value slice to the pool
+// PutValueSlice returns a time series value slice to the pool.
func PutValueSlice(s []*qbtypes.TimeSeriesValue) {
s = s[:0] // Reset slice
valueSlicePool.Put(&s)
}
-// GetAggValueMap gets an aggregation value map from the pool
+// GetAggValueMap gets an aggregation value map from the pool.
func GetAggValueMap() map[int]float64 {
mp := aggValueMapPool.Get().(*map[int]float64)
m := *mp
@@ -88,7 +88,7 @@ func GetAggValueMap() map[int]float64 {
return m
}
-// PutAggValueMap returns an aggregation value map to the pool
+// PutAggValueMap returns an aggregation value map to the pool.
func PutAggValueMap(m map[int]float64) {
// Clear before returning to pool
for k := range m {
diff --git a/pkg/querier/postprocess.go b/pkg/querier/postprocess.go
index 9b2dc48158..5271f2c084 100644
--- a/pkg/querier/postprocess.go
+++ b/pkg/querier/postprocess.go
@@ -16,14 +16,14 @@ import (
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
-// queryInfo holds common query properties
+// queryInfo holds common query properties.
type queryInfo struct {
Name string
Disabled bool
Step qbtypes.Step
}
-// getqueryInfo extracts common info from any query type
+// getqueryInfo extracts common info from any query type.
func getqueryInfo(spec any) queryInfo {
switch s := spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:
@@ -44,7 +44,7 @@ func getqueryInfo(spec any) queryInfo {
return queryInfo{}
}
-// getQueryName is a convenience function when only name is needed
+// getQueryName is a convenience function when only name is needed.
func getQueryName(spec any) string {
return getqueryInfo(spec).Name
}
@@ -161,7 +161,7 @@ func (q *querier) postProcessResults(ctx context.Context, results map[string]any
return finalResults, nil
}
-// postProcessBuilderQuery applies postprocessing to a single builder query result
+// postProcessBuilderQuery applies postprocessing to a single builder query result.
func postProcessBuilderQuery[T any](
q *querier,
result *qbtypes.Result,
@@ -173,7 +173,7 @@ func postProcessBuilderQuery[T any](
// Apply functions
if len(query.Functions) > 0 {
- step := query.StepInterval.Duration.Milliseconds()
+ step := query.StepInterval.Milliseconds()
functions := q.prepareFillZeroArgsWithStep(query.Functions, req, step)
result = q.applyFunctions(result, functions)
}
@@ -181,7 +181,7 @@ func postProcessBuilderQuery[T any](
return result
}
-// postProcessMetricQuery applies postprocessing to a metric query result
+// postProcessMetricQuery applies postprocessing to a metric query result.
func postProcessMetricQuery(
q *querier,
result *qbtypes.Result,
@@ -205,7 +205,7 @@ func postProcessMetricQuery(
result = q.applySeriesLimit(result, query.Limit, query.Order)
if len(query.Functions) > 0 {
- step := query.StepInterval.Duration.Milliseconds()
+ step := query.StepInterval.Milliseconds()
functions := q.prepareFillZeroArgsWithStep(query.Functions, req, step)
result = q.applyFunctions(result, functions)
}
@@ -220,7 +220,7 @@ func postProcessMetricQuery(
return result
}
-// postProcessTraceOperator applies postprocessing to a trace operator query result
+// postProcessTraceOperator applies postprocessing to a trace operator query result.
func postProcessTraceOperator(
q *querier,
result *qbtypes.Result,
@@ -232,7 +232,7 @@ func postProcessTraceOperator(
// Apply functions if any
if len(query.Functions) > 0 {
- step := query.StepInterval.Duration.Milliseconds()
+ step := query.StepInterval.Milliseconds()
functions := q.prepareFillZeroArgsWithStep(query.Functions, req, step)
result = q.applyFunctions(result, functions)
}
@@ -240,7 +240,7 @@ func postProcessTraceOperator(
return result
}
-// applyMetricReduceTo applies reduce to operation using the metric's ReduceTo field
+// applyMetricReduceTo applies reduce to operation using the metric's ReduceTo field.
func (q *querier) applyMetricReduceTo(result *qbtypes.Result, reduceOp qbtypes.ReduceTo) *qbtypes.Result {
tsData, ok := result.Value.(*qbtypes.TimeSeriesData)
if !ok {
@@ -263,7 +263,7 @@ func (q *querier) applyMetricReduceTo(result *qbtypes.Result, reduceOp qbtypes.R
return result
}
-// applySeriesLimit limits the number of series in the result
+// applySeriesLimit limits the number of series in the result.
func (q *querier) applySeriesLimit(result *qbtypes.Result, limit int, orderBy []qbtypes.OrderBy) *qbtypes.Result {
tsData, ok := result.Value.(*qbtypes.TimeSeriesData)
if !ok {
@@ -280,7 +280,7 @@ func (q *querier) applySeriesLimit(result *qbtypes.Result, limit int, orderBy []
return result
}
-// applyFunctions applies functions to time series data
+// applyFunctions applies functions to time series data.
func (q *querier) applyFunctions(result *qbtypes.Result, functions []qbtypes.Function) *qbtypes.Result {
tsData, ok := result.Value.(*qbtypes.TimeSeriesData)
if !ok {
@@ -298,7 +298,7 @@ func (q *querier) applyFunctions(result *qbtypes.Result, functions []qbtypes.Fun
return result
}
-// applyFormulas processes formula queries in the composite query
+// applyFormulas processes formula queries in the composite query.
func (q *querier) applyFormulas(ctx context.Context, results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]*qbtypes.Result {
// Collect formula queries
formulaQueries := make(map[string]qbtypes.QueryBuilderFormula)
@@ -340,7 +340,7 @@ func (q *querier) applyFormulas(ctx context.Context, results map[string]*qbtypes
return results
}
-// processTimeSeriesFormula handles formula evaluation for time series data
+// processTimeSeriesFormula handles formula evaluation for time series data.
func (q *querier) processTimeSeriesFormula(
ctx context.Context,
results map[string]*qbtypes.Result,
@@ -568,7 +568,7 @@ func (q *querier) processScalarFormula(
}
}
-// filterDisabledQueries removes results for disabled queries
+// filterDisabledQueries removes results for disabled queries.
func (q *querier) filterDisabledQueries(results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]*qbtypes.Result {
filtered := make(map[string]*qbtypes.Result)
@@ -584,7 +584,7 @@ func (q *querier) filterDisabledQueries(results map[string]*qbtypes.Result, req
return filtered
}
-// formatScalarResultsAsTable formats scalar results as a unified table for UI display
+// formatScalarResultsAsTable formats scalar results as a unified table for UI display.
func (q *querier) formatScalarResultsAsTable(results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]any {
if len(results) == 0 {
return map[string]any{"table": &qbtypes.ScalarData{}}
@@ -617,7 +617,7 @@ func (q *querier) formatScalarResultsAsTable(results map[string]*qbtypes.Result,
return map[string]any{"table": merged}
}
-// convertTimeSeriesDataToScalar converts time series to scalar format
+// convertTimeSeriesDataToScalar converts time series to scalar format.
func convertTimeSeriesDataToScalar(tsData *qbtypes.TimeSeriesData, queryName string) *qbtypes.ScalarData {
if tsData == nil || len(tsData.Aggregations) == 0 {
return &qbtypes.ScalarData{QueryName: queryName}
@@ -682,7 +682,7 @@ func convertTimeSeriesDataToScalar(tsData *qbtypes.TimeSeriesData, queryName str
}
}
-// hasMultipleQueries checks if ScalarData contains columns from multiple queries
+// hasMultipleQueries checks if ScalarData contains columns from multiple queries.
func hasMultipleQueries(sd *qbtypes.ScalarData) bool {
queries := make(map[string]bool)
for _, col := range sd.Columns {
@@ -693,7 +693,7 @@ func hasMultipleQueries(sd *qbtypes.ScalarData) bool {
return len(queries) > 1
}
-// deduplicateRows removes duplicate rows based on group columns
+// deduplicateRows removes duplicate rows based on group columns.
func deduplicateRows(sd *qbtypes.ScalarData, applyDefaultSort bool) *qbtypes.ScalarData {
// Find group column indices
groupIndices := []int{}
@@ -740,7 +740,7 @@ func deduplicateRows(sd *qbtypes.ScalarData, applyDefaultSort bool) *qbtypes.Sca
}
}
-// mergeScalarData merges multiple scalar data results
+// mergeScalarData merges multiple scalar data results.
func mergeScalarData(results map[string]*qbtypes.ScalarData, applyDefaultSort bool) *qbtypes.ScalarData {
// Collect unique group columns
groupCols := []string{}
@@ -856,7 +856,7 @@ func mergeScalarData(results map[string]*qbtypes.ScalarData, applyDefaultSort bo
}
}
-// buildRowKey builds a unique key from row values at specified indices
+// buildRowKey builds a unique key from row values at specified indices.
func buildRowKey(row []any, indices []int) string {
parts := make([]string, len(indices))
for i, idx := range indices {
@@ -869,7 +869,7 @@ func buildRowKey(row []any, indices []int) string {
return fmt.Sprintf("%v", parts)
}
-// buildKeyFromGroupCols builds a key from group column values
+// buildKeyFromGroupCols builds a key from group column values.
func buildKeyFromGroupCols(row []any, groupMap map[string]int, groupCols []string) string {
parts := make([]string, len(groupCols))
for i, colName := range groupCols {
@@ -882,7 +882,7 @@ func buildKeyFromGroupCols(row []any, groupMap map[string]int, groupCols []strin
return fmt.Sprintf("%v", parts)
}
-// sortByFirstAggregation sorts data by the first aggregation column (descending)
+// sortByFirstAggregation sorts data by the first aggregation column (descending).
func sortByFirstAggregation(data [][]any, columns []*qbtypes.ColumnDescriptor) {
// Find first aggregation column
aggIdx := -1
@@ -902,7 +902,7 @@ func sortByFirstAggregation(data [][]any, columns []*qbtypes.ColumnDescriptor) {
})
}
-// compareValues compares two values for sorting (handles n/a and numeric types)
+// compareValues compares two values for sorting (handles n/a and numeric types).
func compareValues(a, b any) int {
// n/a values gets pushed to the end
if a == "n/a" && b == "n/a" {
@@ -932,7 +932,7 @@ func compareValues(a, b any) int {
return 0
}
-// toFloat64 attempts to convert a value to float64
+// toFloat64 attempts to convert a value to float64.
func toFloat64(v any) (float64, bool) {
val := numericAsFloat(getPointerValue(v))
if math.IsNaN(val) {
@@ -948,7 +948,7 @@ func gcd(a, b int64) int64 {
return gcd(b, a%b)
}
-// prepareFillZeroArgsWithStep prepares fillZero function arguments with a specific step
+// prepareFillZeroArgsWithStep prepares fillZero function arguments with a specific step.
func (q *querier) prepareFillZeroArgsWithStep(functions []qbtypes.Function, req *qbtypes.QueryRangeRequest, step int64) []qbtypes.Function {
needsCopy := false
for _, fn := range functions {
@@ -979,7 +979,7 @@ func (q *querier) prepareFillZeroArgsWithStep(functions []qbtypes.Function, req
return updatedFunctions
}
-// calculateFormulaStep calculates the GCD of steps from queries referenced in the formula
+// calculateFormulaStep calculates the GCD of steps from queries referenced in the formula.
func (q *querier) calculateFormulaStep(expression string, req *qbtypes.QueryRangeRequest) int64 {
parsedExpr, err := govaluate.NewEvaluableExpression(expression)
if err != nil {
@@ -1003,7 +1003,7 @@ func (q *querier) calculateFormulaStep(expression string, req *qbtypes.QueryRang
for _, query := range req.CompositeQuery.Queries {
info := getqueryInfo(query.Spec)
if queryNames[info.Name] && info.Step.Duration > 0 {
- stepMs := info.Step.Duration.Milliseconds()
+ stepMs := info.Step.Milliseconds()
if stepMs > 0 {
steps = append(steps, stepMs)
}
diff --git a/pkg/querier/promql_query.go b/pkg/querier/promql_query.go
index 3b072d55f5..b8df2c152c 100644
--- a/pkg/querier/promql_query.go
+++ b/pkg/querier/promql_query.go
@@ -27,7 +27,7 @@ import (
// unquotedDottedNamePattern matches unquoted identifiers containing dots
// that appear in metric or label name positions. This helps detect queries
// using the old syntax that needs migration to UTF-8 quoted syntax.
-// Examples it matches: k8s.pod.name, deployment.environment, http.status_code
+// Examples it matches: k8s.pod.name, deployment.environment, http.status_code.
var unquotedDottedNamePattern = regexp.MustCompile(`(?:^|[{,(\s])([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)+)(?:[}\s,=!~)\[]|$)`)
// quotedMetricOutsideBracesPattern matches the incorrect syntax where a quoted
@@ -121,7 +121,7 @@ func (q *promqlQuery) Fingerprint() string {
parts := []string{
"promql",
query,
- q.query.Step.Duration.String(),
+ q.query.Step.String(),
}
return strings.Join(parts, "&")
@@ -166,7 +166,7 @@ func (q *promqlQuery) removeAllVarMatchers(query string, vars map[string]qbv5.Va
return expr.String(), nil
}
-// TODO(srikanthccv): cleanup the templating logic
+// TODO(srikanthccv): cleanup the templating logic.
func (q *promqlQuery) renderVars(query string, vars map[string]qbv5.VariableItem, start, end uint64) (string, error) {
// First, remove label matchers that use variables with __all__ value.
// This must happen before variable substitution so we can detect variable references
@@ -191,9 +191,9 @@ func (q *promqlQuery) renderVars(query string, vars map[string]qbv5.VariableItem
})
for _, k := range keys {
- query = strings.Replace(query, fmt.Sprintf("{{%s}}", k), fmt.Sprint(varsData[k]), -1)
- query = strings.Replace(query, fmt.Sprintf("[[%s]]", k), fmt.Sprint(varsData[k]), -1)
- query = strings.Replace(query, fmt.Sprintf("$%s", k), fmt.Sprint(varsData[k]), -1)
+ query = strings.ReplaceAll(query, fmt.Sprintf("{{%s}}", k), fmt.Sprint(varsData[k]))
+ query = strings.ReplaceAll(query, fmt.Sprintf("[[%s]]", k), fmt.Sprint(varsData[k]))
+ query = strings.ReplaceAll(query, fmt.Sprintf("$%s", k), fmt.Sprint(varsData[k]))
}
tmpl := template.New("promql-query")
diff --git a/pkg/querier/querier.go b/pkg/querier/querier.go
index 0b22821c32..b51057810b 100644
--- a/pkg/querier/querier.go
+++ b/pkg/querier/querier.go
@@ -43,7 +43,7 @@ type querier struct {
meterStmtBuilder qbtypes.StatementBuilder[qbtypes.MetricAggregation]
traceOperatorStmtBuilder qbtypes.TraceOperatorStatementBuilder
bucketCache BucketCache
- liveDataRefreshSeconds time.Duration
+ liveDataRefresh time.Duration
}
var _ Querier = (*querier)(nil)
@@ -72,11 +72,11 @@ func New(
meterStmtBuilder: meterStmtBuilder,
traceOperatorStmtBuilder: traceOperatorStmtBuilder,
bucketCache: bucketCache,
- liveDataRefreshSeconds: 5,
+ liveDataRefresh: 5 * time.Second,
}
}
-// extractShiftFromBuilderQuery extracts the shift value from timeShift function if present
+// extractShiftFromBuilderQuery extracts the shift value from timeShift function if present.
func extractShiftFromBuilderQuery[T any](spec qbtypes.QueryBuilderQuery[T]) int64 {
for _, fn := range spec.Functions {
if fn.Name == qbtypes.FunctionNameTimeShift && len(fn.Args) > 0 {
@@ -97,7 +97,7 @@ func extractShiftFromBuilderQuery[T any](spec qbtypes.QueryBuilderQuery[T]) int6
return 0
}
-// adjustTimeRangeForShift adjusts the time range based on the shift value from timeShift function
+// adjustTimeRangeForShift adjusts the time range based on the shift value from timeShift function.
func adjustTimeRangeForShift[T any](spec qbtypes.QueryBuilderQuery[T], tr qbtypes.TimeRange, kind qbtypes.RequestType) qbtypes.TimeRange {
// Only apply time shift for time series and scalar queries
// Raw/list queries don't support timeshift
@@ -186,7 +186,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepInterval(req.Start, req.End)),
}
- intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Duration.Seconds()))
+ intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
req.CompositeQuery.Queries[idx].Spec = spec
@@ -203,7 +203,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepInterval(req.Start, req.End)),
}
- intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Duration.Seconds()))
+ intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
req.CompositeQuery.Queries[idx].Spec = spec
@@ -233,7 +233,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepIntervalForMetric(req.Start, req.End)),
}
- intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Duration.Seconds()))
+ intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
}
@@ -271,7 +271,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepInterval(req.Start, req.End)),
}
- intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Duration.Seconds()))
+ intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
req.CompositeQuery.Queries[idx].Spec = spec
@@ -488,7 +488,7 @@ func (q *querier) QueryRawStream(ctx context.Context, orgID valuer.UUID, req *qb
}
updatedLogID := ""
- ticker := time.NewTicker(time.Duration(q.liveDataRefreshSeconds) * time.Second)
+ ticker := time.NewTicker(q.liveDataRefresh)
defer ticker.Stop()
// we are creating a custom ticker wrapper to trigger it instantly
@@ -639,7 +639,7 @@ func (q *querier) run(
// or go to related logs/traces from a point in line/bar chart with correct time range
stepIntervals := make(map[string]uint64, len(steps))
for name, step := range steps {
- stepIntervals[name] = uint64(step.Duration.Seconds())
+ stepIntervals[name] = uint64(step.Seconds())
}
for _, query := range req.CompositeQuery.Queries {
if query.Type == qbtypes.QueryTypeFormula {
@@ -680,7 +680,7 @@ func (q *querier) run(
return resp, nil
}
-// executeWithCache executes a query using the bucket cache
+// executeWithCache executes a query using the bucket cache.
func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query qbtypes.Query, step qbtypes.Step, _ bool) (*qbtypes.Result, error) {
// Get cached data and missing ranges
cachedResult, missingRanges := q.bucketCache.GetMissRanges(ctx, orgID, query, step)
@@ -783,7 +783,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
return mergedResult, nil
}
-// createRangedQuery creates a copy of the query with a different time range
+// createRangedQuery creates a copy of the query with a different time range.
func (q *querier) createRangedQuery(originalQuery qbtypes.Query, timeRange qbtypes.TimeRange) qbtypes.Query {
// this is called in a goroutine, so we create a copy of the query to avoid race conditions
switch qt := originalQuery.(type) {
@@ -833,7 +833,7 @@ func (q *querier) createRangedQuery(originalQuery qbtypes.Query, timeRange qbtyp
}
}
-// mergeResults merges cached result with fresh results
+// mergeResults merges cached result with fresh results.
func (q *querier) mergeResults(cached *qbtypes.Result, fresh []*qbtypes.Result) *qbtypes.Result {
if cached == nil {
if len(fresh) == 1 {
@@ -897,7 +897,7 @@ func (q *querier) mergeResults(cached *qbtypes.Result, fresh []*qbtypes.Result)
return merged
}
-// mergeTimeSeriesResults merges time series data
+// mergeTimeSeriesResults merges time series data.
func (q *querier) mergeTimeSeriesResults(cachedValue *qbtypes.TimeSeriesData, freshResults []*qbtypes.Result) *qbtypes.TimeSeriesData {
// Map to store merged series by aggregation index and series key
diff --git a/pkg/querier/shift_test.go b/pkg/querier/shift_test.go
index 24d200da9b..6e262dc368 100644
--- a/pkg/querier/shift_test.go
+++ b/pkg/querier/shift_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
)
-// TestAdjustTimeRangeForShift tests the time range adjustment logic
+// TestAdjustTimeRangeForShift tests the time range adjustment logic.
func TestAdjustTimeRangeForShift(t *testing.T) {
tests := []struct {
name string
@@ -121,7 +121,7 @@ func TestAdjustTimeRangeForShift(t *testing.T) {
}
}
-// TestExtractShiftFromBuilderQuery tests the shift extraction logic
+// TestExtractShiftFromBuilderQuery tests the shift extraction logic.
func TestExtractShiftFromBuilderQuery(t *testing.T) {
tests := []struct {
name string
diff --git a/pkg/querier/signozquerier/provider.go b/pkg/querier/signozquerier/provider.go
index e301c5fe02..940d2040a5 100644
--- a/pkg/querier/signozquerier/provider.go
+++ b/pkg/querier/signozquerier/provider.go
@@ -18,7 +18,7 @@ import (
"github.com/SigNoz/signoz/pkg/telemetrytraces"
)
-// NewFactory creates a new factory for the signoz querier provider
+// NewFactory creates a new factory for the signoz querier provider.
func NewFactory(
telemetryStore telemetrystore.TelemetryStore,
prometheus prometheus.Prometheus,
diff --git a/pkg/querybuilder/having_rewriter.go b/pkg/querybuilder/having_rewriter.go
index e5ebf62359..6e75ba32d3 100644
--- a/pkg/querybuilder/having_rewriter.go
+++ b/pkg/querybuilder/having_rewriter.go
@@ -12,7 +12,7 @@ type HavingExpressionRewriter struct {
columnMap map[string]string
}
-// NewHavingExpressionRewriter creates a new having expression rewriter
+// NewHavingExpressionRewriter creates a new having expression rewriter.
func NewHavingExpressionRewriter() *HavingExpressionRewriter {
return &HavingExpressionRewriter{
columnMap: make(map[string]string),
diff --git a/pkg/querybuilder/never_true.go b/pkg/querybuilder/never_true.go
index b818fad420..e88bbdada4 100644
--- a/pkg/querybuilder/never_true.go
+++ b/pkg/querybuilder/never_true.go
@@ -11,7 +11,7 @@ import (
"github.com/antlr4-go/antlr/v4"
)
-// FieldConstraint represents a constraint on a field
+// FieldConstraint represents a constraint on a field.
type FieldConstraint struct {
Field string
Operator qbtypes.FilterOperator
@@ -19,12 +19,12 @@ type FieldConstraint struct {
Values []interface{} // For IN, NOT IN operations
}
-// ConstraintSet represents a set of constraints that must all be true (AND)
+// ConstraintSet represents a set of constraints that must all be true (AND).
type ConstraintSet struct {
Constraints map[string][]FieldConstraint // field -> constraints
}
-// LogicalContradictionDetector implements the visitor pattern to detect logical contradictions
+// LogicalContradictionDetector implements the visitor pattern to detect logical contradictions.
type LogicalContradictionDetector struct {
grammar.BaseFilterQueryVisitor
constraintStack []*ConstraintSet // Stack of constraint sets for nested expressions
@@ -32,7 +32,7 @@ type LogicalContradictionDetector struct {
notContextStack []bool // Stack to track NOT contexts
}
-// DetectContradictions analyzes a query string and returns any contradictions found
+// DetectContradictions analyzes a query string and returns any contradictions found.
func DetectContradictions(query string) ([]string, error) {
// Setup ANTLR parsing pipeline
input := antlr.NewInputStream(query)
@@ -82,12 +82,12 @@ func DetectContradictions(query string) ([]string, error) {
return unique, nil
}
-// Helper methods for constraint stack
+// Helper methods for constraint stack.
func (d *LogicalContradictionDetector) currentConstraints() *ConstraintSet {
return d.constraintStack[len(d.constraintStack)-1]
}
-// Helper methods for NOT context
+// Helper methods for NOT context.
func (d *LogicalContradictionDetector) inNotContext() bool {
return d.notContextStack[len(d.notContextStack)-1]
}
@@ -102,7 +102,7 @@ func (d *LogicalContradictionDetector) popNotContext() {
}
}
-// Visit dispatches to the appropriate visit method
+// Visit dispatches to the appropriate visit method.
func (d *LogicalContradictionDetector) Visit(tree antlr.ParseTree) interface{} {
if tree == nil {
return nil
@@ -110,7 +110,7 @@ func (d *LogicalContradictionDetector) Visit(tree antlr.ParseTree) interface{} {
return tree.Accept(d)
}
-// VisitQuery is the entry point
+// VisitQuery is the entry point.
func (d *LogicalContradictionDetector) VisitQuery(ctx *grammar.QueryContext) interface{} {
d.Visit(ctx.Expression())
// Check final constraints
@@ -118,12 +118,12 @@ func (d *LogicalContradictionDetector) VisitQuery(ctx *grammar.QueryContext) int
return nil
}
-// VisitExpression just passes through to OrExpression
+// VisitExpression just passes through to OrExpression.
func (d *LogicalContradictionDetector) VisitExpression(ctx *grammar.ExpressionContext) interface{} {
return d.Visit(ctx.OrExpression())
}
-// VisitOrExpression handles OR logic
+// VisitOrExpression handles OR logic.
func (d *LogicalContradictionDetector) VisitOrExpression(ctx *grammar.OrExpressionContext) interface{} {
andExpressions := ctx.AllAndExpression()
@@ -148,7 +148,7 @@ func (d *LogicalContradictionDetector) VisitOrExpression(ctx *grammar.OrExpressi
return nil
}
-// VisitAndExpression handles AND logic (including implicit AND)
+// VisitAndExpression handles AND logic (including implicit AND).
func (d *LogicalContradictionDetector) VisitAndExpression(ctx *grammar.AndExpressionContext) interface{} {
unaryExpressions := ctx.AllUnaryExpression()
@@ -160,7 +160,7 @@ func (d *LogicalContradictionDetector) VisitAndExpression(ctx *grammar.AndExpres
return nil
}
-// VisitUnaryExpression handles NOT operator
+// VisitUnaryExpression handles NOT operator.
func (d *LogicalContradictionDetector) VisitUnaryExpression(ctx *grammar.UnaryExpressionContext) interface{} {
hasNot := ctx.NOT() != nil
@@ -179,7 +179,7 @@ func (d *LogicalContradictionDetector) VisitUnaryExpression(ctx *grammar.UnaryEx
return result
}
-// VisitPrimary handles different primary expressions
+// VisitPrimary handles different primary expressions.
func (d *LogicalContradictionDetector) VisitPrimary(ctx *grammar.PrimaryContext) interface{} {
if ctx.OrExpression() != nil {
// Parenthesized expression
@@ -199,7 +199,7 @@ func (d *LogicalContradictionDetector) VisitPrimary(ctx *grammar.PrimaryContext)
return nil
}
-// VisitComparison extracts constraints from comparisons
+// VisitComparison extracts constraints from comparisons.
func (d *LogicalContradictionDetector) VisitComparison(ctx *grammar.ComparisonContext) interface{} {
if ctx.Key() == nil {
return nil
@@ -342,7 +342,7 @@ func (d *LogicalContradictionDetector) VisitComparison(ctx *grammar.ComparisonCo
return nil
}
-// extractValue extracts the actual value from a ValueContext
+// extractValue extracts the actual value from a ValueContext.
func (d *LogicalContradictionDetector) extractValue(ctx grammar.IValueContext) interface{} {
if ctx.QUOTED_TEXT() != nil {
text := ctx.QUOTED_TEXT().GetText()
@@ -361,7 +361,7 @@ func (d *LogicalContradictionDetector) extractValue(ctx grammar.IValueContext) i
return ""
}
-// extractValueList extracts values from a ValueListContext
+// extractValueList extracts values from a ValueListContext.
func (d *LogicalContradictionDetector) extractValueList(ctx grammar.IValueListContext) []interface{} {
if ctx == nil {
return nil
@@ -374,7 +374,7 @@ func (d *LogicalContradictionDetector) extractValueList(ctx grammar.IValueListCo
return values
}
-// addConstraint adds a constraint to the current set
+// addConstraint adds a constraint to the current set.
func (d *LogicalContradictionDetector) addConstraint(constraint FieldConstraint) {
constraints := d.currentConstraints()
@@ -399,7 +399,7 @@ func (d *LogicalContradictionDetector) addConstraint(constraint FieldConstraint)
)
}
-// checkContradictions checks the given constraint set for contradictions
+// checkContradictions checks the given constraint set for contradictions.
func (d *LogicalContradictionDetector) checkContradictions(constraintSet *ConstraintSet) {
for field, constraints := range constraintSet.Constraints {
if len(constraints) < 2 {
@@ -412,7 +412,7 @@ func (d *LogicalContradictionDetector) checkContradictions(constraintSet *Constr
}
}
-// findContradictionsInConstraints checks if a set of constraints on the same field contradict
+// findContradictionsInConstraints checks if a set of constraints on the same field contradict.
func (d *LogicalContradictionDetector) findContradictionsInConstraints(field string, constraints []FieldConstraint) []string {
contradictions := []string{}
@@ -644,7 +644,7 @@ func (d *LogicalContradictionDetector) findContradictionsInConstraints(field str
return contradictions
}
-// hasCommonIntersection checks if all BETWEEN ranges have a common intersection
+// hasCommonIntersection checks if all BETWEEN ranges have a common intersection.
func (d *LogicalContradictionDetector) hasCommonIntersection(betweens []FieldConstraint) bool {
if len(betweens) == 0 {
return true
@@ -684,7 +684,7 @@ func (d *LogicalContradictionDetector) hasCommonIntersection(betweens []FieldCon
return !initialized || intersectionMin <= intersectionMax
}
-// checkRangeContradictions checks if range constraints are satisfiable
+// checkRangeContradictions checks if range constraints are satisfiable.
func (d *LogicalContradictionDetector) checkRangeContradictions(constraints []FieldConstraint) bool {
// We need to find if there's any value that satisfies all constraints
@@ -762,7 +762,7 @@ func (d *LogicalContradictionDetector) checkRangeContradictions(constraints []Fi
return false
}
-// valuesSatisfyRanges checks if a value satisfies all range constraints
+// valuesSatisfyRanges checks if a value satisfies all range constraints.
func (d *LogicalContradictionDetector) valuesSatisfyRanges(value interface{}, constraints []FieldConstraint) bool {
val, err := parseNumericValue(value)
if err != nil {
@@ -798,7 +798,7 @@ func (d *LogicalContradictionDetector) valuesSatisfyRanges(value interface{}, co
return true
}
-// valueSatisfiesBetween checks if a value is within a BETWEEN range
+// valueSatisfiesBetween checks if a value is within a BETWEEN range.
func (d *LogicalContradictionDetector) valueSatisfiesBetween(value interface{}, between FieldConstraint) bool {
if len(between.Values) != 2 {
return false
@@ -819,7 +819,7 @@ func (d *LogicalContradictionDetector) valueSatisfiesBetween(value interface{},
return val >= min && val <= max
}
-// matchesLikePattern is a simple pattern matcher for LIKE
+// matchesLikePattern is a simple pattern matcher for LIKE.
func (d *LogicalContradictionDetector) matchesLikePattern(value, pattern string) bool {
// Simple implementation - just check prefix/suffix with %
if strings.HasPrefix(pattern, "%") && strings.HasSuffix(pattern, "%") {
@@ -832,7 +832,7 @@ func (d *LogicalContradictionDetector) matchesLikePattern(value, pattern string)
return value == pattern
}
-// cloneConstraintSet creates a deep copy of a constraint set
+// cloneConstraintSet creates a deep copy of a constraint set.
func (d *LogicalContradictionDetector) cloneConstraintSet(set *ConstraintSet) *ConstraintSet {
newSet := &ConstraintSet{
Constraints: make(map[string][]FieldConstraint),
@@ -847,7 +847,7 @@ func (d *LogicalContradictionDetector) cloneConstraintSet(set *ConstraintSet) *C
return newSet
}
-// parseNumericValue attempts to parse a value as a number
+// parseNumericValue attempts to parse a value as a number.
func parseNumericValue(value interface{}) (float64, error) {
switch v := value.(type) {
case float64:
@@ -861,7 +861,7 @@ func parseNumericValue(value interface{}) (float64, error) {
}
}
-// negateOperator returns the negated version of an operator
+// negateOperator returns the negated version of an operator.
func negateOperator(op qbtypes.FilterOperator) qbtypes.FilterOperator {
switch op {
case qbtypes.FilterOperatorEqual:
@@ -909,7 +909,7 @@ func negateOperator(op qbtypes.FilterOperator) qbtypes.FilterOperator {
}
}
-// isRangeOperator returns true if the operator is a range comparison operator
+// isRangeOperator returns true if the operator is a range comparison operator.
func isRangeOperator(op qbtypes.FilterOperator) bool {
switch op {
case qbtypes.FilterOperatorLessThan,
@@ -922,7 +922,7 @@ func isRangeOperator(op qbtypes.FilterOperator) bool {
}
}
-// isNegativeOperator returns true if the operator is a negative/exclusion operator
+// isNegativeOperator returns true if the operator is a negative/exclusion operator.
func isNegativeOperator(op qbtypes.FilterOperator) bool {
switch op {
case qbtypes.FilterOperatorNotEqual,
diff --git a/pkg/querybuilder/resourcefilter/condition_builder_test.go b/pkg/querybuilder/resourcefilter/condition_builder_test.go
index 50a9c10b47..d63b478e82 100644
--- a/pkg/querybuilder/resourcefilter/condition_builder_test.go
+++ b/pkg/querybuilder/resourcefilter/condition_builder_test.go
@@ -4,7 +4,6 @@ import (
"context"
"testing"
- "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/huandu/go-sqlbuilder"
@@ -17,7 +16,7 @@ func TestConditionBuilder(t *testing.T) {
testCases := []struct {
name string
key *telemetrytypes.TelemetryFieldKey
- op querybuildertypesv5.FilterOperator
+ op qbtypes.FilterOperator
value any
expected string
expectedArgs []any
@@ -29,7 +28,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorEqual,
+ op: qbtypes.FilterOperatorEqual,
value: "watch",
expected: "simpleJSONExtractString(labels, 'k8s.namespace.name') = ? AND labels LIKE ? AND labels LIKE ?",
expectedArgs: []any{"watch", "%k8s.namespace.name%", `%k8s.namespace.name":"watch%`},
@@ -40,7 +39,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorNotEqual,
+ op: qbtypes.FilterOperatorNotEqual,
value: "redis",
expected: "simpleJSONExtractString(labels, 'k8s.namespace.name') <> ? AND labels NOT LIKE ?",
expectedArgs: []any{"redis", `%k8s.namespace.name":"redis%`},
@@ -51,7 +50,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorLike,
+ op: qbtypes.FilterOperatorLike,
value: "_mango%",
expected: "LOWER(simpleJSONExtractString(labels, 'k8s.namespace.name')) LIKE LOWER(?) AND labels LIKE ? AND LOWER(labels) LIKE LOWER(?)",
expectedArgs: []any{"_mango%", "%k8s.namespace.name%", `%k8s.namespace.name%_mango%%`},
@@ -62,7 +61,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorNotLike,
+ op: qbtypes.FilterOperatorNotLike,
value: "_mango%",
expected: "LOWER(simpleJSONExtractString(labels, 'k8s.namespace.name')) NOT LIKE LOWER(?)",
expectedArgs: []any{"_mango%"},
@@ -73,7 +72,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorContains,
+ op: qbtypes.FilterOperatorContains,
value: "banana",
expected: "LOWER(simpleJSONExtractString(labels, 'k8s.namespace.name')) LIKE LOWER(?) AND labels LIKE ? AND LOWER(labels) LIKE LOWER(?)",
expectedArgs: []any{"%banana%", "%k8s.namespace.name%", `%k8s.namespace.name%banana%`},
@@ -96,7 +95,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorNotContains,
+ op: qbtypes.FilterOperatorNotContains,
value: "banana",
expected: "LOWER(simpleJSONExtractString(labels, 'k8s.namespace.name')) NOT LIKE LOWER(?)",
expectedArgs: []any{"%banana%"},
@@ -107,7 +106,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorIn,
+ op: qbtypes.FilterOperatorIn,
value: []any{"watch", "redis"},
expected: "(simpleJSONExtractString(labels, 'k8s.namespace.name') = ? OR simpleJSONExtractString(labels, 'k8s.namespace.name') = ?) AND labels LIKE ? AND (labels LIKE ? OR labels LIKE ?)",
expectedArgs: []any{"watch", "redis", "%k8s.namespace.name%", "%k8s.namespace.name\":\"watch%", "%k8s.namespace.name\":\"redis%"},
@@ -118,7 +117,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorNotIn,
+ op: qbtypes.FilterOperatorNotIn,
value: []any{"watch", "redis"},
expected: "(simpleJSONExtractString(labels, 'k8s.namespace.name') <> ? AND simpleJSONExtractString(labels, 'k8s.namespace.name') <> ?) AND (labels NOT LIKE ? AND labels NOT LIKE ?)",
expectedArgs: []any{"watch", "redis", "%k8s.namespace.name\":\"watch%", "%k8s.namespace.name\":\"redis%"},
@@ -129,7 +128,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorExists,
+ op: qbtypes.FilterOperatorExists,
expected: "simpleJSONHas(labels, 'k8s.namespace.name') = ? AND labels LIKE ?",
expectedArgs: []any{true, "%k8s.namespace.name%"},
},
@@ -139,7 +138,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorNotExists,
+ op: qbtypes.FilterOperatorNotExists,
expected: "simpleJSONHas(labels, 'k8s.namespace.name') <> ?",
expectedArgs: []any{true},
},
@@ -149,7 +148,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "test_num",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorEqual,
+ op: qbtypes.FilterOperatorEqual,
value: 1,
expected: "simpleJSONExtractString(labels, 'test_num') = ? AND labels LIKE ? AND labels LIKE ?",
expectedArgs: []any{"1", "%test_num%", "%test_num\":\"1%"},
@@ -160,7 +159,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "test_num",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorGreaterThan,
+ op: qbtypes.FilterOperatorGreaterThan,
value: 1,
expected: "simpleJSONExtractString(labels, 'test_num') > ? AND labels LIKE ?",
expectedArgs: []any{"1", "%test_num%"},
@@ -171,7 +170,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "test_num",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorIn,
+ op: qbtypes.FilterOperatorIn,
value: []any{1, 2},
expected: "(simpleJSONExtractString(labels, 'test_num') = ? OR simpleJSONExtractString(labels, 'test_num') = ?) AND labels LIKE ? AND (labels LIKE ? OR labels LIKE ?)",
expectedArgs: []any{"1", "2", "%test_num%", "%test_num\":\"1%", "%test_num\":\"2%"},
@@ -182,7 +181,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "test_num",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorBetween,
+ op: qbtypes.FilterOperatorBetween,
value: []any{1, 2},
expected: "labels LIKE ? AND simpleJSONExtractString(labels, 'test_num') BETWEEN ? AND ?",
expectedArgs: []any{"%test_num%", "1", "2"},
@@ -193,7 +192,7 @@ func TestConditionBuilder(t *testing.T) {
Name: "k8s.namespace.name",
FieldContext: telemetrytypes.FieldContextResource,
},
- op: querybuildertypesv5.FilterOperatorRegexp,
+ op: qbtypes.FilterOperatorRegexp,
value: "ban.*",
expected: "match(simpleJSONExtractString(labels, 'k8s.namespace.name'), ?) AND labels LIKE ?",
expectedArgs: []any{"ban.*", "%k8s.namespace.name%"},
diff --git a/pkg/querybuilder/resourcefilter/statement_builder.go b/pkg/querybuilder/resourcefilter/statement_builder.go
index f5d79696bf..cb51185fab 100644
--- a/pkg/querybuilder/resourcefilter/statement_builder.go
+++ b/pkg/querybuilder/resourcefilter/statement_builder.go
@@ -17,7 +17,7 @@ var (
ErrUnsupportedSignal = errors.NewInvalidInputf(errors.CodeInvalidInput, "unsupported signal type")
)
-// Configuration for different signal types
+// Configuration for different signal types.
type signalConfig struct {
dbName string
tableName string
@@ -34,7 +34,7 @@ var signalConfigs = map[telemetrytypes.Signal]signalConfig{
},
}
-// Generic resource filter statement builder
+// Generic resource filter statement builder.
type resourceFilterStatementBuilder[T any] struct {
logger *slog.Logger
fieldMapper qbtypes.FieldMapper
@@ -46,13 +46,13 @@ type resourceFilterStatementBuilder[T any] struct {
jsonKeyToKey qbtypes.JsonKeyToFieldFunc
}
-// Ensure interface compliance at compile time
+// Ensure interface compliance at compile time.
var (
_ qbtypes.StatementBuilder[qbtypes.TraceAggregation] = (*resourceFilterStatementBuilder[qbtypes.TraceAggregation])(nil)
_ qbtypes.StatementBuilder[qbtypes.LogAggregation] = (*resourceFilterStatementBuilder[qbtypes.LogAggregation])(nil)
)
-// Constructor functions
+// NewTraceResourceFilterStatementBuilder creates a new trace resource filter statement builder.
func NewTraceResourceFilterStatementBuilder(
settings factory.ProviderSettings,
fieldMapper qbtypes.FieldMapper,
@@ -111,7 +111,7 @@ func (b *resourceFilterStatementBuilder[T]) getKeySelectors(query qbtypes.QueryB
return filteredKeySelectors
}
-// Build builds a SQL query based on the given parameters
+// Build builds a SQL query based on the given parameters.
func (b *resourceFilterStatementBuilder[T]) Build(
ctx context.Context,
start uint64,
@@ -146,7 +146,7 @@ func (b *resourceFilterStatementBuilder[T]) Build(
}, nil
}
-// addConditions adds both filter and time conditions to the query
+// addConditions adds both filter and time conditions to the query.
func (b *resourceFilterStatementBuilder[T]) addConditions(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
@@ -189,7 +189,7 @@ func (b *resourceFilterStatementBuilder[T]) addConditions(
return nil
}
-// addTimeFilter adds time-based filtering conditions
+// addTimeFilter adds time-based filtering conditions.
func (b *resourceFilterStatementBuilder[T]) addTimeFilter(sb *sqlbuilder.SelectBuilder, start, end uint64) {
// Convert nanoseconds to seconds and adjust start bucket
startBucket := start/querybuilder.NsToSeconds - querybuilder.BucketAdjustment
diff --git a/pkg/querybuilder/resourcefilter/statement_builder_test.go b/pkg/querybuilder/resourcefilter/statement_builder_test.go
index 719f2a669d..63f6265c80 100644
--- a/pkg/querybuilder/resourcefilter/statement_builder_test.go
+++ b/pkg/querybuilder/resourcefilter/statement_builder_test.go
@@ -86,15 +86,15 @@ func buildTestFieldKeyMap(signal telemetrytypes.Signal) map[string][]*telemetryt
return keysMap
}
-// Test constants - values are in nanoseconds as expected by the resource filter builder
+// Test constants - values are in nanoseconds as expected by the resource filter builder.
const (
- // 1747947419000000000 ns = 1747947419 seconds
+ // 1747947419000000000 ns = 1747947419 seconds.
testStartNs = uint64(1747947419000000000)
- // 1747983448000000000 ns = 1747983448 seconds
+ // 1747983448000000000 ns = 1747983448 seconds.
testEndNs = uint64(1747983448000000000)
- // Expected bucket start = 1747947419 - 1800 = 1747945619
+ // Expected bucket start = 1747947419 - 1800 = 1747945619.
expectedBucketStart = uint64(1747945619)
- // Expected bucket end = 1747983448
+ // Expected bucket end = 1747983448.
expectedBucketEnd = uint64(1747983448)
)
diff --git a/pkg/querybuilder/time.go b/pkg/querybuilder/time.go
index 1073b8e6a9..f1a3b3b554 100644
--- a/pkg/querybuilder/time.go
+++ b/pkg/querybuilder/time.go
@@ -18,7 +18,7 @@ const (
MaxAllowedSeries = 3000
)
-// ToNanoSecs takes epoch and returns it in ns
+// ToNanoSecs takes epoch and returns it in ns.
func ToNanoSecs(epoch uint64) uint64 {
temp := epoch
count := 0
@@ -34,7 +34,7 @@ func ToNanoSecs(epoch uint64) uint64 {
}
// TODO(srikanthccv): should these be rounded to nearest multiple of 60 instead of 5 if step > 60?
-// That would make graph look nice but "nice" but should be less important than the usefulness
+// That would make graph look nice but "nice" but should be less important than the usefulness.
func RecommendedStepInterval(start, end uint64) uint64 {
start = ToNanoSecs(start)
end = ToNanoSecs(end)
diff --git a/pkg/querybuilder/where_clause_visitor.go b/pkg/querybuilder/where_clause_visitor.go
index ae49af0a18..f03fc943d9 100644
--- a/pkg/querybuilder/where_clause_visitor.go
+++ b/pkg/querybuilder/where_clause_visitor.go
@@ -22,7 +22,7 @@ var searchTroubleshootingGuideURL = "https://signoz.io/docs/userguide/search-tro
const stringMatchingOperatorDocURL = "https://signoz.io/docs/userguide/operators-reference/#string-matching-operators"
// filterExpressionVisitor implements the FilterQueryVisitor interface
-// to convert the parsed filter expressions into ClickHouse WHERE clause
+// to convert the parsed filter expressions into ClickHouse WHERE clause.
type filterExpressionVisitor struct {
context context.Context
logger *slog.Logger
@@ -65,7 +65,7 @@ type FilterExprVisitorOpts struct {
EndNs uint64
}
-// newFilterExpressionVisitor creates a new filterExpressionVisitor
+// newFilterExpressionVisitor creates a new filterExpressionVisitor.
func newFilterExpressionVisitor(opts FilterExprVisitorOpts) *filterExpressionVisitor {
return &filterExpressionVisitor{
context: opts.Context,
@@ -93,7 +93,7 @@ type PreparedWhereClause struct {
WarningsDocURL string
}
-// PrepareWhereClause generates a ClickHouse compatible WHERE clause from the filter query
+// PrepareWhereClause generates a ClickHouse compatible WHERE clause from the filter query.
func PrepareWhereClause(query string, opts FilterExprVisitorOpts) (*PreparedWhereClause, error) {
// Setup the ANTLR parsing pipeline
@@ -178,7 +178,7 @@ func PrepareWhereClause(query string, opts FilterExprVisitorOpts) (*PreparedWher
return &PreparedWhereClause{WhereClause: whereClause, Warnings: visitor.warnings, WarningsDocURL: visitor.mainWarnURL}, nil
}
-// Visit dispatches to the specific visit method based on node type
+// Visit dispatches to the specific visit method based on node type.
func (v *filterExpressionVisitor) Visit(tree antlr.ParseTree) any {
// Handle nil nodes to prevent panic
if tree == nil {
@@ -230,12 +230,12 @@ func (v *filterExpressionVisitor) VisitQuery(ctx *grammar.QueryContext) any {
return v.Visit(ctx.Expression())
}
-// VisitExpression passes through to the orExpression
+// VisitExpression passes through to the orExpression.
func (v *filterExpressionVisitor) VisitExpression(ctx *grammar.ExpressionContext) any {
return v.Visit(ctx.OrExpression())
}
-// VisitOrExpression handles OR expressions
+// VisitOrExpression handles OR expressions.
func (v *filterExpressionVisitor) VisitOrExpression(ctx *grammar.OrExpressionContext) any {
andExpressions := ctx.AllAndExpression()
@@ -262,7 +262,7 @@ func (v *filterExpressionVisitor) VisitOrExpression(ctx *grammar.OrExpressionCon
return v.builder.Or(andExpressionConditions...)
}
-// VisitAndExpression handles AND expressions
+// VisitAndExpression handles AND expressions.
func (v *filterExpressionVisitor) VisitAndExpression(ctx *grammar.AndExpressionContext) any {
unaryExpressions := ctx.AllUnaryExpression()
@@ -290,7 +290,7 @@ func (v *filterExpressionVisitor) VisitAndExpression(ctx *grammar.AndExpressionC
return v.builder.And(unaryExpressionConditions...)
}
-// VisitUnaryExpression handles NOT expressions
+// VisitUnaryExpression handles NOT expressions.
func (v *filterExpressionVisitor) VisitUnaryExpression(ctx *grammar.UnaryExpressionContext) any {
result := v.Visit(ctx.Primary()).(string)
@@ -306,7 +306,7 @@ func (v *filterExpressionVisitor) VisitUnaryExpression(ctx *grammar.UnaryExpress
return result
}
-// VisitPrimary handles grouped expressions, comparisons, function calls, and full-text search
+// VisitPrimary handles grouped expressions, comparisons, function calls, and full-text search.
func (v *filterExpressionVisitor) VisitPrimary(ctx *grammar.PrimaryContext) any {
if ctx.OrExpression() != nil {
// This is a parenthesized expression
@@ -366,7 +366,7 @@ func (v *filterExpressionVisitor) VisitPrimary(ctx *grammar.PrimaryContext) any
return ErrorConditionLiteral // Should not happen with valid input
}
-// VisitComparison handles all comparison operators
+// VisitComparison handles all comparison operators.
func (v *filterExpressionVisitor) VisitComparison(ctx *grammar.ComparisonContext) any {
keys := v.Visit(ctx.Key()).([]*telemetrytypes.TelemetryFieldKey)
@@ -647,7 +647,7 @@ func (v *filterExpressionVisitor) VisitComparison(ctx *grammar.ComparisonContext
return ErrorConditionLiteral // Should not happen with valid input
}
-// warnIfLikeWithoutWildcards adds a guidance warning when LIKE/ILIKE is used without wildcards
+// warnIfLikeWithoutWildcards adds a guidance warning when LIKE/ILIKE is used without wildcards.
func (v *filterExpressionVisitor) warnIfLikeWithoutWildcards(op string, value any) {
if hasLikeWildcards(value) {
return
@@ -660,7 +660,7 @@ func (v *filterExpressionVisitor) warnIfLikeWithoutWildcards(op string, value an
}
}
-// VisitInClause handles IN expressions
+// VisitInClause handles IN expressions.
func (v *filterExpressionVisitor) VisitInClause(ctx *grammar.InClauseContext) any {
if ctx.ValueList() != nil {
return v.Visit(ctx.ValueList())
@@ -668,7 +668,7 @@ func (v *filterExpressionVisitor) VisitInClause(ctx *grammar.InClauseContext) an
return v.Visit(ctx.Value())
}
-// VisitNotInClause handles NOT IN expressions
+// VisitNotInClause handles NOT IN expressions.
func (v *filterExpressionVisitor) VisitNotInClause(ctx *grammar.NotInClauseContext) any {
if ctx.ValueList() != nil {
return v.Visit(ctx.ValueList())
@@ -676,7 +676,7 @@ func (v *filterExpressionVisitor) VisitNotInClause(ctx *grammar.NotInClauseConte
return v.Visit(ctx.Value())
}
-// VisitValueList handles comma-separated value lists
+// VisitValueList handles comma-separated value lists.
func (v *filterExpressionVisitor) VisitValueList(ctx *grammar.ValueListContext) any {
values := ctx.AllValue()
@@ -688,7 +688,7 @@ func (v *filterExpressionVisitor) VisitValueList(ctx *grammar.ValueListContext)
return parts
}
-// VisitFullText handles standalone quoted strings for full-text search
+// VisitFullText handles standalone quoted strings for full-text search.
func (v *filterExpressionVisitor) VisitFullText(ctx *grammar.FullTextContext) any {
if v.skipFullTextFilter {
// A skipped FT term must be treated as TrueConditionLiteral, not "".
@@ -832,7 +832,7 @@ func (v *filterExpressionVisitor) VisitFunctionCall(ctx *grammar.FunctionCallCon
return v.builder.Or(conds...)
}
-// VisitFunctionParamList handles the parameter list for function calls
+// VisitFunctionParamList handles the parameter list for function calls.
func (v *filterExpressionVisitor) VisitFunctionParamList(ctx *grammar.FunctionParamListContext) any {
params := ctx.AllFunctionParam()
parts := make([]any, len(params))
@@ -844,7 +844,7 @@ func (v *filterExpressionVisitor) VisitFunctionParamList(ctx *grammar.FunctionPa
return parts
}
-// VisitFunctionParam handles individual parameters in function calls
+// VisitFunctionParam handles individual parameters in function calls.
func (v *filterExpressionVisitor) VisitFunctionParam(ctx *grammar.FunctionParamContext) any {
if ctx.Key() != nil {
return v.Visit(ctx.Key())
@@ -857,12 +857,12 @@ func (v *filterExpressionVisitor) VisitFunctionParam(ctx *grammar.FunctionParamC
return ErrorConditionLiteral // Should not happen with valid input
}
-// VisitArray handles array literals
+// VisitArray handles array literals.
func (v *filterExpressionVisitor) VisitArray(ctx *grammar.ArrayContext) any {
return v.Visit(ctx.ValueList())
}
-// VisitValue handles literal values: strings, numbers, booleans
+// VisitValue handles literal values: strings, numbers, booleans.
func (v *filterExpressionVisitor) VisitValue(ctx *grammar.ValueContext) any {
if ctx.QUOTED_TEXT() != nil {
txt := ctx.QUOTED_TEXT().GetText()
@@ -890,7 +890,7 @@ func (v *filterExpressionVisitor) VisitValue(ctx *grammar.ValueContext) any {
return ErrorConditionLiteral // Should not happen with valid input
}
-// VisitKey handles field/column references
+// VisitKey handles field/column references.
func (v *filterExpressionVisitor) VisitKey(ctx *grammar.KeyContext) any {
fieldKey := telemetrytypes.GetFieldKeyFromKeyText(ctx.GetText())
keyName := fieldKey.Name
@@ -991,7 +991,7 @@ func (v *filterExpressionVisitor) VisitKey(ctx *grammar.KeyContext) any {
return fieldKeysForName
}
-// hasLikeWildcards checks if a value contains LIKE wildcards (% or _)
+// hasLikeWildcards checks if a value contains LIKE wildcards (% or _).
func hasLikeWildcards(value any) bool {
str, ok := value.(string)
if !ok {
diff --git a/pkg/querybuilder/where_clause_visitor_test.go b/pkg/querybuilder/where_clause_visitor_test.go
index 5c9e4faf85..a16393554f 100644
--- a/pkg/querybuilder/where_clause_visitor_test.go
+++ b/pkg/querybuilder/where_clause_visitor_test.go
@@ -15,7 +15,7 @@ import (
"github.com/stretchr/testify/assert"
)
-// TestPrepareWhereClause_EmptyVariableList ensures PrepareWhereClause errors when a variable has an empty list value
+// TestPrepareWhereClause_EmptyVariableList ensures PrepareWhereClause errors when a variable has an empty list value.
func TestPrepareWhereClause_EmptyVariableList(t *testing.T) {
tests := []struct {
name string
@@ -78,7 +78,7 @@ func TestPrepareWhereClause_EmptyVariableList(t *testing.T) {
}
}
-// createTestVisitor creates a filterExpressionVisitor for testing VisitKey
+// createTestVisitor creates a filterExpressionVisitor for testing VisitKey.
func createTestVisitor(fieldKeys map[string][]*telemetrytypes.TelemetryFieldKey, ignoreNotFoundKeys bool) *filterExpressionVisitor {
return &filterExpressionVisitor{
logger: slog.Default(),
@@ -89,7 +89,7 @@ func createTestVisitor(fieldKeys map[string][]*telemetrytypes.TelemetryFieldKey,
}
}
-// parseKeyContext parses a key string and returns the KeyContext for testing
+// parseKeyContext parses a key string and returns the KeyContext for testing.
func parseKeyContext(keyText string) *grammar.KeyContext {
input := antlr.NewInputStream(keyText + " = 1") // Add minimal expression to parse key
lexer := grammar.NewFilterQueryLexer(input)
@@ -116,7 +116,7 @@ func parseKeyContext(keyText string) *grammar.KeyContext {
return nil
}
-// TestVisitKey tests the VisitKey method of filterExpressionVisitor
+// TestVisitKey tests the VisitKey method of filterExpressionVisitor.
func TestVisitKey(t *testing.T) {
tests := []struct {
name string
@@ -1626,7 +1626,7 @@ func TestVisitComparison_UnknownKeys(t *testing.T) {
}
// TestVisitComparison_SkippableLiteralValues guards against two distinct collision risks
-// involving SkippableConditionLiterals ("true", "__skip__", "__skip_because_of_error__"):
+// involving SkippableConditionLiterals ("true", "__skip__", "__skip_because_of_error__"):.
func TestVisitComparison_SkippableLiteralValues(t *testing.T) {
rsbOpts, sbOpts := visitComparisonOpts()
diff --git a/pkg/queryparser/api.go b/pkg/queryparser/api.go
index 5be2ec4918..60c7ed80f8 100644
--- a/pkg/queryparser/api.go
+++ b/pkg/queryparser/api.go
@@ -19,7 +19,7 @@ func NewAPI(settings factory.ProviderSettings, queryParser QueryParser) *API {
return &API{settings: settings, queryParser: queryParser}
}
-// AnalyzeQueryFilter analyzes a query and extracts metric names and grouping columns
+// AnalyzeQueryFilter analyzes a query and extracts metric names and grouping columns.
func (a *API) AnalyzeQueryFilter(w http.ResponseWriter, r *http.Request) {
// Limit request body size to 255 KB (CH query limit is 256 KB)
r.Body = http.MaxBytesReader(w, r.Body, 255*1024)
diff --git a/pkg/queryparser/queryfilterextractor/clickhouse.go b/pkg/queryparser/queryfilterextractor/clickhouse.go
index 0411721da0..cb63860ece 100644
--- a/pkg/queryparser/queryfilterextractor/clickhouse.go
+++ b/pkg/queryparser/queryfilterextractor/clickhouse.go
@@ -10,19 +10,19 @@ import (
)
const (
- // MetricNameColumn is the column name used for filtering metrics
+ // MetricNameColumn is the column name used for filtering metrics.
MetricNameColumn = "metric_name"
)
-// ClickHouseFilterExtractor extracts metric names and grouping keys from ClickHouse SQL queries
+// ClickHouseFilterExtractor extracts metric names and grouping keys from ClickHouse SQL queries.
type ClickHouseFilterExtractor struct{}
-// NewClickHouseFilterExtractor creates a new ClickHouse filter extractor
+// NewClickHouseFilterExtractor creates a new ClickHouse filter extractor.
func NewClickHouseFilterExtractor() *ClickHouseFilterExtractor {
return &ClickHouseFilterExtractor{}
}
-// Extract parses a ClickHouse query and extracts metric names and grouping keys
+// Extract parses a ClickHouse query and extracts metric names and grouping keys.
func (e *ClickHouseFilterExtractor) Extract(query string) (*FilterResult, error) {
p := clickhouse.NewParser(query)
stmts, err := p.ParseStmts()
@@ -101,7 +101,7 @@ func (e *ClickHouseFilterExtractor) Extract(query string) (*FilterResult, error)
// Metric Name Extraction
// ========================================
-// fillMetricNamesFromExpr extracts metric names from various node types
+// fillMetricNamesFromExpr extracts metric names from various node types.
func (e *ClickHouseFilterExtractor) fillMetricNamesFromExpr(node clickhouse.Expr, metricNames map[string]bool) {
switch n := node.(type) {
@@ -110,7 +110,7 @@ func (e *ClickHouseFilterExtractor) fillMetricNamesFromExpr(node clickhouse.Expr
}
}
-// fillMetricFromBinaryOp extracts metrics from binary operations
+// fillMetricFromBinaryOp extracts metrics from binary operations.
func (e *ClickHouseFilterExtractor) fillMetricFromBinaryOp(op *clickhouse.BinaryOperation, metricNames map[string]bool) {
// Check if left side is metric_name column
leftCol := e.getColumnName(op.LeftExpr)
@@ -165,7 +165,7 @@ func (e *ClickHouseFilterExtractor) fillMetricWithBinaryOpConditions(op *clickho
}
}
-// extractStringLiteral extracts a string literal value from an expression
+// extractStringLiteral extracts a string literal value from an expression.
func (e *ClickHouseFilterExtractor) extractStringLiteral(expr clickhouse.Expr) string {
switch ex := expr.(type) {
case *clickhouse.StringLiteral:
@@ -174,7 +174,7 @@ func (e *ClickHouseFilterExtractor) extractStringLiteral(expr clickhouse.Expr) s
return ""
}
-// extractInValues extracts values from IN expressions
+// extractInValues extracts values from IN expressions.
func (e *ClickHouseFilterExtractor) extractInValues(expr clickhouse.Expr, metricNames map[string]bool) {
// Find all string literals in the expression
strLits := clickhouse.FindAll(expr, func(node clickhouse.Expr) bool {
@@ -200,7 +200,7 @@ func (e *ClickHouseFilterExtractor) extractInValues(expr clickhouse.Expr, metric
// extractGroupByColumns extracts the GROUP BY columns from a query
// It follows the top-down approach where outer GROUP BY overrides inner GROUP BY in subqueries and CTEs.
-// Returns a slice of ColumnInfo with column names, aliases, and origins
+// Returns a slice of ColumnInfo with column names, aliases, and origins.
func (e *ClickHouseFilterExtractor) extractGroupByColumns(query *clickhouse.SelectQuery, cteMap map[string]*clickhouse.SelectQuery, visited map[*clickhouse.SelectQuery]bool) ([]ColumnInfo, error) {
if visited[query] {
return nil, nil
@@ -255,7 +255,7 @@ func (e *ClickHouseFilterExtractor) extractGroupByColumns(query *clickhouse.Sele
return nil, nil
}
-// fillGroupsFromGroupByClause extracts GROUP BY columns from a specific GroupByClause and fills the map with the column names
+// fillGroupsFromGroupByClause extracts GROUP BY columns from a specific GroupByClause and fills the map with the column names.
func (e *ClickHouseFilterExtractor) fillGroupsFromGroupByClause(groupByClause *clickhouse.GroupByClause, groupBy map[string]bool) {
// Extract GROUP BY expressions properly
@@ -331,7 +331,7 @@ func (e *ClickHouseFilterExtractor) extractColumnStrByExpr(expr clickhouse.Expr)
}
// stripTableAlias removes table alias prefix from a column name (e.g., "m.region" -> "region")
-// but for literals with backticks, we need preserve the entire string. (e.g., `os.type` -> "os.type")
+// but for literals with backticks, we need preserve the entire string. (e.g., `os.type` -> "os.type").
func (e *ClickHouseFilterExtractor) stripTableAlias(name string) string {
// Handling for backticks which are native to ClickHouse and used for literal names.
if strings.HasPrefix(name, "`") && strings.HasSuffix(name, "`") {
@@ -352,7 +352,7 @@ func (e *ClickHouseFilterExtractor) stripTableAlias(name string) string {
return name
}
-// getColumnName extracts column name from an expression
+// getColumnName extracts column name from an expression.
func (e *ClickHouseFilterExtractor) getColumnName(expr clickhouse.Expr) string {
switch ex := expr.(type) {
case *clickhouse.Ident:
@@ -417,7 +417,7 @@ func (e *ClickHouseFilterExtractor) extractSourceQuery(query *clickhouse.SelectQ
// extractColumnOrigin recursively traces a column back to its original expression
// Returns the original expression string (e.g., "JSONExtractString(labels, 'service.name')")
-// or the column name itself if it's a direct column reference
+// or the column name itself if it's a direct column reference.
func (e *ClickHouseFilterExtractor) extractColumnOrigin(
columnName string,
query *clickhouse.SelectQuery,
@@ -519,7 +519,7 @@ func (e *ClickHouseFilterExtractor) extractColumnOrigin(
return columnName
}
-// extractFullExpression extracts the complete string representation of an expression
+// extractFullExpression extracts the complete string representation of an expression.
func (e *ClickHouseFilterExtractor) extractFullExpression(expr clickhouse.Expr) string {
if expr == nil {
return ""
@@ -528,7 +528,7 @@ func (e *ClickHouseFilterExtractor) extractFullExpression(expr clickhouse.Expr)
}
// isSimpleColumnReference checks if an expression is just a simple column reference
-// (not a function call or complex expression)
+// (not a function call or complex expression).
func (e *ClickHouseFilterExtractor) isSimpleColumnReference(expr clickhouse.Expr) bool {
if expr == nil {
return false
@@ -560,7 +560,7 @@ func (e *ClickHouseFilterExtractor) isSimpleColumnReference(expr clickhouse.Expr
// extractSelectColumns extracts column names and their aliases from SELECT clause of a specific query
// Returns a map where key is normalized column name and value is the alias
// For duplicate columns with different aliases, the last alias wins
-// This follows the same pattern as extractGroupFromGroupByClause - finding direct children only
+// This follows the same pattern as extractGroupFromGroupByClause - finding direct children only.
func (e *ClickHouseFilterExtractor) extractSelectColumns(query *clickhouse.SelectQuery) map[string]string {
aliasMap := make(map[string]string)
@@ -598,7 +598,7 @@ func (e *ClickHouseFilterExtractor) extractSelectColumns(query *clickhouse.Selec
return aliasMap
}
-// extractSelectItemName extracts the column name or expression from a SelectItem
+// extractSelectItemName extracts the column name or expression from a SelectItem.
func (e *ClickHouseFilterExtractor) extractSelectItemName(selectItem *clickhouse.SelectItem) string {
if selectItem == nil || selectItem.Expr == nil {
return ""
@@ -608,7 +608,7 @@ func (e *ClickHouseFilterExtractor) extractSelectItemName(selectItem *clickhouse
}
// extractSelectItemAlias extracts the alias from a SelectItem
-// Returns empty string if no alias is present
+// Returns empty string if no alias is present.
func (e *ClickHouseFilterExtractor) extractSelectItemAlias(selectItem *clickhouse.SelectItem) string {
if selectItem == nil || selectItem.Alias == nil {
return ""
@@ -627,7 +627,7 @@ func (e *ClickHouseFilterExtractor) extractSelectItemAlias(selectItem *clickhous
// ========================================
// buildCTEMap builds a map of CTE names to their SelectQuery nodes by recursively
-// traversing all queries and their nested expressions
+// traversing all queries and their nested expressions.
func (e *ClickHouseFilterExtractor) buildCTEMap(query *clickhouse.SelectQuery, cteMap map[string]*clickhouse.SelectQuery) {
// Access CTEs directly from WithClause if it exists
@@ -647,7 +647,7 @@ func (e *ClickHouseFilterExtractor) buildCTEMap(query *clickhouse.SelectQuery, c
e.buildCTEMapFromExpr(query, cteMap)
}
-// extractCTEName extracts the CTE name from a CTEStmt, the Expr field is the name of the CTE
+// extractCTEName extracts the CTE name from a CTEStmt, the Expr field is the name of the CTE.
func (e *ClickHouseFilterExtractor) extractCTEName(cte *clickhouse.CTEStmt) string {
if cte == nil || cte.Expr == nil {
return ""
@@ -661,7 +661,7 @@ func (e *ClickHouseFilterExtractor) extractCTEName(cte *clickhouse.CTEStmt) stri
}
}
-// extractCTEQuery extracts the SelectQuery from a CTEStmt, the Alias field is the SelectQuery
+// extractCTEQuery extracts the SelectQuery from a CTEStmt, the Alias field is the SelectQuery.
func (e *ClickHouseFilterExtractor) extractCTEQuery(cte *clickhouse.CTEStmt) *clickhouse.SelectQuery {
if cte == nil || cte.Alias == nil {
return nil
@@ -675,7 +675,7 @@ func (e *ClickHouseFilterExtractor) extractCTEQuery(cte *clickhouse.CTEStmt) *cl
return nil
}
-// buildCTEMapFromExpr recursively extracts CTEs from various expression types
+// buildCTEMapFromExpr recursively extracts CTEs from various expression types.
func (e *ClickHouseFilterExtractor) buildCTEMapFromExpr(expr clickhouse.Expr, cteMap map[string]*clickhouse.SelectQuery) {
// Walk through all nodes to find SelectQuery nodes that might contain CTEs
diff --git a/pkg/queryparser/queryfilterextractor/clickhouse_originparser.go b/pkg/queryparser/queryfilterextractor/clickhouse_originparser.go
index 32c974530b..20bd6a994c 100644
--- a/pkg/queryparser/queryfilterextractor/clickhouse_originparser.go
+++ b/pkg/queryparser/queryfilterextractor/clickhouse_originparser.go
@@ -82,14 +82,14 @@ var jsonExtractFunctions = map[string]string{
"jsonextractkeysandvalues": "JSONExtractKeysAndValues",
}
-// isFunctionPresentInStore checks if a function name exists in the function store map
+// isFunctionPresentInStore checks if a function name exists in the function store map.
func isFunctionPresentInStore(funcName string, funcStore map[string]string) bool {
_, exists := funcStore[strings.ToLower(funcName)]
return exists
}
// isReservedSelectKeyword checks if a keyword is a reserved keyword for the SELECT statement
-// We're only including those which can appear in the SELECT statement without being quoted
+// We're only including those which can appear in the SELECT statement without being quoted.
func isReservedSelectKeyword(keyword string) bool {
return strings.ToUpper(keyword) == parser.KeywordSelect || strings.ToUpper(keyword) == parser.KeywordFrom
}
@@ -185,7 +185,7 @@ func extractOriginFieldFromExpr(expr parser.Expr) (string, error) {
return "", nil
}
-// containsJSONExtractFunction checks if an expression contains a JSON extraction function
+// containsJSONExtractFunction checks if an expression contains a JSON extraction function.
func containsJSONExtractFunction(expr parser.Expr) bool {
if expr == nil {
return false
diff --git a/pkg/queryparser/queryfilterextractor/promql.go b/pkg/queryparser/queryfilterextractor/promql.go
index fa90ccd073..8a350ef964 100644
--- a/pkg/queryparser/queryfilterextractor/promql.go
+++ b/pkg/queryparser/queryfilterextractor/promql.go
@@ -4,19 +4,20 @@ import (
"sort"
"github.com/SigNoz/signoz/pkg/errors"
+ "github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
)
-// PromQLFilterExtractor extracts metric names and grouping keys from PromQL queries
+// PromQLFilterExtractor extracts metric names and grouping keys from PromQL queries.
type PromQLFilterExtractor struct{}
-// NewPromQLFilterExtractor creates a new PromQL filter extractor
+// NewPromQLFilterExtractor creates a new PromQL filter extractor.
func NewPromQLFilterExtractor() *PromQLFilterExtractor {
return &PromQLFilterExtractor{}
}
-// Extract parses a PromQL query and extracts metric names and grouping keys
+// Extract parses a PromQL query and extracts metric names and grouping keys.
func (e *PromQLFilterExtractor) Extract(query string) (*FilterResult, error) {
expr, err := parser.ParseExpr(query)
if err != nil {
@@ -56,7 +57,7 @@ func (e *PromQLFilterExtractor) Extract(query string) (*FilterResult, error) {
return result, nil
}
-// promQLVisitor implements the parser.Visitor interface
+// promQLVisitor implements the parser.Visitor interface.
type promQLVisitor struct {
metricNames map[string]bool
groupBy map[string]bool
@@ -85,7 +86,7 @@ func (v *promQLVisitor) visitVectorSelector(vs *parser.VectorSelector) {
// Check for __name__ label matcher
for _, matcher := range vs.LabelMatchers {
- if matcher.Name == labels.MetricName {
+ if matcher.Name == model.MetricNameLabel {
switch matcher.Type {
case labels.MatchEqual:
v.metricNames[matcher.Value] = true
diff --git a/pkg/queryparser/queryfilterextractor/queryfilterextractor.go b/pkg/queryparser/queryfilterextractor/queryfilterextractor.go
index f768d9e19f..410ae4859c 100644
--- a/pkg/queryparser/queryfilterextractor/queryfilterextractor.go
+++ b/pkg/queryparser/queryfilterextractor/queryfilterextractor.go
@@ -18,7 +18,7 @@ var (
ExtractorTypePromQL = ExtractorType{valuer.NewString("qfe_promql")}
)
-// ColumnInfo represents a column in the query
+// ColumnInfo represents a column in the query.
type ColumnInfo struct {
Name string
Alias string
diff --git a/pkg/queryparser/queryparser.go b/pkg/queryparser/queryparser.go
index d016f1123b..22efd0525c 100644
--- a/pkg/queryparser/queryparser.go
+++ b/pkg/queryparser/queryparser.go
@@ -4,14 +4,13 @@ import (
"context"
"github.com/SigNoz/signoz/pkg/queryparser/queryfilterextractor"
- "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
// QueryParser defines the interface for parsing and analyzing queries.
type QueryParser interface {
// AnalyzeQueryFilter extracts filter conditions from a given query string.
- AnalyzeQueryFilter(ctx context.Context, queryType querybuildertypesv5.QueryType, query string) (*queryfilterextractor.FilterResult, error)
+ AnalyzeQueryFilter(ctx context.Context, queryType qbtypes.QueryType, query string) (*queryfilterextractor.FilterResult, error)
// AnalyzeQueryEnvelopes extracts filter conditions from a list of query envelopes.
// Returns a map of query name to FilterResult.
AnalyzeQueryEnvelopes(ctx context.Context, queries []qbtypes.QueryEnvelope) (map[string]*queryfilterextractor.FilterResult, error)
diff --git a/pkg/ruler/rulestore/rulestoretest/rule.go b/pkg/ruler/rulestore/rulestoretest/rule.go
index 0bb32d8864..0f0fd5ce1d 100644
--- a/pkg/ruler/rulestore/rulestoretest/rule.go
+++ b/pkg/ruler/rulestore/rulestoretest/rule.go
@@ -14,13 +14,13 @@ import (
"github.com/SigNoz/signoz/pkg/valuer"
)
-// MockSQLRuleStore is a mock RuleStore backed by sqlmock
+// MockSQLRuleStore is a mock RuleStore backed by sqlmock.
type MockSQLRuleStore struct {
ruleStore ruletypes.RuleStore
mock sqlmock.Sqlmock
}
-// NewMockSQLRuleStore creates a new MockSQLRuleStore with sqlmock
+// NewMockSQLRuleStore creates a new MockSQLRuleStore with sqlmock.
func NewMockSQLRuleStore() *MockSQLRuleStore {
sqlStore := sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherRegexp)
// For tests, we can pass nil for queryParser and use test provider settings
@@ -34,42 +34,42 @@ func NewMockSQLRuleStore() *MockSQLRuleStore {
}
}
-// Mock returns the sqlmock.Sqlmock instance for setting expectations
+// Mock returns the sqlmock.Sqlmock instance for setting expectations.
func (m *MockSQLRuleStore) Mock() sqlmock.Sqlmock {
return m.mock
}
-// CreateRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL
+// CreateRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL.
func (m *MockSQLRuleStore) CreateRule(ctx context.Context, rule *ruletypes.Rule, fn func(context.Context, valuer.UUID) error) (valuer.UUID, error) {
return m.ruleStore.CreateRule(ctx, rule, fn)
}
-// EditRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL
+// EditRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL.
func (m *MockSQLRuleStore) EditRule(ctx context.Context, rule *ruletypes.Rule, fn func(context.Context) error) error {
return m.ruleStore.EditRule(ctx, rule, fn)
}
-// DeleteRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL
+// DeleteRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL.
func (m *MockSQLRuleStore) DeleteRule(ctx context.Context, id valuer.UUID, fn func(context.Context) error) error {
return m.ruleStore.DeleteRule(ctx, id, fn)
}
-// GetStoredRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL
+// GetStoredRule implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL.
func (m *MockSQLRuleStore) GetStoredRule(ctx context.Context, id valuer.UUID) (*ruletypes.Rule, error) {
return m.ruleStore.GetStoredRule(ctx, id)
}
-// GetStoredRules implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL
+// GetStoredRules implements ruletypes.RuleStore - delegates to underlying ruleStore to trigger SQL.
func (m *MockSQLRuleStore) GetStoredRules(ctx context.Context, orgID string) ([]*ruletypes.Rule, error) {
return m.ruleStore.GetStoredRules(ctx, orgID)
}
-// GetStoredRulesByMetricName implements ruletypes.RuleStore - delegates to underlying ruleStore
+// GetStoredRulesByMetricName implements ruletypes.RuleStore - delegates to underlying ruleStore.
func (m *MockSQLRuleStore) GetStoredRulesByMetricName(ctx context.Context, orgID string, metricName string) ([]ruletypes.RuleAlert, error) {
return m.ruleStore.GetStoredRulesByMetricName(ctx, orgID, metricName)
}
-// ExpectCreateRule sets up SQL expectations for CreateRule operation
+// ExpectCreateRule sets up SQL expectations for CreateRule operation.
func (m *MockSQLRuleStore) ExpectCreateRule(rule *ruletypes.Rule) {
rows := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "created_by", "updated_by", "deleted", "data", "org_id"}).
AddRow(rule.ID, rule.CreatedAt, rule.UpdatedAt, rule.CreatedBy, rule.UpdatedBy, rule.Deleted, rule.Data, rule.OrgID)
@@ -80,21 +80,21 @@ func (m *MockSQLRuleStore) ExpectCreateRule(rule *ruletypes.Rule) {
WillReturnRows(rows)
}
-// ExpectEditRule sets up SQL expectations for EditRule operation
+// ExpectEditRule sets up SQL expectations for EditRule operation.
func (m *MockSQLRuleStore) ExpectEditRule(rule *ruletypes.Rule) {
expectedPattern := `UPDATE "rule".+` + rule.UpdatedBy + `.+` + rule.OrgID + `.+WHERE \(id = '` + rule.ID.StringValue() + `'\)`
m.mock.ExpectExec(expectedPattern).
WillReturnResult(sqlmock.NewResult(1, 1))
}
-// ExpectDeleteRule sets up SQL expectations for DeleteRule operation
+// ExpectDeleteRule sets up SQL expectations for DeleteRule operation.
func (m *MockSQLRuleStore) ExpectDeleteRule(ruleID valuer.UUID) {
expectedPattern := `DELETE FROM "rule".+WHERE \(id = '` + ruleID.StringValue() + `'\)`
m.mock.ExpectExec(expectedPattern).
WillReturnResult(sqlmock.NewResult(1, 1))
}
-// ExpectGetStoredRule sets up SQL expectations for GetStoredRule operation
+// ExpectGetStoredRule sets up SQL expectations for GetStoredRule operation.
func (m *MockSQLRuleStore) ExpectGetStoredRule(ruleID valuer.UUID, rule *ruletypes.Rule) {
rows := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "created_by", "updated_by", "deleted", "data", "org_id"}).
AddRow(rule.ID, rule.CreatedAt, rule.UpdatedAt, rule.CreatedBy, rule.UpdatedBy, rule.Deleted, rule.Data, rule.OrgID)
@@ -103,7 +103,7 @@ func (m *MockSQLRuleStore) ExpectGetStoredRule(ruleID valuer.UUID, rule *ruletyp
WillReturnRows(rows)
}
-// ExpectGetStoredRules sets up SQL expectations for GetStoredRules operation
+// ExpectGetStoredRules sets up SQL expectations for GetStoredRules operation.
func (m *MockSQLRuleStore) ExpectGetStoredRules(orgID string, rules []*ruletypes.Rule) {
rows := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "created_by", "updated_by", "deleted", "data", "org_id"})
for _, rule := range rules {
@@ -114,7 +114,7 @@ func (m *MockSQLRuleStore) ExpectGetStoredRules(orgID string, rules []*ruletypes
WillReturnRows(rows)
}
-// ExpectGetStoredRulesByMetricName sets up SQL expectations for GetStoredRulesByMetricName operation
+// ExpectGetStoredRulesByMetricName sets up SQL expectations for GetStoredRulesByMetricName operation.
func (m *MockSQLRuleStore) ExpectGetStoredRulesByMetricName(orgID string, metricName string, rules []*ruletypes.Rule) {
rows := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "created_by", "updated_by", "deleted", "data", "org_id"})
for _, rule := range rules {
@@ -125,7 +125,7 @@ func (m *MockSQLRuleStore) ExpectGetStoredRulesByMetricName(orgID string, metric
WillReturnRows(rows)
}
-// AssertExpectations asserts that all SQL expectations were met
+// AssertExpectations asserts that all SQL expectations were met.
func (m *MockSQLRuleStore) AssertExpectations() error {
return m.mock.ExpectationsWereMet()
}
diff --git a/pkg/sqlmigration/037_add_trace_funnels.go b/pkg/sqlmigration/037_add_trace_funnels.go
index 99a885b1cf..36612cd6e4 100644
--- a/pkg/sqlmigration/037_add_trace_funnels.go
+++ b/pkg/sqlmigration/037_add_trace_funnels.go
@@ -10,7 +10,7 @@ import (
"github.com/uptrace/bun/migrate"
)
-// funnel Core Data Structure (funnel and funnelStep)
+// funnel Core Data Structure (funnel and funnelStep).
type funnel struct {
bun.BaseModel `bun:"table:trace_funnel"`
types.Identifiable // funnel id
diff --git a/pkg/sqlmigration/069_update_cloud_integration_index.go b/pkg/sqlmigration/069_update_cloud_integration_index.go
index dd25f7a345..f97a169d22 100644
--- a/pkg/sqlmigration/069_update_cloud_integration_index.go
+++ b/pkg/sqlmigration/069_update_cloud_integration_index.go
@@ -205,7 +205,7 @@ func groupCloudIntegrationRows(rows []*cloudIntegrationRow) []duplicateGroup {
return groups
}
-// mergeCloudIntegrationConfigs unions the EnabledRegions from all rows in the group into the keeper's config and updates
+// mergeCloudIntegrationConfigs unions the EnabledRegions from all rows in the group into the keeper's config and updates.
func mergeCloudIntegrationConfigs(ctx context.Context, tx bun.Tx, group duplicateGroup) error {
regionSet := make(map[string]struct{})
diff --git a/pkg/sqlstore/sqlitesqlstore/dialect.go b/pkg/sqlstore/sqlitesqlstore/dialect.go
index 9e267a0eef..5e5c731659 100644
--- a/pkg/sqlstore/sqlitesqlstore/dialect.go
+++ b/pkg/sqlstore/sqlitesqlstore/dialect.go
@@ -343,9 +343,10 @@ func (dialect *dialect) UpdatePrimaryKey(ctx context.Context, bun bun.IDB, oldMo
}
fkReference := ""
- if reference == Org {
+ switch reference {
+ case Org:
fkReference = OrgReference
- } else if reference == User {
+ case User:
fkReference = UserReference
}
@@ -399,9 +400,10 @@ func (dialect *dialect) AddPrimaryKey(ctx context.Context, bun bun.IDB, oldModel
}
fkReference := ""
- if reference == Org {
+ switch reference {
+ case Org:
fkReference = OrgReference
- } else if reference == User {
+ case User:
fkReference = UserReference
}
diff --git a/pkg/sqlstore/sqlstoretest/provider.go b/pkg/sqlstore/sqlstoretest/provider.go
index 97adf272c1..c35be2b388 100644
--- a/pkg/sqlstore/sqlstoretest/provider.go
+++ b/pkg/sqlstore/sqlstoretest/provider.go
@@ -30,11 +30,12 @@ func New(config sqlstore.Config, matcher sqlmock.QueryMatcher) *Provider {
var bunDB *bun.DB
- if config.Provider == "sqlite" {
+ switch config.Provider {
+ case "sqlite":
bunDB = bun.NewDB(db, sqlitedialect.New())
- } else if config.Provider == "postgres" {
+ case "postgres":
bunDB = bun.NewDB(db, pgdialect.New())
- } else {
+ default:
panic(errors.NewInvalidInputf(errors.CodeInvalidInput, "provider %q is not supported", config.Provider))
}
diff --git a/pkg/telemetrylogs/const.go b/pkg/telemetrylogs/const.go
index 89b36cc016..8340fc1c02 100644
--- a/pkg/telemetrylogs/const.go
+++ b/pkg/telemetrylogs/const.go
@@ -11,12 +11,12 @@ import (
const (
- // Internal Columns
+ // Internal Columns.
LogsV2IDColumn = "id"
LogsV2TimestampBucketStartColumn = "ts_bucket_start"
LogsV2ResourceFingerPrintColumn = "resource_fingerprint"
- // Intrinsic Columns
+ // Intrinsic Columns.
LogsV2TimestampColumn = "timestamp"
LogsV2ObservedTimestampColumn = "observed_timestamp"
LogsV2BodyColumn = "body"
@@ -30,7 +30,7 @@ const (
LogsV2ScopeNameColumn = "scope_name"
LogsV2ScopeVersionColumn = "scope_version"
- // Contextual Columns
+ // Contextual Columns.
LogsV2AttributesStringColumn = "attributes_string"
LogsV2AttributesNumberColumn = "attributes_number"
LogsV2AttributesBoolColumn = "attributes_bool"
diff --git a/pkg/telemetrylogs/field_mapper.go b/pkg/telemetrylogs/field_mapper.go
index 958acaedfb..6deecd5878 100644
--- a/pkg/telemetrylogs/field_mapper.go
+++ b/pkg/telemetrylogs/field_mapper.go
@@ -398,7 +398,7 @@ func (m *fieldMapper) ColumnExpressionFor(
return fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(fieldExpression), field.Name), nil
}
-// buildFieldForJSON builds the field expression for body JSON fields using arrayConcat pattern
+// buildFieldForJSON builds the field expression for body JSON fields using arrayConcat pattern.
func (m *fieldMapper) buildFieldForJSON(key *telemetrytypes.TelemetryFieldKey) (string, error) {
plan := key.JSONPlan
if len(plan) == 0 {
@@ -454,7 +454,7 @@ func (m *fieldMapper) buildFieldForJSON(key *telemetrytypes.TelemetryFieldKey) (
return arrayConcatExpr, nil
}
-// buildArrayConcat builds the arrayConcat pattern directly from the tree structure
+// buildArrayConcat builds the arrayConcat pattern directly from the tree structure.
func (m *fieldMapper) buildArrayConcat(plan telemetrytypes.JSONAccessPlan) (string, error) {
if len(plan) == 0 {
return "", errors.Newf(errors.TypeInternal, CodeGroupByPlanEmpty, "group by plan is empty while building arrayConcat")
@@ -485,7 +485,7 @@ func (m *fieldMapper) buildArrayConcat(plan telemetrytypes.JSONAccessPlan) (stri
return arrayFlattenExpr, nil
}
-// buildArrayMap builds the arrayMap expression for a specific branch, handling all sub-branches
+// buildArrayMap builds the arrayMap expression for a specific branch, handling all sub-branches.
func (m *fieldMapper) buildArrayMap(currentNode *telemetrytypes.JSONAccessNode, branchType telemetrytypes.JSONAccessBranchType) (string, error) {
if currentNode == nil {
return "", errors.Newf(errors.TypeInternal, CodeCurrentNodeNil, "current node is nil while building arrayMap")
diff --git a/pkg/telemetrylogs/filter_expr_like_warning_test.go b/pkg/telemetrylogs/filter_expr_like_warning_test.go
index 7914a40780..4db0d1dc96 100644
--- a/pkg/telemetrylogs/filter_expr_like_warning_test.go
+++ b/pkg/telemetrylogs/filter_expr_like_warning_test.go
@@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/require"
)
-// TestLikeAndILikeWithoutWildcards_Warns Tests that LIKE/ILIKE without wildcards add warnings and include docs URL
+// TestLikeAndILikeWithoutWildcards_Warns Tests that LIKE/ILIKE without wildcards add warnings and include docs URL.
func TestLikeAndILikeWithoutWildcards_Warns(t *testing.T) {
ctx := context.Background()
fm := NewFieldMapper()
@@ -49,7 +49,7 @@ func TestLikeAndILikeWithoutWildcards_Warns(t *testing.T) {
}
}
-// TestLikeAndILikeWithWildcards_NoWarn Tests that LIKE/ILIKE with wildcards do not add warnings
+// TestLikeAndILikeWithWildcards_NoWarn Tests that LIKE/ILIKE with wildcards do not add warnings.
func TestLikeAndILikeWithWildcards_NoWarn(t *testing.T) {
fm := NewFieldMapper()
cb := NewConditionBuilder(fm)
diff --git a/pkg/telemetrylogs/filter_expr_logs_body_json_test.go b/pkg/telemetrylogs/filter_expr_logs_body_json_test.go
index ac43125471..9b2f3e21b3 100644
--- a/pkg/telemetrylogs/filter_expr_logs_body_json_test.go
+++ b/pkg/telemetrylogs/filter_expr_logs_body_json_test.go
@@ -13,7 +13,7 @@ import (
"github.com/stretchr/testify/require"
)
-// TestFilterExprLogsBodyJSON tests a comprehensive set of query patterns for body JSON search
+// TestFilterExprLogsBodyJSON tests a comprehensive set of query patterns for body JSON search.
func TestFilterExprLogsBodyJSON(t *testing.T) {
fm := NewFieldMapper()
cb := NewConditionBuilder(fm)
diff --git a/pkg/telemetrylogs/filter_expr_logs_test.go b/pkg/telemetrylogs/filter_expr_logs_test.go
index 1513968da4..63ff938cc7 100644
--- a/pkg/telemetrylogs/filter_expr_logs_test.go
+++ b/pkg/telemetrylogs/filter_expr_logs_test.go
@@ -15,7 +15,7 @@ import (
"github.com/stretchr/testify/require"
)
-// TestFilterExprLogs tests a comprehensive set of query patterns for logs search
+// TestFilterExprLogs tests a comprehensive set of query patterns for logs search.
func TestFilterExprLogs(t *testing.T) {
releaseTime := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
ctx := context.Background()
@@ -2427,7 +2427,7 @@ func TestFilterExprLogs(t *testing.T) {
}
}
-// TestFilterExprLogs tests a comprehensive set of query patterns for logs search
+// TestFilterExprLogs tests a comprehensive set of query patterns for logs search.
func TestFilterExprLogsConflictNegation(t *testing.T) {
fm := NewFieldMapper()
cb := NewConditionBuilder(fm)
diff --git a/pkg/telemetrylogs/json_condition_builder.go b/pkg/telemetrylogs/json_condition_builder.go
index abb3459227..00edfc26be 100644
--- a/pkg/telemetrylogs/json_condition_builder.go
+++ b/pkg/telemetrylogs/json_condition_builder.go
@@ -31,7 +31,7 @@ func NewJSONConditionBuilder(key *telemetrytypes.TelemetryFieldKey, valueType te
return &jsonConditionBuilder{key: key, valueType: telemetrytypes.MappingFieldDataTypeToJSONDataType[valueType]}
}
-// BuildCondition builds the full WHERE condition for body_v2 JSON paths
+// BuildCondition builds the full WHERE condition for body_v2 JSON paths.
func (c *jsonConditionBuilder) buildJSONCondition(operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (string, error) {
conditions := []string{}
for _, node := range c.key.JSONPlan {
@@ -51,7 +51,7 @@ func (c *jsonConditionBuilder) buildJSONCondition(operator qbtypes.FilterOperato
return baseCond, nil
}
-// emitPlannedCondition handles paths with array traversal
+// emitPlannedCondition handles paths with array traversal.
func (c *jsonConditionBuilder) emitPlannedCondition(node *telemetrytypes.JSONAccessNode, operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (string, error) {
// Build traversal + terminal recursively per-hop
compiled, err := c.recurseArrayHops(node, operator, value, sb)
@@ -61,7 +61,7 @@ func (c *jsonConditionBuilder) emitPlannedCondition(node *telemetrytypes.JSONAcc
return compiled, nil
}
-// buildTerminalCondition creates the innermost condition
+// buildTerminalCondition creates the innermost condition.
func (c *jsonConditionBuilder) buildTerminalCondition(node *telemetrytypes.JSONAccessNode, operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (string, error) {
if node.TerminalConfig.ElemType.IsArray {
conditions := []string{}
@@ -100,11 +100,11 @@ func (c *jsonConditionBuilder) buildTerminalCondition(node *telemetrytypes.JSONA
}
// buildPrimitiveTerminalCondition builds the condition if the terminal node is a primitive type
-// it handles the data type collisions and utilizes indexes for the condition if available
+// it handles the data type collisions and utilizes indexes for the condition if available.
func (c *jsonConditionBuilder) buildPrimitiveTerminalCondition(node *telemetrytypes.JSONAccessNode, operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (string, error) {
fieldPath := node.FieldPath()
conditions := []string{}
- var formattedValue any = value
+ var formattedValue = value
if operator.IsStringSearchOperator() {
formattedValue = querybuilder.FormatValueForContains(value)
}
@@ -171,7 +171,7 @@ func (c *jsonConditionBuilder) buildPrimitiveTerminalCondition(node *telemetryty
return conditions[0], nil
}
-// buildArrayMembershipCondition handles array membership checks
+// buildArrayMembershipCondition handles array membership checks.
func (c *jsonConditionBuilder) buildArrayMembershipCondition(node *telemetrytypes.JSONAccessNode, operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (string, error) {
arrayPath := node.FieldPath()
localKeyCopy := *node.TerminalConfig.Key
@@ -208,7 +208,7 @@ func (c *jsonConditionBuilder) buildArrayMembershipCondition(node *telemetrytype
return fmt.Sprintf("arrayExists(%s -> %s, %s)", key, op, arrayExpr), nil
}
-// recurseArrayHops recursively builds array traversal conditions
+// recurseArrayHops recursively builds array traversal conditions.
func (c *jsonConditionBuilder) recurseArrayHops(current *telemetrytypes.JSONAccessNode, operator qbtypes.FilterOperator, value any, sb *sqlbuilder.SelectBuilder) (string, error) {
if current == nil {
return "", errors.NewInternalf(CodeArrayNavigationFailed, "navigation failed, current node is nil")
diff --git a/pkg/telemetrylogs/statement_builder.go b/pkg/telemetrylogs/statement_builder.go
index d951143067..20cfdf6f6b 100644
--- a/pkg/telemetrylogs/statement_builder.go
+++ b/pkg/telemetrylogs/statement_builder.go
@@ -52,7 +52,7 @@ func NewLogQueryStatementBuilder(
}
}
-// Build builds a SQL query for logs based on the given parameters
+// Build builds a SQL query for logs based on the given parameters.
func (b *logQueryStatementBuilder) Build(
ctx context.Context,
start uint64,
@@ -234,7 +234,7 @@ func (b *logQueryStatementBuilder) adjustKey(key *telemetrytypes.TelemetryFieldK
return querybuilder.AdjustKey(key, keys, nil)
}
-// buildListQuery builds a query for list panel type
+// buildListQuery builds a query for list panel type.
func (b *logQueryStatementBuilder) buildListQuery(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
@@ -373,10 +373,10 @@ func (b *logQueryStatementBuilder) buildTimeSeriesQuery(
return nil, err
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", gb.TelemetryFieldKey.Name))
+ fieldNames = append(fieldNames, fmt.Sprintf("`%s`", gb.Name))
}
// Aggregations
@@ -487,7 +487,7 @@ func (b *logQueryStatementBuilder) buildTimeSeriesQuery(
return stmt, nil
}
-// buildScalarQuery builds a query for scalar panel type
+// buildScalarQuery builds a query for scalar panel type.
func (b *logQueryStatementBuilder) buildScalarQuery(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
@@ -520,7 +520,7 @@ func (b *logQueryStatementBuilder) buildScalarQuery(
return nil, err
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
}
@@ -603,7 +603,7 @@ func (b *logQueryStatementBuilder) buildScalarQuery(
return stmt, nil
}
-// buildFilterCondition builds SQL condition from filter expression
+// buildFilterCondition builds SQL condition from filter expression.
func (b *logQueryStatementBuilder) addFilterCondition(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
diff --git a/pkg/telemetrylogs/test_data.go b/pkg/telemetrylogs/test_data.go
index 0463edd9e5..23980359e0 100644
--- a/pkg/telemetrylogs/test_data.go
+++ b/pkg/telemetrylogs/test_data.go
@@ -7,7 +7,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
-// Helper function to limit string length for display
+// Helper function to limit string length for display.
func limitString(s string, maxLen int) string {
s = strings.ReplaceAll(s, "\n", " ")
s = strings.ReplaceAll(s, "\t", " ")
@@ -18,7 +18,7 @@ func limitString(s string, maxLen int) string {
return s[:maxLen-3] + "..."
}
-// Function to build a complete field key map for testing all scenarios
+// Function to build a complete field key map for testing all scenarios.
func buildCompleteFieldKeyMap(releaseTime time.Time) map[string][]*telemetrytypes.TelemetryFieldKey {
keysMap := map[string][]*telemetrytypes.TelemetryFieldKey{
"service.name": {
diff --git a/pkg/telemetrymetadata/backward_compat_keys.go b/pkg/telemetrymetadata/backward_compat_keys.go
index ddecfc31bf..a5e2895e84 100644
--- a/pkg/telemetrymetadata/backward_compat_keys.go
+++ b/pkg/telemetrymetadata/backward_compat_keys.go
@@ -12,12 +12,12 @@ var (
"url.full": "http.url",
}
- // LogsBackwardCompatKeys contains bidirectional mappings for logs
- // Currently empty, can be extended in the future
+ // LogsBackwardCompatKeys contains bidirectional mappings for logs.
+ // Currently empty, can be extended in the future.
LogsBackwardCompatKeys = BackwardCompatibleKeyMap{}
- // MetricsBackwardCompatKeys contains bidirectional mappings for metrics
- // Currently empty, can be extended in the future
+ // MetricsBackwardCompatKeys contains bidirectional mappings for metrics.
+ // Currently empty, can be extended in the future.
MetricsBackwardCompatKeys = BackwardCompatibleKeyMap{}
)
diff --git a/pkg/telemetrymetadata/body_json_metadata.go b/pkg/telemetrymetadata/body_json_metadata.go
index ae7797dc4f..26eff8b717 100644
--- a/pkg/telemetrymetadata/body_json_metadata.go
+++ b/pkg/telemetrymetadata/body_json_metadata.go
@@ -47,7 +47,7 @@ var (
// - For lookup: set to 0 (no limit needed for single path)
// - For metadata API: set to desired pagination limit
//
-// searchOperator: LIKE for pattern matching, EQUAL for exact match
+// searchOperator: LIKE for pattern matching, EQUAL for exact match.
func (t *telemetryMetaStore) fetchBodyJSONPaths(ctx context.Context,
fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, []string, bool, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
@@ -303,7 +303,7 @@ func (t *telemetryMetaStore) ListLogsJSONIndexes(ctx context.Context, filters ..
return indexes, nil
}
-// TODO(Piyush): Remove this if not used in future
+// TODO(Piyush): Remove this if not used in future.
func (t *telemetryMetaStore) ListJSONValues(ctx context.Context, path string, limit int) (*telemetrytypes.TelemetryFieldValues, bool, error) {
ctx = withTelemetryContext(ctx, "ListJSONValues")
path = CleanPathPrefixes(path)
@@ -520,7 +520,7 @@ func (t *telemetryMetaStore) GetPromotedPaths(ctx context.Context, paths ...stri
return promotedPaths, nil
}
-// TODO(Piyush): Remove this function
+// TODO(Piyush): Remove this function.
func CleanPathPrefixes(path string) string {
path = strings.TrimPrefix(path, telemetrytypes.BodyJSONStringSearchPrefix)
path = strings.TrimPrefix(path, telemetrylogs.BodyV2ColumnPrefix)
diff --git a/pkg/telemetrymetadata/metadata.go b/pkg/telemetrymetadata/metadata.go
index 4b5bf57ddd..8aad15cfd2 100644
--- a/pkg/telemetrymetadata/metadata.go
+++ b/pkg/telemetrymetadata/metadata.go
@@ -123,7 +123,7 @@ func NewTelemetryMetaStore(
return t
}
-// tracesTblStatementToFieldKeys returns materialised attribute/resource/scope keys from the traces table
+// tracesTblStatementToFieldKeys returns materialised attribute/resource/scope keys from the traces table.
func (t *telemetryMetaStore) tracesTblStatementToFieldKeys(ctx context.Context) ([]*telemetrytypes.TelemetryFieldKey, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalTraces.StringValue(),
@@ -149,7 +149,7 @@ func (t *telemetryMetaStore) tracesTblStatementToFieldKeys(ctx context.Context)
return materialisedKeys, nil
}
-// getTracesKeys returns the keys from the spans that match the field selection criteria
+// getTracesKeys returns the keys from the spans that match the field selection criteria.
func (t *telemetryMetaStore) getTracesKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalTraces.StringValue(),
@@ -186,7 +186,6 @@ func (t *telemetryMetaStore) getTracesKeys(ctx context.Context, fieldKeySelector
var limit int
searchTexts := []string{}
- dataTypes := []telemetrytypes.FieldDataType{}
conds := []string{}
for _, fieldKeySelector := range fieldKeySelectors {
@@ -208,9 +207,6 @@ func (t *telemetryMetaStore) getTracesKeys(ctx context.Context, fieldKeySelector
}
searchTexts = append(searchTexts, fieldKeySelector.Name)
- if fieldKeySelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
- dataTypes = append(dataTypes, fieldKeySelector.FieldDataType)
- }
// now look at the field context
// we don't write most of intrinsic fields to keys table
// for this reason we don't want to apply tagType if the field context
@@ -329,7 +325,7 @@ func (t *telemetryMetaStore) getTracesKeys(ctx context.Context, fieldKeySelector
return keys, complete, nil
}
-// logsTblStatementToFieldKeys returns materialised attribute/resource/scope keys from the logs table
+// logsTblStatementToFieldKeys returns materialised attribute/resource/scope keys from the logs table.
func (t *telemetryMetaStore) logsTblStatementToFieldKeys(ctx context.Context) ([]*telemetrytypes.TelemetryFieldKey, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
@@ -355,7 +351,7 @@ func (t *telemetryMetaStore) logsTblStatementToFieldKeys(ctx context.Context) ([
return materialisedKeys, nil
}
-// getLogsKeys returns the keys from the spans that match the field selection criteria
+// getLogsKeys returns the keys from the spans that match the field selection criteria.
func (t *telemetryMetaStore) getLogsKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalLogs.StringValue(),
@@ -506,14 +502,10 @@ func (t *telemetryMetaStore) getLogsKeys(ctx context.Context, fieldKeySelectors
keys := []*telemetrytypes.TelemetryFieldKey{}
rowCount := 0
searchTexts := []string{}
- dataTypes := []telemetrytypes.FieldDataType{}
- // Collect search texts and data types for static field matching
+ // Collect search texts for static field matching
for _, fieldKeySelector := range fieldKeySelectors {
searchTexts = append(searchTexts, fieldKeySelector.Name)
- if fieldKeySelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
- dataTypes = append(dataTypes, fieldKeySelector.FieldDataType)
- }
}
for rows.Next() {
@@ -615,7 +607,7 @@ func getPriorityForContext(ctx telemetrytypes.FieldContext) int {
}
}
-// getMetricsKeys returns the keys from the metrics that match the field selection criteria
+// getMetricsKeys returns the keys from the metrics that match the field selection criteria.
func (t *telemetryMetaStore) getMetricsKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalMetrics.StringValue(),
@@ -722,7 +714,7 @@ func (t *telemetryMetaStore) getMetricsKeys(ctx context.Context, fieldKeySelecto
return keys, complete, nil
}
-// getMeterKeys returns the keys from the meter metrics that match the field selection criteria
+// getMeterKeys returns the keys from the meter metrics that match the field selection criteria.
func (t *telemetryMetaStore) getMeterSourceMetricKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalMetrics.StringValue(),
@@ -798,7 +790,7 @@ func (t *telemetryMetaStore) getMeterSourceMetricKeys(ctx context.Context, field
}
-// applyBackwardCompatibleKeys adds backward compatible key aliases to the map
+// applyBackwardCompatibleKeys adds backward compatible key aliases to the map.
func applyBackwardCompatibleKeys(mapOfKeys map[string][]*telemetrytypes.TelemetryFieldKey) {
// Get backward compatible keys for all signals
backwardCompatKeysBySignal := map[telemetrytypes.Signal]BackwardCompatibleKeyMap{
@@ -885,7 +877,7 @@ func matchesSelectorName(selectorName, target string, matchType telemetrytypes.F
func (t *telemetryMetaStore) GetKeys(ctx context.Context, fieldKeySelector *telemetrytypes.FieldKeySelector) (map[string][]*telemetrytypes.TelemetryFieldKey, bool, error) {
var keys []*telemetrytypes.TelemetryFieldKey
- var complete bool = true
+ var complete = true
var err error
selectors := []*telemetrytypes.FieldKeySelector{}
@@ -1197,12 +1189,13 @@ func (t *telemetryMetaStore) getSpanFieldValues(ctx context.Context, fieldValueS
}
if fieldValueSelector.Value != "" {
- if fieldValueSelector.FieldDataType == telemetrytypes.FieldDataTypeString {
+ switch fieldValueSelector.FieldDataType {
+ case telemetrytypes.FieldDataTypeString:
sb.Where(sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"))
- } else if fieldValueSelector.FieldDataType == telemetrytypes.FieldDataTypeNumber {
+ case telemetrytypes.FieldDataTypeNumber:
sb.Where(sb.IsNotNull("number_value"))
sb.Where(sb.ILike("toString(number_value)", "%"+escapeForLike(fieldValueSelector.Value)+"%"))
- } else if fieldValueSelector.FieldDataType == telemetrytypes.FieldDataTypeUnspecified {
+ case telemetrytypes.FieldDataTypeUnspecified:
// or b/w string and number
sb.Where(sb.Or(
sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"),
@@ -1284,12 +1277,13 @@ func (t *telemetryMetaStore) getLogFieldValues(ctx context.Context, fieldValueSe
}
if fieldValueSelector.Value != "" {
- if fieldValueSelector.FieldDataType == telemetrytypes.FieldDataTypeString {
+ switch fieldValueSelector.FieldDataType {
+ case telemetrytypes.FieldDataTypeString:
sb.Where(sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"))
- } else if fieldValueSelector.FieldDataType == telemetrytypes.FieldDataTypeNumber {
+ case telemetrytypes.FieldDataTypeNumber:
sb.Where(sb.IsNotNull("number_value"))
sb.Where(sb.ILike("toString(number_value)", "%"+escapeForLike(fieldValueSelector.Value)+"%"))
- } else if fieldValueSelector.FieldDataType == telemetrytypes.FieldDataTypeUnspecified {
+ case telemetrytypes.FieldDataTypeUnspecified:
// or b/w string and number
sb.Where(sb.Or(
sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"),
@@ -1344,7 +1338,7 @@ func (t *telemetryMetaStore) getLogFieldValues(ctx context.Context, fieldValueSe
return values, complete, nil
}
-// getMetricFieldValues returns field values and whether the result is complete
+// getMetricFieldValues returns field values and whether the result is complete.
func (t *telemetryMetaStore) getMetricFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector) (*telemetrytypes.TelemetryFieldValues, bool, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalMetrics.StringValue(),
@@ -1437,7 +1431,7 @@ func (t *telemetryMetaStore) getMetricFieldValues(ctx context.Context, fieldValu
return values, complete, nil
}
-// getIntrinsicMetricFieldValues returns values, isSearchComplete, error
+// getIntrinsicMetricFieldValues returns values, isSearchComplete, error.
func (t *telemetryMetaStore) getIntrinsicMetricFieldValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector, limit int) (*telemetrytypes.TelemetryFieldValues, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.TelemetrySignal: telemetrytypes.SignalMetrics.StringValue(),
@@ -1619,10 +1613,10 @@ func populateAllUnspecifiedValues(allUnspecifiedValues *telemetrytypes.Telemetry
return complete
}
-// GetAllValues returns all values and whether the result is complete
+// GetAllValues returns all values and whether the result is complete.
func (t *telemetryMetaStore) GetAllValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector) (*telemetrytypes.TelemetryFieldValues, bool, error) {
values := &telemetrytypes.TelemetryFieldValues{}
- var complete bool = true
+ var complete = true
var err error
limit := fieldValueSelector.Limit
diff --git a/pkg/telemetrymetadata/metadata_test.go b/pkg/telemetrymetadata/metadata_test.go
index 3f8f0ecb60..cd8dd833b2 100644
--- a/pkg/telemetrymetadata/metadata_test.go
+++ b/pkg/telemetrymetadata/metadata_test.go
@@ -175,9 +175,10 @@ func TestApplyBackwardCompatibleKeys(t *testing.T) {
hasTraces := false
hasLogs := false
for _, key := range tt.inputKeys {
- if key.Signal == telemetrytypes.SignalTraces {
+ switch key.Signal {
+ case telemetrytypes.SignalTraces:
hasTraces = true
- } else if key.Signal == telemetrytypes.SignalLogs {
+ case telemetrytypes.SignalLogs:
hasLogs = true
}
}
diff --git a/pkg/telemetrymetadata/stmt_parse.go b/pkg/telemetrymetadata/stmt_parse.go
index deff14f82a..8cd92300aa 100644
--- a/pkg/telemetrymetadata/stmt_parse.go
+++ b/pkg/telemetrymetadata/stmt_parse.go
@@ -7,7 +7,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
-// TelemetryFieldVisitor is an AST visitor for extracting telemetry fields
+// TelemetryFieldVisitor is an AST visitor for extracting telemetry fields.
type TelemetryFieldVisitor struct {
parser.DefaultASTVisitor
Fields []*telemetrytypes.TelemetryFieldKey
@@ -19,7 +19,7 @@ func NewTelemetryFieldVisitor() *TelemetryFieldVisitor {
}
}
-// VisitColumnDef is called when visiting a column definition
+// VisitColumnDef is called when visiting a column definition.
func (v *TelemetryFieldVisitor) VisitColumnDef(expr *parser.ColumnDef) error {
// Check if this is a materialized column with DEFAULT expression
if expr.DefaultExpr == nil {
diff --git a/pkg/telemetrymeter/statement_builder.go b/pkg/telemetrymeter/statement_builder.go
index f53eedea89..905f19bdd0 100644
--- a/pkg/telemetrymeter/statement_builder.go
+++ b/pkg/telemetrymeter/statement_builder.go
@@ -338,7 +338,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(
wrapped := sqlbuilder.NewSelectBuilder()
wrapped.Select("ts")
for _, g := range query.GroupBy {
- wrapped.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ wrapped.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", telemetrymetrics.RateTmpl))
wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))
@@ -349,7 +349,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(
wrapped := sqlbuilder.NewSelectBuilder()
wrapped.Select("ts")
for _, g := range query.GroupBy {
- wrapped.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ wrapped.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", telemetrymetrics.IncreaseTmpl))
wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))
@@ -379,7 +379,7 @@ func (b *meterQueryStatementBuilder) buildSpatialAggregationCTE(
sb.Select("ts")
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
sb.SelectMore(fmt.Sprintf("%s(per_series_value) AS value", query.Aggregations[0].SpaceAggregation.StringValue()))
sb.From("__temporal_aggregation_cte")
diff --git a/pkg/telemetrymeter/tables.go b/pkg/telemetrymeter/tables.go
index 8aa0c3157a..53a7bbd1ed 100644
--- a/pkg/telemetrymeter/tables.go
+++ b/pkg/telemetrymeter/tables.go
@@ -21,7 +21,7 @@ var (
// when the query requests for almost 1 day, but not exactly 1 day, we need to add an offset to the end time
// to make sure that we are using the correct table
// this is because the start gets adjusted to the nearest step interval and uses the 5m table for 4m step interval
- // leading to time series that doesn't best represent the rate of change
+ // leading to time series that doesn't best represent the rate of change.
offsetBucket = uint64(1 * time.Hour.Milliseconds())
)
@@ -29,7 +29,7 @@ var (
// we have two tables for samples
// 1. distributed_samples
// 2. distributed_samples_agg_1d - for queries with time range above or equal to 30 days
-// if the `timeAggregation` is `count_distinct` we can't use the aggregated tables because they don't support it
+// if the `timeAggregation` is `count_distinct` we can't use the aggregated tables because they don't support it.
func WhichSamplesTableToUse(
start, end uint64,
metricType metrictypes.Type,
diff --git a/pkg/telemetrymetrics/statement_builder.go b/pkg/telemetrymetrics/statement_builder.go
index e2c82569f7..65e97ffddf 100644
--- a/pkg/telemetrymetrics/statement_builder.go
+++ b/pkg/telemetrymetrics/statement_builder.go
@@ -63,7 +63,7 @@ func GetKeySelectors(query qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation])
for idx := range query.GroupBy {
groupBy := query.GroupBy[idx]
- selectors := querybuilder.QueryStringToKeysSelectors(groupBy.TelemetryFieldKey.Name)
+ selectors := querybuilder.QueryStringToKeysSelectors(groupBy.Name)
keySelectors = append(keySelectors, selectors...)
}
@@ -126,7 +126,7 @@ func (b *MetricQueryStatementBuilder) buildPipelineStatement(
// add le in the group by if doesn't exist
leExists := false
for _, g := range query.GroupBy {
- if g.TelemetryFieldKey.Name == "le" {
+ if g.Name == "le" {
leExists = true
break
}
@@ -218,7 +218,7 @@ func (b *MetricQueryStatementBuilder) buildTemporalAggDeltaFastPath(
stepSec,
))
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
aggCol, err := AggregationColumnForSamplesTable(
@@ -355,7 +355,7 @@ func (b *MetricQueryStatementBuilder) buildTemporalAggDelta(
stepSec,
))
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
aggCol, err := AggregationColumnForSamplesTable(start, end, query.Aggregations[0].Type, query.Aggregations[0].Temporality, query.Aggregations[0].TimeAggregation, query.Aggregations[0].TableHints)
@@ -401,7 +401,7 @@ func (b *MetricQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(
stepSec,
))
for _, g := range query.GroupBy {
- baseSb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ baseSb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
aggCol, err := AggregationColumnForSamplesTable(start, end, query.Aggregations[0].Type, query.Aggregations[0].Temporality, query.Aggregations[0].TimeAggregation, query.Aggregations[0].TableHints)
@@ -429,7 +429,7 @@ func (b *MetricQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(
wrapped := sqlbuilder.NewSelectBuilder()
wrapped.Select("ts")
for _, g := range query.GroupBy {
- wrapped.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ wrapped.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", RateTmpl))
wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))
@@ -440,7 +440,7 @@ func (b *MetricQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(
wrapped := sqlbuilder.NewSelectBuilder()
wrapped.Select("ts")
for _, g := range query.GroupBy {
- wrapped.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ wrapped.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", IncreaseTmpl))
wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))
@@ -466,7 +466,7 @@ func (b *MetricQueryStatementBuilder) buildTemporalAggForMultipleTemporalities(
stepSec,
))
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
aggForDeltaTemporality, err := AggregationColumnForSamplesTable(start, end, query.Aggregations[0].Type, metrictypes.Delta, query.Aggregations[0].TimeAggregation, query.Aggregations[0].TableHints)
@@ -527,7 +527,7 @@ func (b *MetricQueryStatementBuilder) buildSpatialAggregationCTE(
sb.Select("ts")
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
sb.SelectMore(fmt.Sprintf("%s(per_series_value) AS value", query.Aggregations[0].SpaceAggregation.StringValue()))
sb.From("__temporal_aggregation_cte")
@@ -563,7 +563,7 @@ func (b *MetricQueryStatementBuilder) BuildFinalSelect(
quantile := query.Aggregations[0].SpaceAggregation.Percentile()
sb.Select("ts")
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
sb.SelectMore(fmt.Sprintf(
"histogramQuantile(arrayMap(x -> toFloat64(x), groupArray(le)), groupArray(value), %.3f) AS value",
@@ -581,7 +581,7 @@ func (b *MetricQueryStatementBuilder) BuildFinalSelect(
sb.Select("ts")
for _, g := range query.GroupBy {
- sb.SelectMore(fmt.Sprintf("`%s`", g.TelemetryFieldKey.Name))
+ sb.SelectMore(fmt.Sprintf("`%s`", g.Name))
}
aggQuery, err := AggregationQueryForHistogramCountWithParams(query.Aggregations[0].ComparisonSpaceAggregationParam)
diff --git a/pkg/telemetrymetrics/tables.go b/pkg/telemetrymetrics/tables.go
index ff87e62d2f..e390b63268 100644
--- a/pkg/telemetrymetrics/tables.go
+++ b/pkg/telemetrymetrics/tables.go
@@ -41,12 +41,12 @@ var (
// when the query requests for almost 1 day, but not exactly 1 day, we need to add an offset to the end time
// to make sure that we are using the correct table
// this is because the start gets adjusted to the nearest step interval and uses the 5m table for 4m step interval
- // leading to time series that doesn't best represent the rate of change
+ // leading to time series that doesn't best represent the rate of change.
offsetBucket = uint64(60 * time.Minute.Milliseconds())
)
// WhichTSTableToUse returns adjusted start, adjusted end, distributed table name, local table name
-// in that order
+// in that order.
func WhichTSTableToUse(
start, end uint64,
tableHints *metrictypes.MetricTableHints,
@@ -129,7 +129,7 @@ func CountExpressionForSamplesTable(tableName string) string {
// 1. distributed_samples_v4
// 2. distributed_samples_v4_agg_5m - for queries with time range above or equal to 1 day and less than 1 week
// 3. distributed_samples_v4_agg_30m - for queries with time range above or equal to 1 week
-// if the `timeAggregation` is `count_distinct` we can't use the aggregated tables because they don't support it
+// if the `timeAggregation` is `count_distinct` we can't use the aggregated tables because they don't support it.
func WhichSamplesTableToUse(
start, end uint64,
metricType metrictypes.Type,
diff --git a/pkg/telemetrystore/clickhousetelemetrystore/rows.go b/pkg/telemetrystore/clickhousetelemetrystore/rows.go
index a27a4f4fc6..3be2965f1f 100644
--- a/pkg/telemetrystore/clickhousetelemetrystore/rows.go
+++ b/pkg/telemetrystore/clickhousetelemetrystore/rows.go
@@ -25,7 +25,7 @@ func (r *rowsWithHooks) Close() error {
// mark as closed and run the onClose hook
r.closed = true
- if err := r.Rows.Err(); err != nil {
+ if err := r.Err(); err != nil {
r.event.Err = err
}
closeErr := r.Rows.Close()
diff --git a/pkg/telemetrystore/telemetrystoretest/provider.go b/pkg/telemetrystore/telemetrystoretest/provider.go
index 37dd3c4f45..19722190b0 100644
--- a/pkg/telemetrystore/telemetrystoretest/provider.go
+++ b/pkg/telemetrystore/telemetrystoretest/provider.go
@@ -9,12 +9,12 @@ import (
var _ telemetrystore.TelemetryStore = (*Provider)(nil)
-// Provider represents a mock telemetry store provider for testing
+// Provider represents a mock telemetry store provider for testing.
type Provider struct {
clickhouseDB cmock.ClickConnMockCommon
}
-// New creates a new mock telemetry store provider
+// New creates a new mock telemetry store provider.
func New(_ telemetrystore.Config, matcher sqlmock.QueryMatcher) *Provider {
clickhouseDB, err := cmock.NewClickHouseWithQueryMatcher(&clickhouse.Options{}, matcher)
if err != nil {
@@ -26,17 +26,17 @@ func New(_ telemetrystore.Config, matcher sqlmock.QueryMatcher) *Provider {
}
}
-// ClickhouseDB returns the mock Clickhouse connection
+// ClickhouseDB returns the mock Clickhouse connection.
func (p *Provider) ClickhouseDB() clickhouse.Conn {
return p.clickhouseDB.(clickhouse.Conn)
}
-// Cluster returns the cluster name
+// Cluster returns the cluster name.
func (p *Provider) Cluster() string {
return "cluster"
}
-// Mock returns the underlying Clickhouse mock instance for setting expectations
+// Mock returns the underlying Clickhouse mock instance for setting expectations.
func (p *Provider) Mock() cmock.ClickConnMockCommon {
return p.clickhouseDB
}
diff --git a/pkg/telemetrytraces/field_mapper.go b/pkg/telemetrytraces/field_mapper.go
index 111fe3da14..3fa681e171 100644
--- a/pkg/telemetrytraces/field_mapper.go
+++ b/pkg/telemetrytraces/field_mapper.go
@@ -122,7 +122,7 @@ var (
"attribute_string_peer$$service_exists": {Name: "attribute_string_peer$$service_exists", Type: schema.ColumnTypeBool},
}
- // TODO(srikanthccv): remove this mapping
+ // TODO(srikanthccv): remove this mapping.
oldToNew = map[string]string{
// deprecated intrinsic -> new intrinsic
"traceID": "trace_id",
@@ -237,7 +237,7 @@ func (m *defaultFieldMapper) ColumnFor(
}
// FieldFor returns the table field name for the given key if it exists
-// otherwise it returns qbtypes.ErrColumnNotFound
+// otherwise it returns qbtypes.ErrColumnNotFound.
func (m *defaultFieldMapper) FieldFor(
ctx context.Context,
startNs, endNs uint64,
@@ -314,7 +314,7 @@ func (m *defaultFieldMapper) FieldFor(
}
// ColumnExpressionFor returns the column expression for the given field
-// if it exists otherwise it returns qbtypes.ErrColumnNotFound
+// if it exists otherwise it returns qbtypes.ErrColumnNotFound.
func (m *defaultFieldMapper) ColumnExpressionFor(
ctx context.Context,
startNs, endNs uint64,
diff --git a/pkg/telemetrytraces/statement_builder.go b/pkg/telemetrytraces/statement_builder.go
index 5693ec3b85..35daebd9c2 100644
--- a/pkg/telemetrytraces/statement_builder.go
+++ b/pkg/telemetrytraces/statement_builder.go
@@ -54,7 +54,7 @@ func NewTraceQueryStatementBuilder(
}
}
-// Build builds a SQL query for traces based on the given parameters
+// Build builds a SQL query for traces based on the given parameters.
func (b *traceQueryStatementBuilder) Build(
ctx context.Context,
start uint64,
@@ -272,7 +272,7 @@ func (b *traceQueryStatementBuilder) adjustKey(key *telemetrytypes.TelemetryFiel
return actions
}
-// buildListQuery builds a query for list panel type
+// buildListQuery builds a query for list panel type.
func (b *traceQueryStatementBuilder) buildListQuery(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
@@ -502,10 +502,10 @@ func (b *traceQueryStatementBuilder) buildTimeSeriesQuery(
if err != nil {
return nil, err
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", gb.TelemetryFieldKey.Name))
+ fieldNames = append(fieldNames, fmt.Sprintf("`%s`", gb.Name))
}
// Aggregations
@@ -612,7 +612,7 @@ func (b *traceQueryStatementBuilder) buildTimeSeriesQuery(
return stmt, nil
}
-// buildScalarQuery builds a query for scalar panel type
+// buildScalarQuery builds a query for scalar panel type.
func (b *traceQueryStatementBuilder) buildScalarQuery(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
@@ -644,7 +644,7 @@ func (b *traceQueryStatementBuilder) buildScalarQuery(
if err != nil {
return nil, err
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
}
@@ -727,7 +727,7 @@ func (b *traceQueryStatementBuilder) buildScalarQuery(
return stmt, nil
}
-// buildFilterCondition builds SQL condition from filter expression
+// buildFilterCondition builds SQL condition from filter expression.
func (b *traceQueryStatementBuilder) addFilterCondition(
ctx context.Context,
sb *sqlbuilder.SelectBuilder,
diff --git a/pkg/telemetrytraces/stmt_builder_test.go b/pkg/telemetrytraces/stmt_builder_test.go
index 75598ca45e..ac5a4246eb 100644
--- a/pkg/telemetrytraces/stmt_builder_test.go
+++ b/pkg/telemetrytraces/stmt_builder_test.go
@@ -1461,10 +1461,10 @@ func TestAdjustKeys(t *testing.T) {
if c.expectedGroupBy != nil {
require.Len(t, c.query.GroupBy, len(c.expectedGroupBy))
for i, expected := range c.expectedGroupBy {
- require.Equal(t, expected.TelemetryFieldKey.Name, c.query.GroupBy[i].TelemetryFieldKey.Name, "group by field %d name should match", i)
- require.Equal(t, expected.TelemetryFieldKey.FieldContext, c.query.GroupBy[i].TelemetryFieldKey.FieldContext, "group by field %d context should match", i)
- require.Equal(t, expected.TelemetryFieldKey.FieldDataType, c.query.GroupBy[i].TelemetryFieldKey.FieldDataType, "group by field %d data type should match", i)
- require.Equal(t, expected.TelemetryFieldKey.Materialized, c.query.GroupBy[i].TelemetryFieldKey.Materialized, "group by field %d materialized should match", i)
+ require.Equal(t, expected.Name, c.query.GroupBy[i].Name, "group by field %d name should match", i)
+ require.Equal(t, expected.FieldContext, c.query.GroupBy[i].FieldContext, "group by field %d context should match", i)
+ require.Equal(t, expected.FieldDataType, c.query.GroupBy[i].FieldDataType, "group by field %d data type should match", i)
+ require.Equal(t, expected.Materialized, c.query.GroupBy[i].Materialized, "group by field %d materialized should match", i)
}
}
@@ -1472,10 +1472,10 @@ func TestAdjustKeys(t *testing.T) {
if c.expectedOrder != nil {
require.Len(t, c.query.Order, len(c.expectedOrder))
for i, expected := range c.expectedOrder {
- require.Equal(t, expected.Key.TelemetryFieldKey.Name, c.query.Order[i].Key.TelemetryFieldKey.Name, "order field %d name should match", i)
- require.Equal(t, expected.Key.TelemetryFieldKey.FieldContext, c.query.Order[i].Key.TelemetryFieldKey.FieldContext, "order field %d context should match", i)
- require.Equal(t, expected.Key.TelemetryFieldKey.FieldDataType, c.query.Order[i].Key.TelemetryFieldKey.FieldDataType, "order field %d data type should match", i)
- require.Equal(t, expected.Key.TelemetryFieldKey.Materialized, c.query.Order[i].Key.TelemetryFieldKey.Materialized, "order field %d materialized should match", i)
+ require.Equal(t, expected.Key.Name, c.query.Order[i].Key.Name, "order field %d name should match", i)
+ require.Equal(t, expected.Key.FieldContext, c.query.Order[i].Key.FieldContext, "order field %d context should match", i)
+ require.Equal(t, expected.Key.FieldDataType, c.query.Order[i].Key.FieldDataType, "order field %d data type should match", i)
+ require.Equal(t, expected.Key.Materialized, c.query.Order[i].Key.Materialized, "order field %d materialized should match", i)
require.Equal(t, expected.Direction, c.query.Order[i].Direction, "order field %d direction should match", i)
}
}
diff --git a/pkg/telemetrytraces/trace_id_extractor.go b/pkg/telemetrytraces/trace_id_extractor.go
index ddd4a15478..e1ed948439 100644
--- a/pkg/telemetrytraces/trace_id_extractor.go
+++ b/pkg/telemetrytraces/trace_id_extractor.go
@@ -31,7 +31,7 @@ func ExtractTraceIDsFromFilter(filterExpr string) ([]string, bool) {
return extractor.traceIDs, extractor.found
}
-// Visit dispatches to the specific visit method based on node type
+// Visit dispatches to the specific visit method based on node type.
func (e *traceIDExtractor) Visit(tree antlr.ParseTree) any {
if tree == nil {
return nil
diff --git a/pkg/telemetrytraces/trace_operator_cte_builder.go b/pkg/telemetrytraces/trace_operator_cte_builder.go
index ecfd150e9d..a1c7026480 100644
--- a/pkg/telemetrytraces/trace_operator_cte_builder.go
+++ b/pkg/telemetrytraces/trace_operator_cte_builder.go
@@ -109,7 +109,7 @@ func (b *traceOperatorCTEBuilder) build(ctx context.Context, requestType qbtypes
}, nil
}
-// Will be used in Indirect descendant Query, will not be used in any other query
+// Will be used in Indirect descendant Query, will not be used in any other query.
func (b *traceOperatorCTEBuilder) buildAllSpansCTE(ctx context.Context) {
sb := sqlbuilder.NewSelectBuilder()
sb.Select("*")
@@ -513,7 +513,7 @@ func (b *traceOperatorCTEBuilder) getKeySelectors() []*telemetrytypes.FieldKeySe
}
for _, gb := range b.operator.GroupBy {
- selectors := querybuilder.QueryStringToKeysSelectors(gb.TelemetryFieldKey.Name)
+ selectors := querybuilder.QueryStringToKeysSelectors(gb.Name)
keySelectors = append(keySelectors, selectors...)
}
@@ -565,11 +565,11 @@ func (b *traceOperatorCTEBuilder) buildTimeSeriesQuery(ctx context.Context, sele
return nil, errors.NewInvalidInputf(
errors.CodeInvalidInput,
"failed to map group by field '%s': %v",
- gb.TelemetryFieldKey.Name,
+ gb.Name,
err,
)
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
}
@@ -605,7 +605,7 @@ func (b *traceOperatorCTEBuilder) buildTimeSeriesQuery(ctx context.Context, sele
if len(b.operator.GroupBy) > 0 {
groupByKeys := make([]string, len(b.operator.GroupBy))
for i, gb := range b.operator.GroupBy {
- groupByKeys[i] = fmt.Sprintf("`%s`", gb.TelemetryFieldKey.Name)
+ groupByKeys[i] = fmt.Sprintf("`%s`", gb.Name)
}
sb.GroupBy(groupByKeys...)
}
@@ -678,11 +678,11 @@ func (b *traceOperatorCTEBuilder) buildTraceQuery(ctx context.Context, selectFro
return nil, errors.NewInvalidInputf(
errors.CodeInvalidInput,
"failed to map group by field '%s': %v",
- gb.TelemetryFieldKey.Name,
+ gb.Name,
err,
)
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
}
@@ -735,7 +735,7 @@ func (b *traceOperatorCTEBuilder) buildTraceQuery(ctx context.Context, selectFro
if len(b.operator.GroupBy) > 0 {
groupByKeys := make([]string, len(b.operator.GroupBy))
for i, gb := range b.operator.GroupBy {
- groupByKeys[i] = fmt.Sprintf("`%s`", gb.TelemetryFieldKey.Name)
+ groupByKeys[i] = fmt.Sprintf("`%s`", gb.Name)
}
sb.GroupBy(groupByKeys...)
}
@@ -821,11 +821,11 @@ func (b *traceOperatorCTEBuilder) buildScalarQuery(ctx context.Context, selectFr
return nil, errors.NewInvalidInputf(
errors.CodeInvalidInput,
"failed to map group by field '%s': %v",
- gb.TelemetryFieldKey.Name,
+ gb.Name,
err,
)
}
- colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.TelemetryFieldKey.Name)
+ colExpr := fmt.Sprintf("toString(%s) AS `%s`", expr, gb.Name)
allGroupByArgs = append(allGroupByArgs, args...)
sb.SelectMore(colExpr)
}
@@ -860,7 +860,7 @@ func (b *traceOperatorCTEBuilder) buildScalarQuery(ctx context.Context, selectFr
if len(b.operator.GroupBy) > 0 {
groupByKeys := make([]string, len(b.operator.GroupBy))
for i, gb := range b.operator.GroupBy {
- groupByKeys[i] = fmt.Sprintf("`%s`", gb.TelemetryFieldKey.Name)
+ groupByKeys[i] = fmt.Sprintf("`%s`", gb.Name)
}
sb.GroupBy(groupByKeys...)
}
diff --git a/pkg/transition/v5_to_v4.go b/pkg/transition/v5_to_v4.go
index 60e13c12c2..2c467d37ff 100644
--- a/pkg/transition/v5_to_v4.go
+++ b/pkg/transition/v5_to_v4.go
@@ -7,7 +7,7 @@ import (
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
-// ConvertV5TimeSeriesDataToV4Result converts v5 TimeSeriesData to v4 Result
+// ConvertV5TimeSeriesDataToV4Result converts v5 TimeSeriesData to v4 Result.
func ConvertV5TimeSeriesDataToV4Result(v5Data *qbtypes.TimeSeriesData) *v3.Result {
if v5Data == nil {
return nil
@@ -85,7 +85,7 @@ func ConvertV5TimeSeriesDataToV4Result(v5Data *qbtypes.TimeSeriesData) *v3.Resul
return result
}
-// ConvertV5TimeSeriesDataSliceToV4Results converts a slice of v5 TimeSeriesData to v4 QueryRangeResponse
+// ConvertV5TimeSeriesDataSliceToV4Results converts a slice of v5 TimeSeriesData to v4 QueryRangeResponse.
func ConvertV5TimeSeriesDataSliceToV4Results(v5DataSlice []*qbtypes.TimeSeriesData) *v3.QueryRangeResponse {
response := &v3.QueryRangeResponse{
ResultType: "matrix", // Time series data is typically "matrix" type
diff --git a/pkg/types/alertmanagertypes/channel.go b/pkg/types/alertmanagertypes/channel.go
index 8e8beea380..7f15c4d782 100644
--- a/pkg/types/alertmanagertypes/channel.go
+++ b/pkg/types/alertmanagertypes/channel.go
@@ -20,7 +20,7 @@ var (
)
var (
- // Regular expression to match anything before "_configs"
+ // Regular expression to match anything before "_configs".
receiverTypeRegex = regexp.MustCompile(`^(.+)_configs`)
)
diff --git a/pkg/types/alertmanagertypes/config.go b/pkg/types/alertmanagertypes/config.go
index b5323ea9cf..4675a46f27 100644
--- a/pkg/types/alertmanagertypes/config.go
+++ b/pkg/types/alertmanagertypes/config.go
@@ -31,7 +31,7 @@ var (
)
type (
- // GlobalConfig is the type for the global configuration
+ // GlobalConfig is the type for the global configuration.
GlobalConfig = config.GlobalConfig
)
@@ -52,7 +52,7 @@ type StoreableConfig struct {
OrgID string `bun:"org_id"`
}
-// Config is the type for the entire alertmanager configuration
+// Config is the type for the entire alertmanager configuration.
type Config struct {
// alertmanagerConfig is the actual alertmanager configuration referenced from the upstream
alertmanagerConfig *config.Config
diff --git a/pkg/types/alertmanagertypes/expressionroute.go b/pkg/types/alertmanagertypes/expressionroute.go
index 858864c681..a8c4390ef1 100644
--- a/pkg/types/alertmanagertypes/expressionroute.go
+++ b/pkg/types/alertmanagertypes/expressionroute.go
@@ -73,7 +73,7 @@ var (
PolicyBasedExpression = ExpressionKind{valuer.NewString("policy")}
)
-// RoutePolicy represents the database model for expression routes
+// RoutePolicy represents the database model for expression routes.
type RoutePolicy struct {
bun.BaseModel `bun:"table:route_policy"`
types.Identifiable
diff --git a/pkg/types/authtypes/authn.go b/pkg/types/authtypes/authn.go
index ce3271f4e3..1559e032b8 100644
--- a/pkg/types/authtypes/authn.go
+++ b/pkg/types/authtypes/authn.go
@@ -101,11 +101,11 @@ func NewCallbackIdentity(name string, email valuer.Email, orgID valuer.UUID, sta
}
func newDomainIDForState(domainID valuer.UUID) string {
- return strings.Replace(domainID.String(), "-", ":", -1)
+ return strings.ReplaceAll(domainID.String(), "-", ":")
}
func newDomainIDFromState(state string) (valuer.UUID, error) {
- return valuer.NewUUID(strings.Replace(state, ":", "-", -1))
+ return valuer.NewUUID(strings.ReplaceAll(state, ":", "-"))
}
func (typ Identity) MarshalBinary() ([]byte, error) {
diff --git a/pkg/types/cloudintegrationtypes/service.go b/pkg/types/cloudintegrationtypes/service.go
index 70273fb13d..2bac5d9d24 100644
--- a/pkg/types/cloudintegrationtypes/service.go
+++ b/pkg/types/cloudintegrationtypes/service.go
@@ -162,7 +162,7 @@ type AWSLogsStrategy struct {
// Dashboard represents a dashboard definition for cloud integration.
// This is used to show available pre-made dashboards for a service,
-// hence has additional fields like id, title and description
+// hence has additional fields like id, title and description.
type Dashboard struct {
ID string `json:"id"`
Title string `json:"title"`
diff --git a/pkg/types/dashboardtypes/dashboard.go b/pkg/types/dashboardtypes/dashboard.go
index fb60d7681b..1d569a0469 100644
--- a/pkg/types/dashboardtypes/dashboard.go
+++ b/pkg/types/dashboardtypes/dashboard.go
@@ -203,11 +203,12 @@ func addStatsFromStorableDashboard(dashboard *StorableDashboard, stats map[strin
for _, queryData := range builderQueryData {
data, ok := queryData.(map[string]interface{})
if ok {
- if data["dataSource"] == "traces" {
+ switch data["dataSource"] {
+ case "traces":
stats["dashboard.panels.traces.count"] = stats["dashboard.panels.traces.count"].(int64) + 1
- } else if data["dataSource"] == "metrics" {
+ case "metrics":
stats["dashboard.panels.metrics.count"] = stats["dashboard.panels.metrics.count"].(int64) + 1
- } else if data["dataSource"] == "logs" {
+ case "logs":
stats["dashboard.panels.logs.count"] = stats["dashboard.panels.logs.count"].(int64) + 1
}
}
@@ -349,7 +350,7 @@ func (dashboard *Dashboard) GetWidgetQuery(startTime, endTime, widgetIndex uint6
return nil, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodeDashboardInvalidData, "invalid dashboard data")
}
- if widgetIndex < 0 || int(widgetIndex) >= len(data.Widgets) {
+ if int(widgetIndex) >= len(data.Widgets) {
return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardInvalidInput, "widget with index %v doesn't exist", widgetIndex)
}
diff --git a/pkg/types/factor_api_key.go b/pkg/types/factor_api_key.go
index e1eb05db69..5613400fa4 100644
--- a/pkg/types/factor_api_key.go
+++ b/pkg/types/factor_api_key.go
@@ -124,7 +124,7 @@ func NewStorableAPIKey(name string, userID valuer.UUID, role Role, expiresAt int
func NewGettableAPIKeyFromStorableAPIKey(storableAPIKey *StorableAPIKeyUser) *GettableAPIKey {
lastUsed := storableAPIKey.LastUsed.Unix()
- if storableAPIKey.LastUsed == storableAPIKey.CreatedAt {
+ if storableAPIKey.LastUsed.Equal(storableAPIKey.CreatedAt) {
lastUsed = 0
}
return &GettableAPIKey{
diff --git a/pkg/types/featuretypes/context.go b/pkg/types/featuretypes/context.go
index a265a43278..b067c66f81 100644
--- a/pkg/types/featuretypes/context.go
+++ b/pkg/types/featuretypes/context.go
@@ -5,12 +5,12 @@ import (
"github.com/open-feature/go-sdk/openfeature"
)
-// A concrete wrapper around the openfeature.EvaluationContext
+// A concrete wrapper around the openfeature.EvaluationContext.
type FlaggerEvaluationContext struct {
ctx openfeature.EvaluationContext
}
-// Creates a new FlaggerEvaluationContext with given details
+// Creates a new FlaggerEvaluationContext with given details.
func NewFlaggerEvaluationContext(orgID valuer.UUID) FlaggerEvaluationContext {
ctx := openfeature.NewTargetlessEvaluationContext(map[string]any{
"orgId": orgID.String(),
diff --git a/pkg/types/featuretypes/feature.go b/pkg/types/featuretypes/feature.go
index 585fcf40ae..7ace4fb228 100644
--- a/pkg/types/featuretypes/feature.go
+++ b/pkg/types/featuretypes/feature.go
@@ -13,7 +13,7 @@ var (
ErrCodeFeatureNotFound = errors.MustNewCode("feature_not_found")
)
-// A concrete type for a feature flag
+// A concrete type for a feature flag.
type Feature struct {
// Name of the feature
Name Name `json:"name"`
@@ -29,7 +29,7 @@ type Feature struct {
Variants map[Name]FeatureVariant `json:"variants"`
}
-// A concrete type for a feature flag variant
+// A concrete type for a feature flag variant.
type FeatureVariant struct {
// Name of the variant
Variant Name `json:"variant"`
@@ -47,7 +47,7 @@ type GettableFeature struct {
ResolvedValue any `json:"resolvedValue"`
}
-// This is the helper function to get the value of a variant of a feature
+// This is the helper function to get the value of a variant of a feature.
func VariantValue[T any](feature *Feature, variant Name) (t T, detail openfeature.ProviderResolutionDetail, err error) {
value, ok := feature.Variants[variant]
if !ok {
@@ -79,7 +79,7 @@ func VariantValue[T any](feature *Feature, variant Name) (t T, detail openfeatur
return
}
-// This is the helper function to get the variant by value for the given feature
+// This is the helper function to get the variant by value for the given feature.
func VariantByValue[T comparable](feature *Feature, value T) (featureVariant *FeatureVariant, err error) {
// technically this method should not be called for object kind
diff --git a/pkg/types/featuretypes/kind.go b/pkg/types/featuretypes/kind.go
index 779c756c51..6b7fec4056 100644
--- a/pkg/types/featuretypes/kind.go
+++ b/pkg/types/featuretypes/kind.go
@@ -2,7 +2,7 @@ package featuretypes
import "github.com/SigNoz/signoz/pkg/valuer"
-// A concrete type for a feature flag kind
+// A concrete type for a feature flag kind.
type Kind struct{ valuer.String }
var (
diff --git a/pkg/types/featuretypes/registry.go b/pkg/types/featuretypes/registry.go
index ca37b3a89c..fb55425b19 100644
--- a/pkg/types/featuretypes/registry.go
+++ b/pkg/types/featuretypes/registry.go
@@ -5,7 +5,7 @@ import (
"github.com/open-feature/go-sdk/openfeature"
)
-// Consumer facing interface for the feature registry
+// Consumer facing interface for the feature registry.
type Registry interface {
// Returns the feature and the resolution detail for the given name
Get(name Name) (*Feature, openfeature.ProviderResolutionDetail, error)
@@ -17,12 +17,12 @@ type Registry interface {
List() []*Feature
}
-// Concrete implementation of the Registry interface
+// Concrete implementation of the Registry interface.
type registry struct {
features map[Name]*Feature
}
-// Validates and builds a new registry from a list of features
+// Validates and builds a new registry from a list of features.
func NewRegistry(features ...*Feature) (Registry, error) {
registry := &registry{features: make(map[Name]*Feature)}
diff --git a/pkg/types/featuretypes/stage.go b/pkg/types/featuretypes/stage.go
index 597b681f9a..a9754676ef 100644
--- a/pkg/types/featuretypes/stage.go
+++ b/pkg/types/featuretypes/stage.go
@@ -2,19 +2,19 @@ package featuretypes
import "github.com/SigNoz/signoz/pkg/valuer"
-// A concrete type for a feature flag stage
+// A concrete type for a feature flag stage.
type Stage struct{ valuer.String }
var (
- // Used when the feature is experimental
+ // Used when the feature is experimental.
StageExperimental = Stage{valuer.NewString("experimental")}
- // Used when the feature works and in preview stage but is not ready for production
+ // Used when the feature works and in preview stage but is not ready for production.
StagePreview = Stage{valuer.NewString("preview")}
- // Used when the feature is stable and ready for production
+ // Used when the feature is stable and ready for production.
StageStable = Stage{valuer.NewString("stable")}
- // Used when the feature is deprecated and will be removed in the future
+ // Used when the feature is deprecated and will be removed in the future.
StageDeprecated = Stage{valuer.NewString("deprecated")}
)
diff --git a/pkg/types/instrumentationtypes/duration.go b/pkg/types/instrumentationtypes/duration.go
index 9f2a1f0698..9a058a5104 100644
--- a/pkg/types/instrumentationtypes/duration.go
+++ b/pkg/types/instrumentationtypes/duration.go
@@ -37,7 +37,7 @@ func DurationBucket(from, to uint64) string {
return ">=1M"
}
-// ToNanoSecs takes epoch and returns it in ns
+// ToNanoSecs takes epoch and returns it in ns.
func ToNanoSecs(epoch uint64) uint64 {
temp := epoch
count := 0
diff --git a/pkg/types/instrumentationtypes/keys.go b/pkg/types/instrumentationtypes/keys.go
index 2c4479468f..c546b890ee 100644
--- a/pkg/types/instrumentationtypes/keys.go
+++ b/pkg/types/instrumentationtypes/keys.go
@@ -14,7 +14,7 @@ const (
TelemetrySignal = "telemetry.signal"
// QueryDuration is the query time-range bucket label (e.g. "<1h", "<24h").
QueryDuration = "query.duration"
- // PanelType is the panel type: "timeseries", "list", "value"
+ // PanelType is the panel type: "timeseries", "list", "value".
PanelType = "panel.type"
// QueryType is the query type: "promql", "clickhouse_sql", "builder_query".
QueryType = "query.type"
diff --git a/pkg/types/integrationtypes/integration.go b/pkg/types/integrationtypes/integration.go
index 09d94cd47e..957ddd47e6 100644
--- a/pkg/types/integrationtypes/integration.go
+++ b/pkg/types/integrationtypes/integration.go
@@ -36,7 +36,7 @@ type InstalledIntegration struct {
type InstalledIntegrationConfig map[string]any
-// For serializing from db
+// For serializing from db.
func (c *InstalledIntegrationConfig) Scan(src any) error {
var data []byte
switch v := src.(type) {
@@ -51,7 +51,7 @@ func (c *InstalledIntegrationConfig) Scan(src any) error {
return json.Unmarshal(data, c)
}
-// For serializing to db
+// For serializing to db.
func (c *InstalledIntegrationConfig) Value() (driver.Value, error) {
filterSetJson, err := json.Marshal(c)
if err != nil {
@@ -127,7 +127,7 @@ type AccountConfig struct {
EnabledRegions []string `json:"regions"`
}
-// For serializing from db
+// For serializing from db.
func (c *AccountConfig) Scan(src any) error {
var data []byte
switch v := src.(type) {
@@ -142,7 +142,7 @@ func (c *AccountConfig) Scan(src any) error {
return json.Unmarshal(data, c)
}
-// For serializing to db
+// For serializing to db.
func (c *AccountConfig) Value() (driver.Value, error) {
if c == nil {
return nil, errors.NewInternalf(errors.CodeInternal, "cloud account config is nil")
@@ -161,7 +161,7 @@ type AgentReport struct {
Data map[string]any `json:"data"`
}
-// For serializing from db
+// For serializing from db.
func (r *AgentReport) Scan(src any) error {
var data []byte
switch v := src.(type) {
@@ -176,7 +176,7 @@ func (r *AgentReport) Scan(src any) error {
return json.Unmarshal(data, r)
}
-// For serializing to db
+// For serializing to db.
func (r *AgentReport) Value() (driver.Value, error) {
if r == nil {
return nil, errors.NewInternalf(errors.CodeInternal, "agent report is nil")
@@ -216,7 +216,7 @@ type CloudServiceConfig struct {
Metrics *CloudServiceMetricsConfig `json:"metrics,omitempty"`
}
-// For serializing from db
+// For serializing from db.
func (c *CloudServiceConfig) Scan(src any) error {
var data []byte
switch src := src.(type) {
@@ -231,7 +231,7 @@ func (c *CloudServiceConfig) Scan(src any) error {
return json.Unmarshal(data, c)
}
-// For serializing to db
+// For serializing to db.
func (c *CloudServiceConfig) Value() (driver.Value, error) {
if c == nil {
return nil, errors.NewInternalf(errors.CodeInternal, "cloud service config is nil")
diff --git a/pkg/types/licensetypes/license.go b/pkg/types/licensetypes/license.go
index 39b8f5de99..0271828369 100644
--- a/pkg/types/licensetypes/license.go
+++ b/pkg/types/licensetypes/license.go
@@ -23,7 +23,7 @@ type StorableLicense struct {
OrgID valuer.UUID `bun:"org_id,type:text,notnull" json:"orgId"`
}
-// this data excludes ID and Key
+// this data excludes ID and Key.
type License struct {
ID valuer.UUID
Key string
diff --git a/pkg/types/licensetypes/plan.go b/pkg/types/licensetypes/plan.go
index 36782359de..dfa10d3e22 100644
--- a/pkg/types/licensetypes/plan.go
+++ b/pkg/types/licensetypes/plan.go
@@ -5,7 +5,7 @@ import (
)
var (
- // Feature Key
+ // Feature Key.
SSO = valuer.NewString("sso")
Onboarding = valuer.NewString("onboarding")
ChatSupport = valuer.NewString("chat_support")
@@ -15,10 +15,10 @@ var (
AnomalyDetection = valuer.NewString("anomaly_detection")
DotMetricsEnabled = valuer.NewString("dot_metrics_enabled")
- // License State
+ // License State.
LicenseStatusInvalid = valuer.NewString("invalid")
- // Plan
+ // Plan.
PlanNameEnterprise = valuer.NewString("enterprise")
PlanNameBasic = valuer.NewString("basic")
)
diff --git a/pkg/types/metricsexplorertypes/metricsexplorer.go b/pkg/types/metricsexplorertypes/metricsexplorer.go
index ad6a596218..2eb87ee7ef 100644
--- a/pkg/types/metricsexplorertypes/metricsexplorer.go
+++ b/pkg/types/metricsexplorertypes/metricsexplorer.go
@@ -125,12 +125,12 @@ type MetricMetadata struct {
IsMonotonic bool `json:"isMonotonic" required:"true"`
}
-// MarshalBinary implements cachetypes.Cacheable interface
+// MarshalBinary implements cachetypes.Cacheable interface.
func (m *MetricMetadata) MarshalBinary() ([]byte, error) {
return json.Marshal(m)
}
-// UnmarshalBinary implements cachetypes.Cacheable interface
+// UnmarshalBinary implements cachetypes.Cacheable interface.
func (m *MetricMetadata) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, m)
}
diff --git a/pkg/types/metrictypes/metrictypes.go b/pkg/types/metrictypes/metrictypes.go
index 7b0eb02842..755f067e88 100644
--- a/pkg/types/metrictypes/metrictypes.go
+++ b/pkg/types/metrictypes/metrictypes.go
@@ -257,7 +257,7 @@ func (s SpaceAggregation) Percentile() float64 {
}
// MetricTableHints is a struct that contains tables to use instead of the derived tables
-// from the start and end time, for internal use only when we need to override the derived tables
+// from the start and end time, for internal use only when we need to override the derived tables.
type MetricTableHints struct {
TimeSeriesTableName string
SamplesTableName string
diff --git a/pkg/types/parsertypes/queryfilteranalyzer.go b/pkg/types/parsertypes/queryfilteranalyzer.go
index d00ed66b90..d7e066e892 100644
--- a/pkg/types/parsertypes/queryfilteranalyzer.go
+++ b/pkg/types/parsertypes/queryfilteranalyzer.go
@@ -8,13 +8,13 @@ import (
"github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
-// QueryFilterAnalyzeRequest represents the request body for query filter analysis
+// QueryFilterAnalyzeRequest represents the request body for query filter analysis.
type QueryFilterAnalyzeRequest struct {
Query string `json:"query"`
QueryType querybuildertypesv5.QueryType `json:"queryType"`
}
-// UnmarshalJSON implements custom JSON unmarshaling with validation and normalization
+// UnmarshalJSON implements custom JSON unmarshaling with validation and normalization.
func (q *QueryFilterAnalyzeRequest) UnmarshalJSON(data []byte) error {
// Use a temporary struct to avoid infinite recursion
type Alias QueryFilterAnalyzeRequest
@@ -42,7 +42,7 @@ type ColumnInfoResponse struct {
Alias string `json:"columnAlias"`
}
-// QueryFilterAnalyzeResponse represents the response body for query filter analysis
+// QueryFilterAnalyzeResponse represents the response body for query filter analysis.
type QueryFilterAnalyzeResponse struct {
MetricNames []string `json:"metricNames"`
Groups []ColumnInfoResponse `json:"groups"`
diff --git a/pkg/types/pipelinetypes/pipeline.go b/pkg/types/pipelinetypes/pipeline.go
index 2411f3d751..22bb7ac627 100644
--- a/pkg/types/pipelinetypes/pipeline.go
+++ b/pkg/types/pipelinetypes/pipeline.go
@@ -152,14 +152,14 @@ func (op PipelineOperator) MarshalYAML() (interface{}, error) {
alias := Alias(op)
if alias.TraceParser != nil {
- if alias.TraceParser.TraceId != nil && len(alias.TraceParser.TraceId.ParseFrom) < 1 {
- alias.TraceParser.TraceId = nil
+ if alias.TraceId != nil && len(alias.TraceId.ParseFrom) < 1 {
+ alias.TraceId = nil
}
- if alias.TraceParser.SpanId != nil && len(alias.TraceParser.SpanId.ParseFrom) < 1 {
- alias.TraceParser.SpanId = nil
+ if alias.SpanId != nil && len(alias.SpanId.ParseFrom) < 1 {
+ alias.SpanId = nil
}
- if alias.TraceParser.TraceFlags != nil && len(alias.TraceParser.TraceFlags.ParseFrom) < 1 {
- alias.TraceParser.TraceFlags = nil
+ if alias.TraceFlags != nil && len(alias.TraceFlags.ParseFrom) < 1 {
+ alias.TraceFlags = nil
}
}
@@ -204,7 +204,7 @@ type PostablePipeline struct {
Config []PipelineOperator `json:"config"`
}
-// IsValid checks if postable pipeline has all the required params
+// IsValid checks if postable pipeline has all the required params.
func (p *PostablePipeline) IsValid() error {
if p.OrderID == 0 {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "orderId with value > 1 is required")
@@ -324,22 +324,22 @@ func isValidOperator(op PipelineOperator) error {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "field of %s remove operator cannot be empty", op.ID)
}
- hasTraceIdParseFrom := (op.TraceParser.TraceId != nil && op.TraceParser.TraceId.ParseFrom != "")
- hasSpanIdParseFrom := (op.TraceParser.SpanId != nil && op.TraceParser.SpanId.ParseFrom != "")
- hasTraceFlagsParseFrom := (op.TraceParser.TraceFlags != nil && op.TraceParser.TraceFlags.ParseFrom != "")
+ hasTraceIdParseFrom := (op.TraceId != nil && op.TraceId.ParseFrom != "")
+ hasSpanIdParseFrom := (op.SpanId != nil && op.SpanId.ParseFrom != "")
+ hasTraceFlagsParseFrom := (op.TraceFlags != nil && op.TraceFlags.ParseFrom != "")
- if !(hasTraceIdParseFrom || hasSpanIdParseFrom || hasTraceFlagsParseFrom) {
+ if !hasTraceIdParseFrom && !hasSpanIdParseFrom && !hasTraceFlagsParseFrom {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "one of trace_id, span_id, trace_flags of %s trace_parser operator must be present", op.ID)
}
- if hasTraceIdParseFrom && !isValidOtelValue(op.TraceParser.TraceId.ParseFrom) {
- return errors.NewInvalidInputf(errors.CodeInvalidInput, "trace id can't be parsed from %s", op.TraceParser.TraceId.ParseFrom)
+ if hasTraceIdParseFrom && !isValidOtelValue(op.TraceId.ParseFrom) {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "trace id can't be parsed from %s", op.TraceId.ParseFrom)
}
- if hasSpanIdParseFrom && !isValidOtelValue(op.TraceParser.SpanId.ParseFrom) {
- return errors.NewInvalidInputf(errors.CodeInvalidInput, "span id can't be parsed from %s", op.TraceParser.SpanId.ParseFrom)
+ if hasSpanIdParseFrom && !isValidOtelValue(op.SpanId.ParseFrom) {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "span id can't be parsed from %s", op.SpanId.ParseFrom)
}
- if hasTraceFlagsParseFrom && !isValidOtelValue(op.TraceParser.TraceFlags.ParseFrom) {
- return errors.NewInvalidInputf(errors.CodeInvalidInput, "trace flags can't be parsed from %s", op.TraceParser.TraceFlags.ParseFrom)
+ if hasTraceFlagsParseFrom && !isValidOtelValue(op.TraceFlags.ParseFrom) {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "trace flags can't be parsed from %s", op.TraceFlags.ParseFrom)
}
case "retain":
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go b/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go
index 7a151eea30..9e7be9c2ed 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go
@@ -72,10 +72,10 @@ func (s *Step) UnmarshalJSON(b []byte) error {
}
func (s Step) MarshalJSON() ([]byte, error) {
- return json.Marshal(s.Duration.Seconds())
+ return json.Marshal(s.Seconds())
}
-// Copy creates a copy of Step
+// Copy creates a copy of Step.
func (s Step) Copy() Step {
return s
}
@@ -186,7 +186,7 @@ func (f FilterOperator) IsStringSearchOperator() bool {
}
}
-// IsArrayOperator returns true if the operator works with array values only
+// IsArrayOperator returns true if the operator works with array values only.
func (f FilterOperator) IsArrayOperator() bool {
switch f {
case FilterOperatorIn, FilterOperatorNotIn,
@@ -251,7 +251,7 @@ func (ReduceTo) Enum() []any {
// FunctionReduceTo applies the reduceTo operator to a time series and returns a new series with the reduced value
// reduceTo can be one of: last, sum, avg, min, max, count, median
-// if reduceTo is not recognized, the function returns the original series
+// if reduceTo is not recognized, the function returns the original series.
func FunctionReduceTo(result *TimeSeries, reduceTo ReduceTo) *TimeSeries {
if len(result.Values) == 0 {
return result
@@ -297,7 +297,7 @@ func FunctionReduceTo(result *TimeSeries, reduceTo ReduceTo) *TimeSeries {
case ReduceToMin:
// Find minimum value, use its timestamp
- var min float64 = math.Inf(1)
+ var min = math.Inf(1)
var minTimestamp int64
for _, point := range result.Values {
if !math.IsNaN(point.Value) && point.Value < min {
@@ -315,7 +315,7 @@ func FunctionReduceTo(result *TimeSeries, reduceTo ReduceTo) *TimeSeries {
case ReduceToMax:
// Find maximum value, use its timestamp
- var max float64 = math.Inf(-1)
+ var max = math.Inf(-1)
var maxTimestamp int64
for _, point := range result.Values {
if !math.IsNaN(point.Value) && point.Value > max {
@@ -418,7 +418,7 @@ type TraceAggregation struct {
Alias string `json:"alias,omitempty"`
}
-// Copy creates a deep copy of TraceAggregation
+// Copy creates a deep copy of TraceAggregation.
func (t TraceAggregation) Copy() TraceAggregation {
return t
}
@@ -430,7 +430,7 @@ type LogAggregation struct {
Alias string `json:"alias,omitempty"`
}
-// Copy creates a deep copy of LogAggregation
+// Copy creates a deep copy of LogAggregation.
func (l LogAggregation) Copy() LogAggregation {
return l
}
@@ -456,7 +456,7 @@ type MetricAggregation struct {
ReduceTo ReduceTo `json:"reduceTo,omitempty"`
}
-// Copy creates a deep copy of MetricAggregation
+// Copy creates a deep copy of MetricAggregation.
func (m MetricAggregation) Copy() MetricAggregation {
c := m
if m.TableHints != nil {
@@ -475,7 +475,7 @@ type Filter struct {
Expression string `json:"expression"`
}
-// Copy creates a deep copy of Filter
+// Copy creates a deep copy of Filter.
func (f *Filter) Copy() *Filter {
if f == nil {
return nil
@@ -489,7 +489,7 @@ type GroupByKey struct {
telemetrytypes.TelemetryFieldKey
}
-// Copy creates a deep copy of GroupByKey
+// Copy creates a deep copy of GroupByKey.
func (g GroupByKey) Copy() GroupByKey {
return g
}
@@ -499,7 +499,7 @@ type Having struct {
Expression string `json:"expression"`
}
-// Copy creates a deep copy of Having
+// Copy creates a deep copy of Having.
func (h *Having) Copy() *Having {
if h == nil {
return nil
@@ -513,12 +513,12 @@ type OrderByKey struct {
telemetrytypes.TelemetryFieldKey
}
-// Copy creates a deep copy of OrderByKey
+// Copy creates a deep copy of OrderByKey.
func (o OrderByKey) Copy() OrderByKey {
return o
}
-// key to order by
+// key to order by.
type OrderBy struct {
// key to order by
Key OrderByKey `json:"key"`
@@ -526,7 +526,7 @@ type OrderBy struct {
Direction OrderDirection `json:"direction"`
}
-// Copy creates a deep copy of OrderBy
+// Copy creates a deep copy of OrderBy.
func (o OrderBy) Copy() OrderBy {
return OrderBy{
Key: o.Key.Copy(),
@@ -534,7 +534,7 @@ func (o OrderBy) Copy() OrderBy {
}
}
-// secondary aggregation to apply to the query
+// secondary aggregation to apply to the query.
type SecondaryAggregation struct {
// stepInterval of the query
// if not set, it will use the step interval of the primary aggregation
@@ -553,7 +553,7 @@ type SecondaryAggregation struct {
LimitBy *LimitBy `json:"limitBy,omitempty"`
}
-// Copy creates a deep copy of SecondaryAggregation
+// Copy creates a deep copy of SecondaryAggregation.
func (s SecondaryAggregation) Copy() SecondaryAggregation {
c := s
@@ -585,7 +585,7 @@ type FunctionArg struct {
Value any `json:"value"`
}
-// Copy creates a deep copy of FunctionArg
+// Copy creates a deep copy of FunctionArg.
func (f FunctionArg) Copy() FunctionArg {
// value is an interface{}, we keep it as-is
// in practice, it's usually primitives (string, float64, etc)
@@ -600,7 +600,7 @@ type Function struct {
Args []FunctionArg `json:"args,omitempty"`
}
-// Copy creates a deep copy of Function
+// Copy creates a deep copy of Function.
func (f Function) Copy() Function {
c := f
@@ -614,7 +614,7 @@ func (f Function) Copy() Function {
return c
}
-// Validate validates the name and args for the function
+// Validate validates the name and args for the function.
func (f Function) Validate() error {
if err := f.Name.Validate(); err != nil {
return err
@@ -633,7 +633,7 @@ type LimitBy struct {
Value string `json:"value"`
}
-// Copy creates a deep copy of LimitBy
+// Copy creates a deep copy of LimitBy.
func (l *LimitBy) Copy() *LimitBy {
if l == nil {
return nil
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/builder_query.go b/pkg/types/querybuildertypes/querybuildertypesv5/builder_query.go
index dd72c9bbe9..b57d9183b5 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/builder_query.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/builder_query.go
@@ -69,7 +69,7 @@ type QueryBuilderQuery[T any] struct {
ShiftBy int64 `json:"-"`
}
-// Copy creates a deep copy of the QueryBuilderQuery
+// Copy creates a deep copy of the QueryBuilderQuery.
func (q QueryBuilderQuery[T]) Copy() QueryBuilderQuery[T] {
// start with a shallow copy
c := q
@@ -127,7 +127,7 @@ func (q QueryBuilderQuery[T]) Copy() QueryBuilderQuery[T] {
return c
}
-// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields
+// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields.
func (q *QueryBuilderQuery[T]) UnmarshalJSON(data []byte) error {
// Define a type alias to avoid infinite recursion
type Alias QueryBuilderQuery[T]
@@ -146,7 +146,7 @@ func (q *QueryBuilderQuery[T]) UnmarshalJSON(data []byte) error {
return nil
}
-// Normalize normalizes all the field keys in the query
+// Normalize normalizes all the field keys in the query.
func (q *QueryBuilderQuery[T]) Normalize() {
// normalize select fields
@@ -197,7 +197,7 @@ func (q *QueryBuilderQuery[T]) Normalize() {
// 5. special case exphist, there is no need for per series/fingerprint aggregation
// we can directly use the quantilesDDMerge function
//
-// all of this is true only for delta metrics
+// all of this is true only for delta metrics.
func CanShortCircuitDelta(metricAgg MetricAggregation) bool {
if metricAgg.Temporality != metrictypes.Delta {
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/builder_query_test.go b/pkg/types/querybuildertypes/querybuildertypesv5/builder_query_test.go
index ee2ed452df..2cdf4a4378 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/builder_query_test.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/builder_query_test.go
@@ -602,7 +602,7 @@ func TestQueryBuilderQuery_UnmarshalJSON(t *testing.T) {
assert.Equal(t, telemetrytypes.SignalTraces, query.Signal)
assert.Equal(t, int64(300000), query.StepInterval.Milliseconds())
// Source is set in the JSON, so it should be "traces", not SourceUnspecified
- assert.Equal(t, "traces", query.Source.String.StringValue())
+ assert.Equal(t, "traces", query.Source.StringValue())
assert.True(t, query.Disabled)
assert.Equal(t, query.Aggregations[0].Expression, "count()")
assert.Equal(t, query.Aggregations[0].Alias, "span.count")
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/cached.go b/pkg/types/querybuildertypes/querybuildertypesv5/cached.go
index 385521d8f5..ad2c615c09 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/cached.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/cached.go
@@ -33,7 +33,7 @@ func (c *CachedBucket) Clone() *CachedBucket {
}
}
-// CachedData represents the full cached data for a query
+// CachedData represents the full cached data for a query.
type CachedData struct {
Buckets []*CachedBucket `json:"buckets"`
Warnings []string `json:"warnings"`
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/clickhouse_query.go b/pkg/types/querybuildertypes/querybuildertypesv5/clickhouse_query.go
index 00e25a8ba8..523a3b168b 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/clickhouse_query.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/clickhouse_query.go
@@ -11,7 +11,7 @@ type ClickHouseQuery struct {
Legend string `json:"legend,omitempty"`
}
-// Copy creates a deep copy of the ClickHouseQuery
+// Copy creates a deep copy of the ClickHouseQuery.
func (q ClickHouseQuery) Copy() ClickHouseQuery {
return q
}
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/formula.go b/pkg/types/querybuildertypes/querybuildertypesv5/formula.go
index d153fe7de9..658a963b4e 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/formula.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/formula.go
@@ -37,7 +37,7 @@ type QueryBuilderFormula struct {
Legend string `json:"legend,omitempty"`
}
-// Copy creates a deep copy of the QueryBuilderFormula
+// Copy creates a deep copy of the QueryBuilderFormula.
func (f QueryBuilderFormula) Copy() QueryBuilderFormula {
c := f
@@ -62,7 +62,7 @@ func (f QueryBuilderFormula) Copy() QueryBuilderFormula {
return c
}
-// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields
+// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields.
func (f *QueryBuilderFormula) UnmarshalJSON(data []byte) error {
type Alias QueryBuilderFormula
var temp Alias
@@ -73,7 +73,7 @@ func (f *QueryBuilderFormula) UnmarshalJSON(data []byte) error {
return nil
}
-// Validate checks if the QueryBuilderFormula fields are valid
+// Validate checks if the QueryBuilderFormula fields are valid.
func (f QueryBuilderFormula) Validate() error {
// Validate name is not blank
if strings.TrimSpace(f.Name) == "" {
@@ -112,14 +112,14 @@ func (f QueryBuilderFormula) Validate() error {
// small container to store the query name and index or alias reference
// for a variable in the formula expression
-// read below for more details on aggregation references
+// read below for more details on aggregation references.
type aggregationRef struct {
QueryName string
Index *int // Index-based reference (e.g., A.0)
Alias *string // Alias-based reference (e.g., A.my_alias)
}
-// seriesLookup provides lookup for series data
+// seriesLookup provides lookup for series data.
type seriesLookup struct {
// seriesKey -> timestamp -> value
data map[string]map[int64]float64
@@ -142,7 +142,7 @@ type seriesLookup struct {
// To address this, we now evaluate the formula expression in query-service.
// The queries are run in parallel to fetch the results and then on the
// result series, we evaluate the formula expression.
-// This also makes use of any application caching to avoid recomputing on same data
+// This also makes use of any application caching to avoid recomputing on same data.
type FormulaEvaluator struct {
// expression to evaluate, prepared from the expression string with list of
// supported functions https://github.com/SigNoz/govaluate?tab=readme-ov-file#what-operators-and-types-does-this-support
@@ -182,7 +182,7 @@ type FormulaEvaluator struct {
valuesPool sync.Pool
}
-// NewFormulaEvaluator creates a formula evaluator
+// NewFormulaEvaluator creates a formula evaluator.
func NewFormulaEvaluator(expressionStr string, canDefaultZero map[string]bool) (*FormulaEvaluator, error) {
functions := EvalFuncs()
expression, err := govaluate.NewEvaluableExpressionWithFunctions(expressionStr, functions)
@@ -238,7 +238,7 @@ func NewFormulaEvaluator(expressionStr string, canDefaultZero map[string]bool) (
}
// parseAggregationReference parses variable names like "A", "A.0", "A.my_alias"
-// into a aggregationRef container for later use
+// into a aggregationRef container for later use.
func parseAggregationReference(variable string) (aggregationRef, error) {
parts := strings.Split(variable, ".")
@@ -273,7 +273,7 @@ func parseAggregationReference(variable string) (aggregationRef, error) {
return aggregationRef{}, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid aggregation reference %q", variable)
}
-// EvaluateFormula processes multiple time series with proper aggregation handling
+// EvaluateFormula processes multiple time series with proper aggregation handling.
func (fe *FormulaEvaluator) EvaluateFormula(timeSeriesData map[string]*TimeSeriesData) ([]*TimeSeries, error) {
// Build lookup structures for all referenced aggregations
lookup := fe.buildSeriesLookup(timeSeriesData)
@@ -316,7 +316,7 @@ func (fe *FormulaEvaluator) EvaluateFormula(timeSeriesData map[string]*TimeSerie
return resultSeries, nil
}
-// buildSeriesLookup creates lookup structure for all referenced aggregations
+// buildSeriesLookup creates lookup structure for all referenced aggregations.
func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSeriesData) *seriesLookup {
lookup := &seriesLookup{
// data is a map of series key to timestamp to value
@@ -393,7 +393,7 @@ func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSer
return lookup
}
-// buildSeriesKey creates a unique key for a series within a specific aggregation
+// buildSeriesKey creates a unique key for a series within a specific aggregation.
func (fe *FormulaEvaluator) buildSeriesKey(variable string, seriesIndex int, labels []*Label) string {
// Create a deterministic key that includes variable and label information
// Why is variable name needed?
@@ -498,14 +498,14 @@ func (fe *FormulaEvaluator) isSubset(labels1, labels2 []*Label) bool {
return true
}
-// evaluateForLabelSet performs formula evaluation for a specific label set
+// evaluateForLabelSet performs formula evaluation for a specific label set.
func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels []*Label, lookup *seriesLookup) *TimeSeries {
// Find matching series for each variable
variableData := make(map[string]map[int64]float64)
// not every series would have a value for every timestamp
// so we need to collect all timestamps from the series that have a value
// for the variable
- var allTimestamps map[int64]struct{} = make(map[int64]struct{})
+ var allTimestamps = make(map[int64]struct{})
for variable := range fe.aggRefs {
// Find series with matching labels for this variable
@@ -602,7 +602,7 @@ func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels []*Label, lookup *s
}
}
-// EvalFuncs returns mathematical functions
+// EvalFuncs returns mathematical functions.
func EvalFuncs() map[string]govaluate.ExpressionFunction {
funcs := make(map[string]govaluate.ExpressionFunction)
@@ -688,7 +688,7 @@ func EvalFuncs() map[string]govaluate.ExpressionFunction {
return funcs
}
-// GetSupportedFunctions returns the list of supported function names
+// GetSupportedFunctions returns the list of supported function names.
func GetSupportedFunctions() []string {
return []string{
"abs", "exp", "log", "ln", "exp2", "log2", "exp10", "log10",
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/formula_bench_test.go b/pkg/types/querybuildertypes/querybuildertypesv5/formula_bench_test.go
index 4c745a6022..888da1b3f7 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/formula_bench_test.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/formula_bench_test.go
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/require"
)
-// createBenchmarkTimeSeriesData creates test data for benchmarking
+// createBenchmarkTimeSeriesData creates test data for benchmarking.
func createBenchmarkTimeSeriesData(queryName string, numSeries, numPoints int) *TimeSeriesData {
series := make([]*TimeSeries, numSeries)
@@ -61,7 +61,7 @@ func createBenchmarkTimeSeriesData(queryName string, numSeries, numPoints int) *
}
}
-// BenchmarkFormulaEvaluator_10k_Series_300_Points benchmarks the target scenario
+// BenchmarkFormulaEvaluator_10k_Series_300_Points benchmarks the target scenario.
func BenchmarkFormulaEvaluator_10k_Series_300_Points(b *testing.B) {
// Create test data: 10k series, 300 points each
const numSeries = 10000
@@ -99,7 +99,7 @@ func BenchmarkFormulaEvaluator_10k_Series_300_Points(b *testing.B) {
}
}
-// BenchmarkFormulaEvaluator_Scaling tests different scales for comparison
+// BenchmarkFormulaEvaluator_Scaling tests different scales for comparison.
func BenchmarkFormulaEvaluator_1k_Series_300_Points(b *testing.B) {
const numSeries = 1000
const numPoints = 300
@@ -152,7 +152,7 @@ func BenchmarkFormulaEvaluator_5k_Series_300_Points(b *testing.B) {
}
}
-// BenchmarkFormulaEvaluator_Complex_Expression tests more complex math
+// BenchmarkFormulaEvaluator_Complex_Expression tests more complex math.
func BenchmarkFormulaEvaluator_10k_Series_Complex(b *testing.B) {
const numSeries = 10000
const numPoints = 300
@@ -180,7 +180,7 @@ func BenchmarkFormulaEvaluator_10k_Series_Complex(b *testing.B) {
}
}
-// BenchmarkFormulaEvaluator_Memory_Reuse tests object pool efficiency
+// BenchmarkFormulaEvaluator_Memory_Reuse tests object pool efficiency.
func BenchmarkFormulaEvaluator_Memory_Reuse(b *testing.B) {
const numSeries = 1000
const numPoints = 100
@@ -208,7 +208,7 @@ func BenchmarkFormulaEvaluator_Memory_Reuse(b *testing.B) {
}
}
-// Benchmark just the lookup building phase
+// Benchmark just the lookup building phase.
func BenchmarkFormulaEvaluator_LookupBuilding(b *testing.B) {
const numSeries = 10000
const numPoints = 300
@@ -230,7 +230,7 @@ func BenchmarkFormulaEvaluator_LookupBuilding(b *testing.B) {
}
}
-// Benchmark just the evaluation phase (excluding lookup building)
+// Benchmark just the evaluation phase (excluding lookup building).
func BenchmarkFormulaEvaluator_EvaluationOnly(b *testing.B) {
const numSeries = 10000
const numPoints = 300
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/functions.go b/pkg/types/querybuildertypes/querybuildertypesv5/functions.go
index d7874a2dbc..6afcd94c5d 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/functions.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/functions.go
@@ -60,7 +60,7 @@ func (FunctionName) Enum() []any {
}
}
-// Validate checks if the FunctionName is valid and one of the known types
+// Validate checks if the FunctionName is valid and one of the known types.
func (fn FunctionName) Validate() error {
validFunctions := []FunctionName{
FunctionNameCutOffMin,
@@ -100,7 +100,7 @@ func (fn FunctionName) Validate() error {
).WithAdditional(fmt.Sprintf("valid functions are: %s", strings.Join(validFunctionNames, ", ")))
}
-// ApplyFunction applies the given function to the result data
+// ApplyFunction applies the given function to the result data.
func ApplyFunction(fn Function, result *TimeSeries) *TimeSeries {
if len(result.Values) == 0 {
return result
@@ -183,7 +183,7 @@ func ApplyFunction(fn Function, result *TimeSeries) *TimeSeries {
return result
}
-// ValidateArgs validates the arguments for the given function
+// ValidateArgs validates the arguments for the given function.
func (fn Function) ValidateArgs() error {
// Extract the function name and arguments
name := fn.Name
@@ -238,7 +238,7 @@ func (fn Function) ValidateArgs() error {
return nil
}
-// parseFloat64Arg parses an argument to float64
+// parseFloat64Arg parses an argument to float64.
func parseFloat64Arg(value any) (float64, error) {
switch v := value.(type) {
case float64:
@@ -254,7 +254,7 @@ func parseFloat64Arg(value any) (float64, error) {
}
}
-// getEWMAAlpha calculates the alpha value for EWMA functions
+// getEWMAAlpha calculates the alpha value for EWMA functions.
func getEWMAAlpha(name FunctionName, args []FunctionArg) float64 {
// Try to get alpha from arguments first
if len(args) > 0 {
@@ -275,7 +275,7 @@ func getEWMAAlpha(name FunctionName, args []FunctionArg) float64 {
return 0.5 // default
}
-// funcCutOffMin cuts off values below the threshold and replaces them with NaN
+// funcCutOffMin cuts off values below the threshold and replaces them with NaN.
func funcCutOffMin(result *TimeSeries, threshold float64) *TimeSeries {
for idx, point := range result.Values {
if point.Value < threshold {
@@ -286,7 +286,7 @@ func funcCutOffMin(result *TimeSeries, threshold float64) *TimeSeries {
return result
}
-// funcCutOffMax cuts off values above the threshold and replaces them with NaN
+// funcCutOffMax cuts off values above the threshold and replaces them with NaN.
func funcCutOffMax(result *TimeSeries, threshold float64) *TimeSeries {
for idx, point := range result.Values {
if point.Value > threshold {
@@ -297,7 +297,7 @@ func funcCutOffMax(result *TimeSeries, threshold float64) *TimeSeries {
return result
}
-// funcClampMin cuts off values below the threshold and replaces them with the threshold
+// funcClampMin cuts off values below the threshold and replaces them with the threshold.
func funcClampMin(result *TimeSeries, threshold float64) *TimeSeries {
for idx, point := range result.Values {
if point.Value < threshold {
@@ -308,7 +308,7 @@ func funcClampMin(result *TimeSeries, threshold float64) *TimeSeries {
return result
}
-// funcClampMax cuts off values above the threshold and replaces them with the threshold
+// funcClampMax cuts off values above the threshold and replaces them with the threshold.
func funcClampMax(result *TimeSeries, threshold float64) *TimeSeries {
for idx, point := range result.Values {
if point.Value > threshold {
@@ -319,7 +319,7 @@ func funcClampMax(result *TimeSeries, threshold float64) *TimeSeries {
return result
}
-// funcAbsolute returns the absolute value of each point
+// funcAbsolute returns the absolute value of each point.
func funcAbsolute(result *TimeSeries) *TimeSeries {
for idx, point := range result.Values {
point.Value = math.Abs(point.Value)
@@ -328,7 +328,7 @@ func funcAbsolute(result *TimeSeries) *TimeSeries {
return result
}
-// funcRunningDiff returns the running difference of each point
+// funcRunningDiff returns the running difference of each point.
func funcRunningDiff(result *TimeSeries) *TimeSeries {
// iterate over the points in reverse order
for idx := len(result.Values) - 1; idx >= 0; idx-- {
@@ -341,7 +341,7 @@ func funcRunningDiff(result *TimeSeries) *TimeSeries {
return result
}
-// funcLog2 returns the log2 of each point
+// funcLog2 returns the log2 of each point.
func funcLog2(result *TimeSeries) *TimeSeries {
for idx, point := range result.Values {
point.Value = math.Log2(point.Value)
@@ -350,7 +350,7 @@ func funcLog2(result *TimeSeries) *TimeSeries {
return result
}
-// funcLog10 returns the log10 of each point
+// funcLog10 returns the log10 of each point.
func funcLog10(result *TimeSeries) *TimeSeries {
for idx, point := range result.Values {
point.Value = math.Log10(point.Value)
@@ -359,7 +359,7 @@ func funcLog10(result *TimeSeries) *TimeSeries {
return result
}
-// funcCumulativeSum returns the cumulative sum for each point in a series
+// funcCumulativeSum returns the cumulative sum for each point in a series.
func funcCumulativeSum(result *TimeSeries) *TimeSeries {
var sum float64
for idx, point := range result.Values {
@@ -373,7 +373,7 @@ func funcCumulativeSum(result *TimeSeries) *TimeSeries {
return result
}
-// funcEWMA calculates the Exponentially Weighted Moving Average
+// funcEWMA calculates the Exponentially Weighted Moving Average.
func funcEWMA(result *TimeSeries, alpha float64) *TimeSeries {
var ewma float64
var initialized bool
@@ -399,22 +399,22 @@ func funcEWMA(result *TimeSeries, alpha float64) *TimeSeries {
return result
}
-// funcMedian3 returns the median of 3 points for each point in a series
+// funcMedian3 returns the median of 3 points for each point in a series.
func funcMedian3(result *TimeSeries) *TimeSeries {
return funcMedianN(result, 3)
}
-// funcMedian5 returns the median of 5 points for each point in a series
+// funcMedian5 returns the median of 5 points for each point in a series.
func funcMedian5(result *TimeSeries) *TimeSeries {
return funcMedianN(result, 5)
}
-// funcMedian7 returns the median of 7 points for each point in a series
+// funcMedian7 returns the median of 7 points for each point in a series.
func funcMedian7(result *TimeSeries) *TimeSeries {
return funcMedianN(result, 7)
}
-// funcMedianN returns the median of N points for each point in a series
+// funcMedianN returns the median of N points for each point in a series.
func funcMedianN(result *TimeSeries, n int) *TimeSeries {
if len(result.Values) == 0 {
return result
@@ -469,7 +469,7 @@ func funcMedianN(result *TimeSeries, n int) *TimeSeries {
return result
}
-// median calculates the median of a slice of float64 values
+// median calculates the median of a slice of float64 values.
func median(values []float64) float64 {
if len(values) == 0 {
return math.NaN()
@@ -483,7 +483,7 @@ func median(values []float64) float64 {
return values[medianIndex]
}
-// funcTimeShift shifts all timestamps by the given amount (in seconds)
+// funcTimeShift shifts all timestamps by the given amount (in seconds).
func funcTimeShift(result *TimeSeries, shift float64) *TimeSeries {
shiftMs := int64(shift * 1000) // Convert seconds to milliseconds
@@ -496,7 +496,7 @@ func funcTimeShift(result *TimeSeries, shift float64) *TimeSeries {
}
// funcFillZero fills gaps in time series with zeros at regular step intervals
-// It takes start, end, and step parameters (all in milliseconds) to ensure consistent filling
+// It takes start, end, and step parameters (all in milliseconds) to ensure consistent filling.
func funcFillZero(result *TimeSeries, start, end, step int64) *TimeSeries {
if step <= 0 {
return result
@@ -528,7 +528,7 @@ func funcFillZero(result *TimeSeries, start, end, step int64) *TimeSeries {
return result
}
-// ApplyFunctions applies a list of functions sequentially to the result
+// ApplyFunctions applies a list of functions sequentially to the result.
func ApplyFunctions(functions []Function, result *TimeSeries) *TimeSeries {
for _, fn := range functions {
result = ApplyFunction(fn, result)
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/functions_test.go b/pkg/types/querybuildertypes/querybuildertypesv5/functions_test.go
index 4fc61695ef..c4def94b0c 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/functions_test.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/functions_test.go
@@ -5,7 +5,7 @@ import (
"testing"
)
-// Helper function to create test time series data
+// Helper function to create test time series data.
func createTestTimeSeriesData(values []float64) *TimeSeries {
timeSeriesValues := make([]*TimeSeriesValue, len(values))
for i, val := range values {
@@ -22,7 +22,7 @@ func createTestTimeSeriesData(values []float64) *TimeSeries {
return series
}
-// Helper function to extract values from result for comparison
+// Helper function to extract values from result for comparison.
func extractValues(result *TimeSeries) []float64 {
values := make([]float64, len(result.Values))
for i, point := range result.Values {
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/join.go b/pkg/types/querybuildertypes/querybuildertypesv5/join.go
index ed61486a5c..5d2dba69eb 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/join.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/join.go
@@ -31,7 +31,7 @@ type QueryRef struct {
Name string `json:"name"`
}
-// Copy creates a deep copy of QueryRef
+// Copy creates a deep copy of QueryRef.
func (q QueryRef) Copy() QueryRef {
return q
}
@@ -64,7 +64,7 @@ type QueryBuilderJoin struct {
Functions []Function `json:"functions,omitempty"`
}
-// Copy creates a deep copy of QueryBuilderJoin
+// Copy creates a deep copy of QueryBuilderJoin.
func (q QueryBuilderJoin) Copy() QueryBuilderJoin {
c := q
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/json_decoder.go b/pkg/types/querybuildertypes/querybuildertypesv5/json_decoder.go
index 665a0d365f..0fb510d978 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/json_decoder.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/json_decoder.go
@@ -11,12 +11,12 @@ import (
)
// UnmarshalJSONWithSuggestions unmarshals JSON data into the target struct
-// and provides field name suggestions for unknown fields
+// and provides field name suggestions for unknown fields.
func UnmarshalJSONWithSuggestions(data []byte, target any) error {
return UnmarshalJSONWithContext(data, target, "")
}
-// UnmarshalJSONWithContext unmarshals JSON with context information for better error messages
+// UnmarshalJSONWithContext unmarshals JSON with context information for better error messages.
func UnmarshalJSONWithContext(data []byte, target any, context string) error {
// First, try to unmarshal with DisallowUnknownFields to catch unknown fields
dec := json.NewDecoder(bytes.NewReader(data))
@@ -68,7 +68,7 @@ func UnmarshalJSONWithContext(data []byte, target any, context string) error {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid JSON: %v", err)
}
-// extractUnknownField extracts the field name from an unknown field error message
+// extractUnknownField extracts the field name from an unknown field error message.
func extractUnknownField(errMsg string) string {
// The error message format is: json: unknown field "fieldname"
parts := strings.Split(errMsg, `"`)
@@ -78,7 +78,7 @@ func extractUnknownField(errMsg string) string {
return ""
}
-// getJSONFieldNames extracts all JSON field names from a struct
+// getJSONFieldNames extracts all JSON field names from a struct.
func getJSONFieldNames(v any) []string {
var fields []string
@@ -110,7 +110,7 @@ func getJSONFieldNames(v any) []string {
}
// wrapUnmarshalError wraps UnmarshalJSONWithContext errors with appropriate context
-// It preserves errors that already have additional context or unknown field errors
+// It preserves errors that already have additional context or unknown field errors.
func wrapUnmarshalError(err error, errorFormat string, args ...interface{}) error {
if err == nil {
return nil
@@ -137,7 +137,7 @@ func wrapUnmarshalError(err error, errorFormat string, args ...interface{}) erro
// wrapValidationError rewraps validation errors with context while preserving additional hints
// It extracts the inner message from the error and creates a new error with the provided format
-// The innerMsg is automatically appended to the args for formatting
+// The innerMsg is automatically appended to the args for formatting.
func wrapValidationError(err error, contextIdentifier string, errorFormat string) error {
if err == nil {
return nil
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/prom_query.go b/pkg/types/querybuildertypes/querybuildertypesv5/prom_query.go
index ac484bc40d..b5b17181f7 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/prom_query.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/prom_query.go
@@ -15,7 +15,7 @@ type PromQuery struct {
Legend string `json:"legend,omitempty"`
}
-// Copy creates a deep copy of the PromQuery
+// Copy creates a deep copy of the PromQuery.
func (q PromQuery) Copy() PromQuery {
return q // shallow copy is sufficient
}
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/req.go b/pkg/types/querybuildertypes/querybuildertypesv5/req.go
index 7cc8c2f316..9d22df6398 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/req.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/req.go
@@ -84,7 +84,7 @@ func (QueryEnvelope) JSONSchemaOneOf() []any {
}
}
-// implement custom json unmarshaler for the QueryEnvelope
+// implement custom json unmarshaler for the QueryEnvelope.
func (q *QueryEnvelope) UnmarshalJSON(data []byte) error {
var shadow struct {
Type QueryType `json:"type"`
@@ -202,7 +202,7 @@ func (c *CompositeQuery) PrepareJSONSchema(schema *jsonschema.Schema) error {
return nil
}
-// UnmarshalJSON implements custom JSON unmarshaling to provide better error messages
+// UnmarshalJSON implements custom JSON unmarshaling to provide better error messages.
func (c *CompositeQuery) UnmarshalJSON(data []byte) error {
type Alias CompositeQuery
@@ -535,7 +535,7 @@ func (r *QueryRangeRequest) SkipFillGaps(name string) bool {
return false
}
-// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields
+// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields.
func (r *QueryRangeRequest) UnmarshalJSON(data []byte) error {
// Define a type alias to avoid infinite recursion
type Alias QueryRangeRequest
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/request_type.go b/pkg/types/querybuildertypes/querybuildertypesv5/request_type.go
index 9d1a68c808..a3fa0fdfdd 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/request_type.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/request_type.go
@@ -8,17 +8,17 @@ type RequestType struct {
var (
RequestTypeUnknown = RequestType{valuer.NewString("")}
- // Scalar result(s), example: number panel, and table panel
+ // Scalar result(s), example: number panel, and table panel.
RequestTypeScalar = RequestType{valuer.NewString("scalar")}
- // []Point (struct{TS int64; Val float64}), example: line/area/bar chart
+ // []Point (struct{TS int64; Val float64}), example: line/area/bar chart.
RequestTypeTimeSeries = RequestType{valuer.NewString("time_series")}
- // [][]any, SQL result set, but paginated, example: list view
+ // [][]any, SQL result set, but paginated, example: list view.
RequestTypeRaw = RequestType{valuer.NewString("raw")}
- // [][]any, SQL result set, but live, example: live list view
+ // [][]any, SQL result set, but live, example: live list view.
RequestTypeRawStream = RequestType{valuer.NewString("raw_stream")}
- // [][]any, Specialized SQL result set, paginated
+ // [][]any, Specialized SQL result set, paginated.
RequestTypeTrace = RequestType{valuer.NewString("trace")}
- // []Bucket (struct{Lower,Upper,Count float64}), example: histogram
+ // []Bucket (struct{Lower,Upper,Count float64}), example: histogram.
RequestTypeDistribution = RequestType{valuer.NewString("distribution")}
)
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/resp.go b/pkg/types/querybuildertypes/querybuildertypesv5/resp.go
index 2ab13f3486..240fb266b8 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/resp.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/resp.go
@@ -173,9 +173,9 @@ type ColumnType struct {
}
var (
- // for the group by part of the query
+ // for the group by part of the query.
ColumnTypeGroup = ColumnType{valuer.NewString("group")}
- // for the aggregation part of the query
+ // for the aggregation part of the query.
ColumnTypeAggregation = ColumnType{valuer.NewString("aggregation")}
)
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/series_limit.go b/pkg/types/querybuildertypes/querybuildertypesv5/series_limit.go
index 2650859d21..1a347923ff 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/series_limit.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/series_limit.go
@@ -14,7 +14,7 @@ const (
)
// ApplyLimit applies limit and ordering to a list of time series
-// This function sorts the series based on the provided order criteria and applies the limit
+// This function sorts the series based on the provided order criteria and applies the limit.
func ApplySeriesLimit(series []*TimeSeries, orderBy []OrderBy, limit int) []*TimeSeries {
if len(series) == 0 {
return series
@@ -74,7 +74,7 @@ func ApplySeriesLimit(series []*TimeSeries, orderBy []OrderBy, limit int) []*Tim
}
// compareSeries compares two time series based on the order criteria
-// Returns true if series i should come before series j
+// Returns true if series i should come before series j.
func compareSeries(seriesI, seriesJ *TimeSeries, orderBy []OrderBy, seriesValues map[*TimeSeries]float64, seriesLabels map[*TimeSeries]map[string]string) bool {
for _, order := range orderBy {
columnName := order.Key.Name
@@ -119,7 +119,7 @@ func compareSeries(seriesI, seriesJ *TimeSeries, orderBy []OrderBy, seriesValues
// calculateSeriesValue calculates the representative value for a time series
// For single-point series (like table queries), returns that value
-// For multi-point series, returns the average of non-NaN/non-Inf values
+// For multi-point series, returns the average of non-NaN/non-Inf values.
func calculateSeriesValue(series *TimeSeries) float64 {
if len(series.Values) == 0 {
return 0.0
@@ -154,7 +154,7 @@ func calculateSeriesValue(series *TimeSeries) float64 {
return sum / count
}
-// convertValueToString converts various types to string for comparison
+// convertValueToString converts various types to string for comparison.
func convertValueToString(value any) string {
switch v := value.(type) {
case string:
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go b/pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go
index 4e5b4206ae..1e0547d354 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/trace_operator.go
@@ -30,7 +30,7 @@ var (
)
const (
- // MaxTraceOperators defines the maximum number of operators allowed in a trace expression
+ // MaxTraceOperators defines the maximum number of operators allowed in a trace expression.
MaxTraceOperators = 10
)
@@ -69,7 +69,7 @@ type QueryBuilderTraceOperator struct {
ParsedExpression *TraceOperand `json:"-"`
}
-// TraceOperand represents the internal parsed tree structure
+// TraceOperand represents the internal parsed tree structure.
type TraceOperand struct {
// For leaf nodes - reference to a query
QueryRef *TraceOperatorQueryRef `json:"-"`
@@ -80,12 +80,12 @@ type TraceOperand struct {
Right *TraceOperand `json:"-"`
}
-// TraceOperatorQueryRef represents a reference to another query
+// TraceOperatorQueryRef represents a reference to another query.
type TraceOperatorQueryRef struct {
Name string `json:"name"`
}
-// ParseExpression parses the expression string into a tree structure
+// ParseExpression parses the expression string into a tree structure.
func (q *QueryBuilderTraceOperator) ParseExpression() error {
if q.Expression == "" {
return errors.WrapInvalidInputf(
@@ -120,7 +120,7 @@ func (q *QueryBuilderTraceOperator) ParseExpression() error {
return nil
}
-// ValidateTraceOperator validates that all referenced queries exist and are trace queries
+// ValidateTraceOperator validates that all referenced queries exist and are trace queries.
func (q *QueryBuilderTraceOperator) ValidateTraceOperator(queries []QueryEnvelope) error {
// Parse the expression - this now includes operator count validation
if err := q.ParseExpression(); err != nil {
@@ -222,7 +222,7 @@ func (q *QueryBuilderTraceOperator) ValidateTraceOperator(queries []QueryEnvelop
return nil
}
-// ValidateOrderBy validates the orderBy field
+// ValidateOrderBy validates the orderBy field.
func (q *QueryBuilderTraceOperator) ValidateOrderBy() error {
if len(q.Order) == 0 {
return nil
@@ -254,7 +254,7 @@ func (q *QueryBuilderTraceOperator) ValidateOrderBy() error {
return nil
}
-// ValidatePagination validates pagination parameters (AIP-158 compliance)
+// ValidatePagination validates pagination parameters (AIP-158 compliance).
func (q *QueryBuilderTraceOperator) ValidatePagination() error {
if q.Limit < 0 {
return errors.WrapInvalidInputf(
@@ -287,7 +287,7 @@ func (q *QueryBuilderTraceOperator) ValidatePagination() error {
return nil
}
-// CollectReferencedQueries collects all query names referenced in the expression tree
+// CollectReferencedQueries collects all query names referenced in the expression tree.
func (q *QueryBuilderTraceOperator) CollectReferencedQueries(operand *TraceOperand) []string {
if operand == nil {
return nil
@@ -316,7 +316,7 @@ func (q *QueryBuilderTraceOperator) CollectReferencedQueries(operand *TraceOpera
return unique
}
-// Copy creates a deep copy of QueryBuilderTraceOperator
+// Copy creates a deep copy of QueryBuilderTraceOperator.
func (q QueryBuilderTraceOperator) Copy() QueryBuilderTraceOperator {
// Start with a shallow copy
c := q
@@ -366,7 +366,7 @@ func (q QueryBuilderTraceOperator) Copy() QueryBuilderTraceOperator {
return c
}
-// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields
+// UnmarshalJSON implements custom JSON unmarshaling to disallow unknown fields.
func (q *QueryBuilderTraceOperator) UnmarshalJSON(data []byte) error {
// Define a type alias to avoid infinite recursion
type Alias QueryBuilderTraceOperator
@@ -385,7 +385,7 @@ func (q *QueryBuilderTraceOperator) UnmarshalJSON(data []byte) error {
return nil
}
-// Normalize normalizes all the field keys in the query
+// Normalize normalizes all the field keys in the query.
func (q *QueryBuilderTraceOperator) Normalize() {
// normalize select fields
@@ -405,7 +405,7 @@ func (q *QueryBuilderTraceOperator) Normalize() {
}
-// ValidateUniqueTraceOperator ensures only one trace operator exists in queries
+// ValidateUniqueTraceOperator ensures only one trace operator exists in queries.
func ValidateUniqueTraceOperator(queries []QueryEnvelope) error {
traceOperatorCount := 0
var traceOperatorNames []string
@@ -433,7 +433,7 @@ func ValidateUniqueTraceOperator(queries []QueryEnvelope) error {
return nil
}
-// Handles precedence: NOT (highest) > || > && > => (lowest)
+// Handles precedence: NOT (highest) > || > && > => (lowest).
func parseTraceExpression(expr string) (*TraceOperand, int, error) {
expr = strings.TrimSpace(expr)
@@ -515,13 +515,14 @@ func parseTraceExpression(expr string) (*TraceOperand, int, error) {
}, 0, nil
}
-// isBalancedParentheses checks if parentheses are balanced in the expression
+// isBalancedParentheses checks if parentheses are balanced in the expression.
func isBalancedParentheses(expr string) bool {
depth := 0
for _, char := range expr {
- if char == '(' {
+ switch char {
+ case '(':
depth++
- } else if char == ')' {
+ case ')':
depth--
if depth < 0 {
return false
@@ -531,7 +532,7 @@ func isBalancedParentheses(expr string) bool {
return depth == 0
}
-// findOperatorPosition finds the position of an operator, respecting parentheses
+// findOperatorPosition finds the position of an operator, respecting parentheses.
func findOperatorPosition(expr, op string) int {
depth := 0
opLen := len(op)
@@ -541,9 +542,10 @@ func findOperatorPosition(expr, op string) int {
char := expr[i]
// Update depth based on parentheses (scanning right to left)
- if char == ')' {
+ switch char {
+ case ')':
depth++
- } else if char == '(' {
+ case '(':
depth--
}
diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/validation.go b/pkg/types/querybuildertypes/querybuildertypesv5/validation.go
index 9ae25a478a..99ad9d26f4 100644
--- a/pkg/types/querybuildertypes/querybuildertypesv5/validation.go
+++ b/pkg/types/querybuildertypes/querybuildertypesv5/validation.go
@@ -10,7 +10,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
-// getQueryIdentifier returns a friendly identifier for a query based on its type and name/content
+// getQueryIdentifier returns a friendly identifier for a query based on its type and name/content.
func getQueryIdentifier(envelope QueryEnvelope, index int) string {
name := envelope.GetQueryName()
@@ -39,7 +39,7 @@ func getQueryIdentifier(envelope QueryEnvelope, index int) string {
}
const (
- // Maximum limit for query results
+ // Maximum limit for query results.
MaxQueryLimit = 10000
)
@@ -172,7 +172,7 @@ func (q *QueryBuilderQuery[T]) validateGroupBy(cfg validationConfig) error {
return nil
}
for idx, item := range q.GroupBy {
- if item.TelemetryFieldKey.Name == "" {
+ if item.Name == "" {
return errors.NewInvalidInputf(
errors.CodeInvalidInput, "invalid empty key name for group by at index %d", idx,
)
@@ -395,7 +395,7 @@ func (q *QueryBuilderQuery[T]) validateOrderByForAggregation() error {
validOrderKeys := make(map[string]bool)
for _, gb := range q.GroupBy {
- validOrderKeys[gb.TelemetryFieldKey.Name] = true
+ validOrderKeys[gb.Name] = true
}
for i, agg := range q.Aggregations {
@@ -497,7 +497,7 @@ func (r *QueryRangeRequest) Validate(opts ...ValidationOption) error {
return nil
}
-// validateAllQueriesNotDisabled validates that at least one query in the composite query is enabled
+// validateAllQueriesNotDisabled validates that at least one query in the composite query is enabled.
func (r *QueryRangeRequest) validateAllQueriesNotDisabled() error {
for _, envelope := range r.CompositeQuery.Queries {
if !envelope.IsDisabled() {
@@ -511,7 +511,7 @@ func (r *QueryRangeRequest) validateAllQueriesNotDisabled() error {
)
}
-// Validate performs validation on CompositeQuery
+// Validate performs validation on CompositeQuery.
func (c *CompositeQuery) Validate(opts ...ValidationOption) error {
if len(c.Queries) == 0 {
return errors.NewInvalidInputf(
diff --git a/pkg/types/quickfiltertypes/filter.go b/pkg/types/quickfiltertypes/filter.go
index b86d2cb192..55a6f8c497 100644
--- a/pkg/types/quickfiltertypes/filter.go
+++ b/pkg/types/quickfiltertypes/filter.go
@@ -38,7 +38,7 @@ var (
SignalMeter = Signal{valuer.NewString("meter")}
)
-// NewSignal creates a Signal from a string
+// NewSignal creates a Signal from a string.
func NewSignal(s string) (Signal, error) {
switch s {
case "traces":
@@ -75,7 +75,7 @@ type UpdatableQuickFilters struct {
Filters []v3.AttributeKey `json:"filters"`
}
-// NewStorableQuickFilter creates a new StorableQuickFilter after validation
+// NewStorableQuickFilter creates a new StorableQuickFilter after validation.
func NewStorableQuickFilter(orgID valuer.UUID, signal Signal, filterJSON []byte) (*StorableQuickFilter, error) {
if orgID.StringValue() == "" {
return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "orgID is required")
@@ -105,7 +105,7 @@ func NewStorableQuickFilter(orgID valuer.UUID, signal Signal, filterJSON []byte)
}, nil
}
-// Update updates an existing StorableQuickFilter with new filter data after validation
+// Update updates an existing StorableQuickFilter with new filter data after validation.
func (quickfilter *StorableQuickFilter) Update(filterJSON []byte) error {
var filters []v3.AttributeKey
if err := json.Unmarshal(filterJSON, &filters); err != nil {
@@ -117,7 +117,7 @@ func (quickfilter *StorableQuickFilter) Update(filterJSON []byte) error {
return nil
}
-// NewSignalFilterFromStorableQuickFilter converts a StorableQuickFilter to a SignalFilters object
+// NewSignalFilterFromStorableQuickFilter converts a StorableQuickFilter to a SignalFilters object.
func NewSignalFilterFromStorableQuickFilter(storableQuickFilter *StorableQuickFilter) (*SignalFilters, error) {
if storableQuickFilter == nil {
return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "storableQuickFilter cannot be nil")
@@ -137,7 +137,7 @@ func NewSignalFilterFromStorableQuickFilter(storableQuickFilter *StorableQuickFi
}, nil
}
-// NewDefaultQuickFilter generates default filters for all supported signals
+// NewDefaultQuickFilter generates default filters for all supported signals.
func NewDefaultQuickFilter(orgID valuer.UUID) ([]*StorableQuickFilter, error) {
tracesFilters := []map[string]interface{}{
{"key": "duration_nano", "dataType": "float64", "type": "tag"},
diff --git a/pkg/types/ruletypes/alerting.go b/pkg/types/ruletypes/alerting.go
index ba78a86258..4e9e8cfc49 100644
--- a/pkg/types/ruletypes/alerting.go
+++ b/pkg/types/ruletypes/alerting.go
@@ -18,7 +18,7 @@ import (
// rule engine
const (
- // how long before re-sending the alert
+ // how long before re-sending the alert.
ResolvedRetention = 15 * time.Minute
TestAlertPostFix = "_TEST_ALERT"
)
@@ -210,7 +210,7 @@ func (rc *RuleCondition) ShouldEval(series *v3.Series) bool {
return !rc.RequireMinPoints || len(series.Points) >= rc.RequiredNumPoints
}
-// QueryType is a shorthand method to get query type
+// QueryType is a shorthand method to get query type.
func (rc *RuleCondition) QueryType() v3.QueryType {
if rc.CompositeQuery != nil {
return rc.CompositeQuery.QueryType
@@ -218,7 +218,7 @@ func (rc *RuleCondition) QueryType() v3.QueryType {
return v3.QueryTypeUnknown
}
-// String is useful in printing rule condition in logs
+// String is useful in printing rule condition in logs.
func (rc *RuleCondition) String() string {
if rc == nil {
return ""
diff --git a/pkg/types/ruletypes/api_params.go b/pkg/types/ruletypes/api_params.go
index 2947b47990..e899673ba3 100644
--- a/pkg/types/ruletypes/api_params.go
+++ b/pkg/types/ruletypes/api_params.go
@@ -38,7 +38,7 @@ const (
RuleDataKindJson RuleDataKind = "json"
)
-// PostableRule is used to create alerting rule from HTTP api
+// PostableRule is used to create alerting rule from HTTP api.
type PostableRule struct {
AlertName string `json:"alert,omitempty"`
AlertType AlertType `json:"alertType,omitempty"`
@@ -293,7 +293,7 @@ func isValidLabelName(ln string) bool {
return false
}
for i, b := range ln {
- if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == '.' || (b >= '0' && b <= '9' && i > 0)) {
+ if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == '.' || (b >= '0' && b <= '9' && i > 0)) { //nolint:staticcheck // QF1001: De Morgan form is less readable here
return false
}
}
diff --git a/pkg/types/ruletypes/maintenance_test.go b/pkg/types/ruletypes/maintenance_test.go
index 5b1c6c3587..22ae497e50 100644
--- a/pkg/types/ruletypes/maintenance_test.go
+++ b/pkg/types/ruletypes/maintenance_test.go
@@ -7,7 +7,7 @@ import (
"github.com/SigNoz/signoz/pkg/valuer"
)
-// Helper function to create a time pointer
+// Helper function to create a time pointer.
func timePtr(t time.Time) *time.Time {
return &t
}
diff --git a/pkg/types/ruletypes/rule.go b/pkg/types/ruletypes/rule.go
index 401e8677c8..471ba91a23 100644
--- a/pkg/types/ruletypes/rule.go
+++ b/pkg/types/ruletypes/rule.go
@@ -47,7 +47,7 @@ func NewStatsFromRules(rules []*Rule) map[string]any {
return stats
}
-// RuleAlert represents an alert associated with a rule, used when filtering by metric name
+// RuleAlert represents an alert associated with a rule, used when filtering by metric name.
type RuleAlert struct {
AlertName string
AlertID string
diff --git a/pkg/types/ruletypes/threshold.go b/pkg/types/ruletypes/threshold.go
index 3dc4ddc529..5148cb0ca7 100644
--- a/pkg/types/ruletypes/threshold.go
+++ b/pkg/types/ruletypes/threshold.go
@@ -7,9 +7,9 @@ import (
"strings"
"github.com/SigNoz/signoz/pkg/errors"
- "github.com/SigNoz/signoz/pkg/units"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
"github.com/SigNoz/signoz/pkg/query-service/utils/labels"
+ "github.com/SigNoz/signoz/pkg/units"
"github.com/SigNoz/signoz/pkg/valuer"
)
@@ -199,7 +199,7 @@ func sortThresholds(thresholds []BasicRuleThreshold) {
})
}
-// convertToRuleUnit converts the given value from the target unit to the rule unit
+// convertToRuleUnit converts the given value from the target unit to the rule unit.
func (b BasicRuleThreshold) convertToRuleUnit(val float64, ruleUnit string) float64 {
unitConverter := units.ConverterFromUnit(units.Unit(b.TargetUnit))
// convert the target value to the y-axis unit
@@ -210,12 +210,12 @@ func (b BasicRuleThreshold) convertToRuleUnit(val float64, ruleUnit string) floa
return value.F
}
-// target returns the target value in the rule unit
+// target returns the target value in the rule unit.
func (b BasicRuleThreshold) target(ruleUnit string) float64 {
return b.convertToRuleUnit(*b.TargetValue, ruleUnit)
}
-// recoveryTarget returns the recovery target value in the rule unit
+// recoveryTarget returns the recovery target value in the rule unit.
func (b BasicRuleThreshold) recoveryTarget(ruleUnit string) float64 {
return b.convertToRuleUnit(*b.RecoveryTarget, ruleUnit)
}
@@ -353,7 +353,7 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series v3.Series, target float
}
// use min value from the series
if shouldAlert {
- var minValue float64 = math.Inf(1)
+ var minValue = math.Inf(1)
for _, smpl := range series.Points {
if smpl.Value < minValue {
minValue = smpl.Value
@@ -369,7 +369,7 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series v3.Series, target float
}
}
if shouldAlert {
- var maxValue float64 = math.Inf(-1)
+ var maxValue = math.Inf(-1)
for _, smpl := range series.Points {
if smpl.Value > maxValue {
maxValue = smpl.Value
@@ -421,23 +421,24 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series v3.Series, target float
}
avg := sum / count
alertSmpl = Sample{Point: Point{V: avg}, Metric: lbls}
- if b.CompareOp == ValueIsAbove {
+ switch b.CompareOp {
+ case ValueIsAbove:
if avg > target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsBelow {
+ case ValueIsBelow:
if avg < target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsEq {
+ case ValueIsEq:
if avg == target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsNotEq {
+ case ValueIsNotEq:
if avg != target {
shouldAlert = true
}
- } else if b.CompareOp == ValueOutsideBounds {
+ case ValueOutsideBounds:
if math.Abs(avg) >= target {
shouldAlert = true
}
@@ -453,23 +454,24 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series v3.Series, target float
sum += smpl.Value
}
alertSmpl = Sample{Point: Point{V: sum}, Metric: lbls}
- if b.CompareOp == ValueIsAbove {
+ switch b.CompareOp {
+ case ValueIsAbove:
if sum > target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsBelow {
+ case ValueIsBelow:
if sum < target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsEq {
+ case ValueIsEq:
if sum == target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsNotEq {
+ case ValueIsNotEq:
if sum != target {
shouldAlert = true
}
- } else if b.CompareOp == ValueOutsideBounds {
+ case ValueOutsideBounds:
if math.Abs(sum) >= target {
shouldAlert = true
}
@@ -478,19 +480,20 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series v3.Series, target float
// If the last sample matches the condition, the rule is firing.
shouldAlert = false
alertSmpl = Sample{Point: Point{V: series.Points[len(series.Points)-1].Value}, Metric: lbls}
- if b.CompareOp == ValueIsAbove {
+ switch b.CompareOp {
+ case ValueIsAbove:
if series.Points[len(series.Points)-1].Value > target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsBelow {
+ case ValueIsBelow:
if series.Points[len(series.Points)-1].Value < target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsEq {
+ case ValueIsEq:
if series.Points[len(series.Points)-1].Value == target {
shouldAlert = true
}
- } else if b.CompareOp == ValueIsNotEq {
+ case ValueIsNotEq:
if series.Points[len(series.Points)-1].Value != target {
shouldAlert = true
}
diff --git a/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go b/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go
index 474265e799..63f53ec646 100644
--- a/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go
+++ b/pkg/types/servicetypes/servicetypesv1/servicetypesv1.go
@@ -1,6 +1,6 @@
package servicetypesv1
-// Request mirrors the /services API input shape
+// Request mirrors the /services API input shape.
type Request struct {
// Start and End are epoch nanoseconds encoded as strings
Start string `json:"start"`
@@ -17,7 +17,7 @@ type TagFilterItem struct {
TagType string `json:"TagType"`
}
-// ResponseItem mirrors model.ServiceItem
+// ResponseItem mirrors model.ServiceItem.
type ResponseItem struct {
ServiceName string `json:"serviceName"`
Percentile99 float64 `json:"p99"`
@@ -35,7 +35,7 @@ type DataWarning struct {
TopLevelOps []string `json:"topLevelOps"`
}
-// OperationsRequest is the common request for both top_operations and entry_point_operations
+// OperationsRequest is the common request for both top_operations and entry_point_operations.
type OperationsRequest struct {
Start string `json:"start"`
End string `json:"end"`
@@ -44,7 +44,7 @@ type OperationsRequest struct {
Limit int `json:"limit,omitempty"`
}
-// OperationItem is the common response item shape for both APIs
+// OperationItem is the common response item shape for both APIs.
type OperationItem struct {
Name string `json:"name"`
P50 float64 `json:"p50"`
diff --git a/pkg/types/telemetrytypes/field.go b/pkg/types/telemetrytypes/field.go
index 82983033e0..66fd59eff2 100644
--- a/pkg/types/telemetrytypes/field.go
+++ b/pkg/types/telemetrytypes/field.go
@@ -19,12 +19,12 @@ var (
)
const (
- // BodyJSONStringSearchPrefix is the prefix used for body JSON search queries
- // e.g., "body.status" where "body." is the prefix
+ // BodyJSONStringSearchPrefix is the prefix used for body JSON search queries.
+ // e.g., "body.status" where "body." is the prefix.
BodyJSONStringSearchPrefix = "body."
ArraySep = jsontypeexporter.ArraySeparator
ArraySepSuffix = "[]"
- // TODO(Piyush): Remove once we've migrated to the new array syntax
+ // TODO(Piyush): Remove once we've migrated to the new array syntax.
ArrayAnyIndex = "[*]."
ArrayAnyIndexSuffix = "[*]"
)
@@ -49,8 +49,8 @@ func (f *TelemetryFieldKey) KeyNameContainsArray() bool {
return strings.Contains(f.Name, ArraySep) || strings.Contains(f.Name, ArrayAnyIndex)
}
-// ArrayPathSegments returns just the individual segments of the path
-// e.g., "education[].awards[].type" -> ["education", "awards", "type"]
+// ArrayPathSegments returns just the individual segments of the path.
+// e.g., "education[].awards[].type" -> ["education", "awards", "type"].
func (f *TelemetryFieldKey) ArrayPathSegments() []string {
return strings.Split(strings.ReplaceAll(f.Name, ArrayAnyIndex, ArraySep), ArraySep)
}
@@ -177,10 +177,10 @@ func (f *TelemetryFieldKey) Normalize() {
// Both fieldContext and :fieldDataType are optional.
// fieldName can contain dots and can start with a dot (e.g., ".http_code").
// Special cases:
-// - When key exactly matches a field context name (e.g., "body", "attribute"), use unspecified context
-// - When key starts with "body." prefix, use "body" as context with remainder as field name
+// - When key exactly matches a field context name (e.g., "body", "attribute"), use unspecified context.
+// - When key starts with "body." prefix, use "body" as context with remainder as field name.
func GetFieldKeyFromKeyText(key string) TelemetryFieldKey {
- var explicitFieldDataType FieldDataType = FieldDataTypeUnspecified
+ var explicitFieldDataType = FieldDataTypeUnspecified
var fieldName string
// Step 1: Parse data type from the right (after the last ":")
diff --git a/pkg/types/telemetrytypes/field_context.go b/pkg/types/telemetrytypes/field_context.go
index dc789feef8..b1773897eb 100644
--- a/pkg/types/telemetrytypes/field_context.go
+++ b/pkg/types/telemetrytypes/field_context.go
@@ -79,7 +79,7 @@ var (
}
)
-// UnmarshalJSON implements the json.Unmarshaler interface
+// UnmarshalJSON implements the json.Unmarshaler interface.
func (f *FieldContext) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
@@ -100,7 +100,7 @@ func (f *FieldContext) UnmarshalJSON(data []byte) error {
return nil
}
-// Scan implements the sql.Scanner interface
+// Scan implements the sql.Scanner interface.
func (f *FieldContext) Scan(value interface{}) error {
if f == nil {
return errors.NewInternalf(errors.CodeInternal, "fieldcontext: nil receiver")
diff --git a/pkg/types/telemetrytypes/field_datatype.go b/pkg/types/telemetrytypes/field_datatype.go
index e9e0735765..9a111ad5c8 100644
--- a/pkg/types/telemetrytypes/field_datatype.go
+++ b/pkg/types/telemetrytypes/field_datatype.go
@@ -18,7 +18,7 @@ var (
FieldDataTypeString = FieldDataType{valuer.NewString("string")}
FieldDataTypeBool = FieldDataType{valuer.NewString("bool")}
FieldDataTypeFloat64 = FieldDataType{valuer.NewString("float64")}
- // int64 and number are synonyms for float64
+ // int64 and number are synonyms for float64.
FieldDataTypeInt64 = FieldDataType{valuer.NewString("int64")}
FieldDataTypeNumber = FieldDataType{valuer.NewString("number")}
FieldDataTypeUnspecified = FieldDataType{valuer.NewString("")}
@@ -27,7 +27,7 @@ var (
FieldDataTypeArrayFloat64 = FieldDataType{valuer.NewString("[]float64")}
FieldDataTypeArrayBool = FieldDataType{valuer.NewString("[]bool")}
- // int64 and number are synonyms for float64
+ // int64 and number are synonyms for float64.
FieldDataTypeArrayInt64 = FieldDataType{valuer.NewString("[]int64")}
FieldDataTypeArrayNumber = FieldDataType{valuer.NewString("[]number")}
@@ -114,7 +114,7 @@ func (f FieldDataType) IsArray() bool {
return strings.HasPrefix(f.StringValue(), "[]") || strings.HasSuffix(f.StringValue(), "[]")
}
-// UnmarshalJSON implements the json.Unmarshaler interface
+// UnmarshalJSON implements the json.Unmarshaler interface.
func (f *FieldDataType) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
@@ -135,7 +135,7 @@ func (f *FieldDataType) UnmarshalJSON(data []byte) error {
return nil
}
-// Scan implements the sql.Scanner interface
+// Scan implements the sql.Scanner interface.
func (f *FieldDataType) Scan(value interface{}) error {
if f == nil {
return errors.NewInternalf(errors.CodeInternal, "fielddatatype: nil receiver")
diff --git a/pkg/types/telemetrytypes/json_access_plan.go b/pkg/types/telemetrytypes/json_access_plan.go
index 6102152fd2..e403645090 100644
--- a/pkg/types/telemetrytypes/json_access_plan.go
+++ b/pkg/types/telemetrytypes/json_access_plan.go
@@ -35,7 +35,7 @@ type TerminalConfig struct {
}
// Node is now a tree structure representing the complete JSON path traversal
-// that precomputes all possible branches and their types
+// that precomputes all possible branches and their types.
type JSONAccessNode struct {
// Node information
Name string
@@ -104,7 +104,7 @@ type planBuilder struct {
typeCache map[string][]JSONDataType
}
-// buildPlan recursively builds the path plan tree
+// buildPlan recursively builds the path plan tree.
func (pb *planBuilder) buildPlan(index int, parent *JSONAccessNode, isDynArrChild bool) (*JSONAccessNode, error) {
if index >= len(pb.paths) {
return nil, errors.NewInvalidInputf(CodePlanIndexOutOfBounds, "index is out of bounds")
@@ -179,7 +179,7 @@ func (pb *planBuilder) buildPlan(index int, parent *JSONAccessNode, isDynArrChil
}
// buildJSONAccessPlan builds a tree structure representing the complete JSON path traversal
-// that precomputes all possible branches and their types
+// that precomputes all possible branches and their types.
func (key *TelemetryFieldKey) SetJSONAccessPlan(columnInfo JSONColumnMetadata, typeCache map[string][]JSONDataType,
) error {
// if path is empty, return nil
diff --git a/pkg/types/telemetrytypes/json_access_plan_test.go b/pkg/types/telemetrytypes/json_access_plan_test.go
index 156f4cf28a..80e283ef61 100644
--- a/pkg/types/telemetrytypes/json_access_plan_test.go
+++ b/pkg/types/telemetrytypes/json_access_plan_test.go
@@ -18,7 +18,7 @@ const (
// Helper Functions for Test Data Creation
// ============================================================================
-// makeKey creates a TelemetryFieldKey for testing
+// makeKey creates a TelemetryFieldKey for testing.
func makeKey(name string, dataType JSONDataType, materialized bool) *TelemetryFieldKey {
return &TelemetryFieldKey{
Name: name,
diff --git a/pkg/types/telemetrytypes/json_datatype.go b/pkg/types/telemetrytypes/json_datatype.go
index aa98c5c8c8..6d5dda4239 100644
--- a/pkg/types/telemetrytypes/json_datatype.go
+++ b/pkg/types/telemetrytypes/json_datatype.go
@@ -13,7 +13,7 @@ type JSONDataType struct {
IndexSupported bool
}
-// Override StringValue to return the correct case
+// Override StringValue to return the correct case.
func (jdt JSONDataType) StringValue() string {
return jdt.str
}
diff --git a/pkg/types/telemetrytypes/maybe_typo.go b/pkg/types/telemetrytypes/maybe_typo.go
index cf46889ad5..73f78d5c0f 100644
--- a/pkg/types/telemetrytypes/maybe_typo.go
+++ b/pkg/types/telemetrytypes/maybe_typo.go
@@ -9,7 +9,7 @@ const (
typoSuggestionThreshold = 0.75
)
-// levenshteinDistance calculates the edit distance between two strings
+// levenshteinDistance calculates the edit distance between two strings.
func levenshteinDistance(s1, s2 string) int {
s1 = strings.ToLower(s1)
s2 = strings.ToLower(s2)
@@ -57,7 +57,7 @@ func levenshteinDistance(s1, s2 string) int {
return v1[len(s2)]
}
-// similarity returns a value between 0 and 1, where 1 means perfect match
+// similarity returns a value between 0 and 1, where 1 means perfect match.
func similarity(s1, s2 string) float64 {
maxLen := max(len(s1), len(s2))
if maxLen == 0 {
@@ -89,7 +89,7 @@ func max(a, b int) int {
}
// SuggestCorrection checks if there are any column names similar to the input
-// and returns a suggestion if there's at least 75% similarity
+// and returns a suggestion if there's at least 75% similarity.
func SuggestCorrection(input string, knownFieldKeys []string) (string, bool) {
var bestMatch string
diff --git a/pkg/types/telemetrytypes/telemetrytypestest/load_keys.go b/pkg/types/telemetrytypes/telemetrytypestest/load_keys.go
index 1b2f56ff23..463fd46579 100644
--- a/pkg/types/telemetrytypes/telemetrytypestest/load_keys.go
+++ b/pkg/types/telemetrytypes/telemetrytypestest/load_keys.go
@@ -8,7 +8,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
-// LoadFieldKeysFromJSON loads telemetry field keys from a JSON file
+// LoadFieldKeysFromJSON loads telemetry field keys from a JSON file.
func LoadFieldKeysFromJSON(filePath string) (map[string][]*telemetrytypes.TelemetryFieldKey, error) {
jsonData, err := os.ReadFile(filePath)
if err != nil {
@@ -23,7 +23,7 @@ func LoadFieldKeysFromJSON(filePath string) (map[string][]*telemetrytypes.Teleme
return result, nil
}
-// LoadFieldKeysFromJSONString loads telemetry field keys from a JSON string
+// LoadFieldKeysFromJSONString loads telemetry field keys from a JSON string.
func LoadFieldKeysFromJSONString(jsonStr string) (map[string][]*telemetrytypes.TelemetryFieldKey, error) {
var result map[string][]*telemetrytypes.TelemetryFieldKey
if err := json.Unmarshal([]byte(jsonStr), &result); err != nil {
diff --git a/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go b/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go
index 631761eb9d..d4c4214be6 100644
--- a/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go
+++ b/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go
@@ -9,7 +9,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
)
-// MockMetadataStore implements the MetadataStore interface for testing purposes
+// MockMetadataStore implements the MetadataStore interface for testing purposes.
type MockMetadataStore struct {
// Maps to store test data
KeysMap map[string][]*telemetrytypes.TelemetryFieldKey
@@ -48,7 +48,7 @@ func (m *MockMetadataStore) SetStaticFields(intrinsicFields map[string]telemetry
m.StaticFields = intrinsicFields
}
-// GetKeys returns a map of field keys types.TelemetryFieldKey by name
+// GetKeys returns a map of field keys types.TelemetryFieldKey by name.
func (m *MockMetadataStore) GetKeys(ctx context.Context, fieldKeySelector *telemetrytypes.FieldKeySelector) (map[string][]*telemetrytypes.TelemetryFieldKey, bool, error) {
setOfKeys := make(map[string]*telemetrytypes.TelemetryFieldKey)
result := make(map[string][]*telemetrytypes.TelemetryFieldKey)
@@ -89,7 +89,7 @@ func (m *MockMetadataStore) GetKeys(ctx context.Context, fieldKeySelector *telem
return result, true, nil
}
-// GetKeysMulti applies multiple selectors and returns combined results
+// GetKeysMulti applies multiple selectors and returns combined results.
func (m *MockMetadataStore) GetKeysMulti(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) (map[string][]*telemetrytypes.TelemetryFieldKey, bool, error) {
result := make(map[string][]*telemetrytypes.TelemetryFieldKey)
@@ -129,7 +129,7 @@ func (m *MockMetadataStore) GetKeysMulti(ctx context.Context, fieldKeySelectors
return result, true, nil
}
-// GetKey returns a list of keys with the given name
+// GetKey returns a list of keys with the given name.
func (m *MockMetadataStore) GetKey(ctx context.Context, fieldKeySelector *telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, error) {
if fieldKeySelector == nil {
return nil, nil
@@ -162,7 +162,7 @@ func (m *MockMetadataStore) GetKey(ctx context.Context, fieldKeySelector *teleme
return result, nil
}
-// GetRelatedValues returns a list of related values for the given key name and selection
+// GetRelatedValues returns a list of related values for the given key name and selection.
func (m *MockMetadataStore) GetRelatedValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector) ([]string, bool, error) {
if fieldValueSelector == nil {
return nil, true, nil
@@ -179,7 +179,7 @@ func (m *MockMetadataStore) GetRelatedValues(ctx context.Context, fieldValueSele
return []string{}, true, nil
}
-// GetAllValues returns all values for a given field
+// GetAllValues returns all values for a given field.
func (m *MockMetadataStore) GetAllValues(ctx context.Context, fieldValueSelector *telemetrytypes.FieldValueSelector) (*telemetrytypes.TelemetryFieldValues, bool, error) {
if fieldValueSelector == nil {
return &telemetrytypes.TelemetryFieldValues{}, true, nil
@@ -198,7 +198,7 @@ func (m *MockMetadataStore) GetAllValues(ctx context.Context, fieldValueSelector
// Helper functions to avoid adding methods to structs
-// matchesName checks if a field name matches the selector criteria
+// matchesName checks if a field name matches the selector criteria.
func matchesName(selector *telemetrytypes.FieldKeySelector, name string) bool {
if selector == nil || selector.Name == "" {
return true
@@ -212,7 +212,7 @@ func matchesName(selector *telemetrytypes.FieldKeySelector, name string) bool {
return strings.Contains(strings.ToLower(name), strings.ToLower(selector.Name))
}
-// matchesKey checks if a field key matches the selector criteria
+// matchesKey checks if a field key matches the selector criteria.
func matchesKey(selector *telemetrytypes.FieldKeySelector, key *telemetrytypes.TelemetryFieldKey) bool {
if selector == nil {
return true
@@ -246,12 +246,12 @@ func matchesKey(selector *telemetrytypes.FieldKeySelector, key *telemetrytypes.T
return true
}
-// keyIdentifier generates a unique identifier for the key
+// keyIdentifier generates a unique identifier for the key.
func keyIdentifier(key *telemetrytypes.TelemetryFieldKey) string {
return key.Name + "-" + key.FieldContext.StringValue() + "-" + key.FieldDataType.StringValue()
}
-// generateLookupKey creates a lookup key for the selector
+// generateLookupKey creates a lookup key for the selector.
func generateLookupKey(selector *telemetrytypes.FieldValueSelector) string {
if selector == nil {
return ""
@@ -260,16 +260,16 @@ func generateLookupKey(selector *telemetrytypes.FieldValueSelector) string {
parts := []string{selector.Name}
if selector.FieldKeySelector != nil {
- if selector.FieldKeySelector.Signal != telemetrytypes.SignalUnspecified {
- parts = append(parts, selector.FieldKeySelector.Signal.StringValue())
+ if selector.Signal != telemetrytypes.SignalUnspecified {
+ parts = append(parts, selector.Signal.StringValue())
}
- if selector.FieldKeySelector.FieldContext != telemetrytypes.FieldContextUnspecified {
- parts = append(parts, selector.FieldKeySelector.FieldContext.StringValue())
+ if selector.FieldContext != telemetrytypes.FieldContextUnspecified {
+ parts = append(parts, selector.FieldContext.StringValue())
}
- if selector.FieldKeySelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
- parts = append(parts, selector.FieldKeySelector.FieldDataType.StringValue())
+ if selector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {
+ parts = append(parts, selector.FieldDataType.StringValue())
}
}
@@ -280,7 +280,7 @@ func generateLookupKey(selector *telemetrytypes.FieldValueSelector) string {
return strings.Join(parts, "-")
}
-// SetKey adds a test key to the mock store
+// SetKey adds a test key to the mock store.
func (m *MockMetadataStore) SetKey(key *telemetrytypes.TelemetryFieldKey) {
name := key.Name
if _, exists := m.KeysMap[name]; !exists {
@@ -289,24 +289,24 @@ func (m *MockMetadataStore) SetKey(key *telemetrytypes.TelemetryFieldKey) {
m.KeysMap[name] = append(m.KeysMap[name], key)
}
-// SetKeys adds a list of test keys to the mock store
+// SetKeys adds a list of test keys to the mock store.
func (m *MockMetadataStore) SetKeys(keys []*telemetrytypes.TelemetryFieldKey) {
for _, key := range keys {
m.SetKey(key)
}
}
-// SetRelatedValues sets related values for testing
+// SetRelatedValues sets related values for testing.
func (m *MockMetadataStore) SetRelatedValues(lookupKey string, values []string) {
m.RelatedValuesMap[lookupKey] = values
}
-// SetAllValues sets all values for testing
+// SetAllValues sets all values for testing.
func (m *MockMetadataStore) SetAllValues(lookupKey string, values *telemetrytypes.TelemetryFieldValues) {
m.AllValuesMap[lookupKey] = values
}
-// FetchTemporality fetches the temporality for a metric
+// FetchTemporality fetches the temporality for a metric.
func (m *MockMetadataStore) FetchTemporality(ctx context.Context, queryTimeRangeStartTs, queryTimeRangeEndTs uint64, metricName string) (metrictypes.Temporality, error) {
if temporality, exists := m.TemporalityMap[metricName]; exists {
return temporality, nil
@@ -314,7 +314,7 @@ func (m *MockMetadataStore) FetchTemporality(ctx context.Context, queryTimeRange
return metrictypes.Unknown, nil
}
-// FetchTemporalityMulti fetches the temporality for multiple metrics
+// FetchTemporalityMulti fetches the temporality for multiple metrics.
func (m *MockMetadataStore) FetchTemporalityMulti(ctx context.Context, queryTimeRangeStartTs, queryTimeRangeEndTs uint64, metricNames ...string) (map[string]metrictypes.Temporality, error) {
result := make(map[string]metrictypes.Temporality)
@@ -329,7 +329,7 @@ func (m *MockMetadataStore) FetchTemporalityMulti(ctx context.Context, queryTime
return result, nil
}
-// FetchTemporalityMulti fetches the temporality for multiple metrics
+// FetchTemporalityMulti fetches the temporality for multiple metrics.
func (m *MockMetadataStore) FetchTemporalityAndTypeMulti(ctx context.Context, queryTimeRangeStartTs, queryTimeRangeEndTs uint64, metricNames ...string) (map[string]metrictypes.Temporality, map[string]metrictypes.Type, error) {
temporalities := make(map[string]metrictypes.Temporality)
types := make(map[string]metrictypes.Type)
@@ -350,7 +350,7 @@ func (m *MockMetadataStore) FetchTemporalityAndTypeMulti(ctx context.Context, qu
return temporalities, types, nil
}
-// SetTemporality sets the temporality for a metric in the mock store
+// SetTemporality sets the temporality for a metric in the mock store.
func (m *MockMetadataStore) SetTemporality(metricName string, temporality metrictypes.Temporality) {
m.TemporalityMap[metricName] = temporality
}
diff --git a/pkg/types/telemetrytypes/test_data.go b/pkg/types/telemetrytypes/test_data.go
index c79821adb2..ef4c96f36d 100644
--- a/pkg/types/telemetrytypes/test_data.go
+++ b/pkg/types/telemetrytypes/test_data.go
@@ -4,8 +4,8 @@ package telemetrytypes
// Test JSON Type Set Data Setup
// ============================================================================
-// TestJSONTypeSet returns a map of path->types for testing
-// This represents the type information available in the test JSON structure
+// TestJSONTypeSet returns a map of path->types for testing.
+// This represents the type information available in the test JSON structure.
func TestJSONTypeSet() (map[string][]JSONDataType, MetadataStore) {
types := map[string][]JSONDataType{
"user.name": {String},
diff --git a/pkg/types/thirdpartyapitypes/thirdpartyapi.go b/pkg/types/thirdpartyapitypes/thirdpartyapi.go
index 57dfefe3e8..bc34d911f6 100644
--- a/pkg/types/thirdpartyapitypes/thirdpartyapi.go
+++ b/pkg/types/thirdpartyapitypes/thirdpartyapi.go
@@ -15,7 +15,7 @@ type ThirdPartyApiRequest struct {
GroupBy []qbtypes.GroupByKey `json:"groupBy,omitempty"`
}
-// Validate validates the ThirdPartyApiRequest
+// Validate validates the ThirdPartyApiRequest.
func (req *ThirdPartyApiRequest) Validate() error {
if req.Start >= req.End {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "start time must be before end time")
diff --git a/pkg/types/tracefunneltypes/tracefunnel.go b/pkg/types/tracefunneltypes/tracefunnel.go
index 4eb725e379..f70045942f 100644
--- a/pkg/types/tracefunneltypes/tracefunnel.go
+++ b/pkg/types/tracefunneltypes/tracefunnel.go
@@ -12,7 +12,7 @@ var (
ErrFunnelAlreadyExists = errors.MustNewCode("funnel_already_exists")
)
-// StorableFunnel Core Data Structure (StorableFunnel and FunnelStep)
+// StorableFunnel Core Data Structure (StorableFunnel and FunnelStep).
type StorableFunnel struct {
types.Identifiable
types.TimeAuditable
@@ -39,7 +39,7 @@ type FunnelStep struct {
HasErrors bool `json:"has_errors"`
}
-// PostableFunnel represents all possible funnel-related requests
+// PostableFunnel represents all possible funnel-related requests.
type PostableFunnel struct {
FunnelID valuer.UUID `json:"funnel_id,omitempty"`
Name string `json:"funnel_name,omitempty"`
@@ -55,7 +55,7 @@ type PostableFunnel struct {
StepEnd int64 `json:"step_end,omitempty"`
}
-// GettableFunnel represents all possible funnel-related responses
+// GettableFunnel represents all possible funnel-related responses.
type GettableFunnel struct {
FunnelID string `json:"funnel_id,omitempty"`
FunnelName string `json:"funnel_name,omitempty"`
@@ -70,20 +70,20 @@ type GettableFunnel struct {
Steps []*FunnelStep `json:"steps,omitempty"`
}
-// TimeRange represents a time range for analytics
+// TimeRange represents a time range for analytics.
type TimeRange struct {
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
}
-// StepTransitionRequest represents a request for step transition analytics
+// StepTransitionRequest represents a request for step transition analytics.
type StepTransitionRequest struct {
TimeRange
StepStart int64 `json:"step_start,omitempty"`
StepEnd int64 `json:"step_end,omitempty"`
}
-// UserInfo represents basic user information
+// UserInfo represents basic user information.
type UserInfo struct {
ID string `json:"id"`
Email string `json:"email"`
diff --git a/pkg/types/tracefunneltypes/utils.go b/pkg/types/tracefunneltypes/utils.go
index c839d2500f..8babfc49f2 100644
--- a/pkg/types/tracefunneltypes/utils.go
+++ b/pkg/types/tracefunneltypes/utils.go
@@ -9,7 +9,7 @@ import (
"github.com/SigNoz/signoz/pkg/valuer"
)
-// ValidateTimestamp validates a timestamp
+// ValidateTimestamp validates a timestamp.
func ValidateTimestamp(timestamp int64, fieldName string) error {
if timestamp == 0 {
return errors.NewInvalidInputf(errors.CodeInvalidInput, "%s is required", fieldName)
@@ -20,7 +20,7 @@ func ValidateTimestamp(timestamp int64, fieldName string) error {
return nil
}
-// ValidateTimestampIsMilliseconds validates that a timestamp is in milliseconds
+// ValidateTimestampIsMilliseconds validates that a timestamp is in milliseconds.
func ValidateTimestampIsMilliseconds(timestamp int64) bool {
return timestamp >= 1000000000000 && timestamp <= 9999999999999
}
diff --git a/pkg/types/user.go b/pkg/types/user.go
index b7ba435918..72f07631e9 100644
--- a/pkg/types/user.go
+++ b/pkg/types/user.go
@@ -199,7 +199,7 @@ func (u *User) ErrIfRoot() error {
}
// ErrIfDeleted returns an error if the user is in deleted state.
-// This error can be enriched with specific operation by the called using errors.WithAdditionalf
+// This error can be enriched with specific operation by the called using errors.WithAdditionalf.
func (u *User) ErrIfDeleted() error {
if u.Status == UserStatusDeleted {
return errors.New(errors.TypeUnsupported, ErrCodeUserStatusDeleted, "unsupported operation for deleted user")
@@ -208,7 +208,7 @@ func (u *User) ErrIfDeleted() error {
}
// ErrIfPending returns an error if the user is in pending invite state.
-// This error can be enriched with specific operation by the called using errors.WithAdditionalf
+// This error can be enriched with specific operation by the called using errors.WithAdditionalf.
func (u *User) ErrIfPending() error {
if u.Status == UserStatusPendingInvite {
return errors.New(errors.TypeUnsupported, ErrCodeUserStatusPendingInvite, "unsupported operation for pending user")
diff --git a/pkg/units/converter.go b/pkg/units/converter.go
index 185edf5d52..3cfaca994c 100644
--- a/pkg/units/converter.go
+++ b/pkg/units/converter.go
@@ -1,15 +1,15 @@
package units
-// Unit represents a unit of measurement
+// Unit represents a unit of measurement.
type Unit string
-// Value represents a value with a unit of measurement
+// Value represents a value with a unit of measurement.
type Value struct {
F float64
U Unit
}
-// Converter converts values from one unit to another
+// Converter converts values from one unit to another.
type Converter interface {
// Convert converts the given value to the given unit
Convert(v Value, to Unit) Value
@@ -18,7 +18,7 @@ type Converter interface {
Name() string
}
-// noneConverter is a converter that does not convert
+// noneConverter is a converter that does not convert.
type noneConverter struct{}
func (*noneConverter) Name() string {
@@ -29,7 +29,7 @@ func (c *noneConverter) Convert(v Value, to Unit) Value {
return v
}
-// Converters
+// Converters.
var (
DurationConverter = NewDurationConverter()
DataConverter = NewDataConverter()
@@ -40,7 +40,7 @@ var (
NoneConverter = &noneConverter{}
)
-// ConverterFromUnit returns a converter for the given unit
+// ConverterFromUnit returns a converter for the given unit.
func ConverterFromUnit(u Unit) Converter {
switch u {
case "ns", "us", "µs", "ms", "s", "m", "h", "d", "min", "w", "wk":
diff --git a/pkg/units/converter_bool.go b/pkg/units/converter_bool.go
index 81d4fe1977..f8f5ef602a 100644
--- a/pkg/units/converter_bool.go
+++ b/pkg/units/converter_bool.go
@@ -1,6 +1,6 @@
package units
-// boolConverter is a Converter implementation for bool
+// boolConverter is a Converter implementation for bool.
type boolConverter struct{}
func NewBoolConverter() Converter {
diff --git a/pkg/units/converter_data.go b/pkg/units/converter_data.go
index 772f701613..02c10911f7 100644
--- a/pkg/units/converter_data.go
+++ b/pkg/units/converter_data.go
@@ -1,7 +1,7 @@
package units
const (
- // base 10 (SI prefixes)
+ // base 10 (SI prefixes).
Bit float64 = 1e0
Kilobit = Bit * 1e3
Megabit = Bit * 1e6
@@ -26,7 +26,7 @@ const (
Ronnabyte = Byte * 1e27
Quettabyte = Byte * 1e30
- // base 2 (IEC prefixes)
+ // base 2 (IEC prefixes).
Kibibit = Bit * 1024
Mebibit = Kibibit * 1024
Gibibit = Mebibit * 1024
@@ -63,7 +63,7 @@ func (*dataConverter) Name() string {
// kibi = Ki, mebi = Mi, gibi = Gi, tebi = Ti, pibi = Pi
// kilo = k, mega = M, giga = G, tera = T, peta = P
// exa = E, zetta = Z, yotta = Y
-// byte = By, bit = bit
+// byte = By, bit = bit.
func FromDataUnit(u Unit) float64 {
switch u {
case "bytes", "By": // base 2
diff --git a/pkg/units/converter_data_rate.go b/pkg/units/converter_data_rate.go
index f99506cabe..e6cd767785 100644
--- a/pkg/units/converter_data_rate.go
+++ b/pkg/units/converter_data_rate.go
@@ -1,7 +1,7 @@
package units
const (
- // base 10 (SI prefixes)
+ // base 10 (SI prefixes).
BitPerSecond float64 = 1e0
KilobitPerSecond = BitPerSecond * 1e3
MegabitPerSecond = BitPerSecond * 1e6
@@ -22,7 +22,7 @@ const (
ZettabytePerSecond = BytePerSecond * 1e21
YottabytePerSecond = BytePerSecond * 1e24
- // base 2 (IEC prefixes)
+ // base 2 (IEC prefixes).
KibibitPerSecond = BitPerSecond * 1024
MebibitPerSecond = KibibitPerSecond * 1024
GibibitPerSecond = MebibitPerSecond * 1024
@@ -42,7 +42,7 @@ const (
YobibytePerSecond = ZebibytePerSecond * 1024
)
-// dataRateConverter is a Converter implementation for data rates
+// dataRateConverter is a Converter implementation for data rates.
type dataRateConverter struct {
}
@@ -59,7 +59,7 @@ func (*dataRateConverter) Name() string {
// kibi = Ki, mebi = Mi, gibi = Gi, tebi = Ti, pibi = Pi
// kilo = k, mega = M, giga = G, tera = T, peta = P
// exa = E, zetta = Z, yotta = Y
-// byte = By, bit = bit
+// byte = By, bit = bit.
func FromDataRateUnit(u Unit) float64 {
// See https://github.com/SigNoz/signoz/blob/5a81f5f90b34845f5b4b3bdd46acf29d04bf3987/frontend/src/container/NewWidget/RightContainer/dataFormatCategories.ts#L62-L85
switch u {
diff --git a/pkg/units/converter_percent.go b/pkg/units/converter_percent.go
index 7748695785..fec4c68c83 100644
--- a/pkg/units/converter_percent.go
+++ b/pkg/units/converter_percent.go
@@ -1,6 +1,6 @@
package units
-// percentConverter is a converter for percent unit
+// percentConverter is a converter for percent unit.
type percentConverter struct{}
func NewPercentConverter() Converter {
diff --git a/pkg/units/converter_throughput.go b/pkg/units/converter_throughput.go
index eb6ddc6542..435218d5cd 100644
--- a/pkg/units/converter_throughput.go
+++ b/pkg/units/converter_throughput.go
@@ -1,6 +1,6 @@
package units
-// throughputConverter is an implementation of Converter that converts throughput
+// throughputConverter is an implementation of Converter that converts throughput.
type throughputConverter struct {
}
diff --git a/pkg/units/formatter_time.go b/pkg/units/formatter_time.go
index 025738dfac..44f65af190 100644
--- a/pkg/units/formatter_time.go
+++ b/pkg/units/formatter_time.go
@@ -39,7 +39,7 @@ func (f *durationFormatter) Format(value float64, unit string) string {
return fmt.Sprintf("%v", value)
}
-// toNanoSeconds returns a easy to read string representation of the given value in nanoseconds
+// toNanoSeconds returns a easy to read string representation of the given value in nanoseconds.
func toNanoSeconds(value float64) string {
absValue := math.Abs(value)
@@ -60,7 +60,7 @@ func toNanoSeconds(value float64) string {
}
}
-// toMicroSeconds returns a easy to read string representation of the given value in microseconds
+// toMicroSeconds returns a easy to read string representation of the given value in microseconds.
func toMicroSeconds(value float64) string {
absValue := math.Abs(value)
if absValue < 1000 {
@@ -72,7 +72,7 @@ func toMicroSeconds(value float64) string {
}
}
-// toMilliSeconds returns a easy to read string representation of the given value in milliseconds
+// toMilliSeconds returns a easy to read string representation of the given value in milliseconds.
func toMilliSeconds(value float64) string {
absValue := math.Abs(value)
@@ -92,7 +92,7 @@ func toMilliSeconds(value float64) string {
return toFixedScaled(value/31536000000, " year")
}
-// toSeconds returns a easy to read string representation of the given value in seconds
+// toSeconds returns a easy to read string representation of the given value in seconds.
func toSeconds(value float64) string {
absValue := math.Abs(value)
@@ -117,7 +117,7 @@ func toSeconds(value float64) string {
return toFixedScaled(value/3.15569e7, " year")
}
-// toMinutes returns a easy to read string representation of the given value in minutes
+// toMinutes returns a easy to read string representation of the given value in minutes.
func toMinutes(value float64) string {
absValue := math.Abs(value)
@@ -134,7 +134,7 @@ func toMinutes(value float64) string {
}
}
-// toHours returns a easy to read string representation of the given value in hours
+// toHours returns a easy to read string representation of the given value in hours.
func toHours(value float64) string {
absValue := math.Abs(value)
@@ -150,7 +150,7 @@ func toHours(value float64) string {
}
}
-// toDays returns a easy to read string representation of the given value in days
+// toDays returns a easy to read string representation of the given value in days.
func toDays(value float64) string {
absValue := math.Abs(value)
@@ -163,7 +163,7 @@ func toDays(value float64) string {
}
}
-// toWeeks returns a easy to read string representation of the given value in weeks
+// toWeeks returns a easy to read string representation of the given value in weeks.
func toWeeks(value float64) string {
absValue := math.Abs(value)
diff --git a/pkg/valuer/string.go b/pkg/valuer/string.go
index 2e22805768..c807472672 100644
--- a/pkg/valuer/string.go
+++ b/pkg/valuer/string.go
@@ -79,7 +79,7 @@ func (enum String) MarshalText() (text []byte, err error) {
}
// Implement Gin's BindUnmarshaler interface
-// See https://github.com/SigNoz/signoz/pull/10219 description for additional details
+// See https://github.com/SigNoz/signoz/pull/10219 description for additional details.
func (enum *String) UnmarshalParam(param string) error {
*enum = NewString(param)
return nil
diff --git a/pkg/variables/clickhouse/processor.go b/pkg/variables/clickhouse/processor.go
index c630e4121f..e76a2d0c30 100644
--- a/pkg/variables/clickhouse/processor.go
+++ b/pkg/variables/clickhouse/processor.go
@@ -7,32 +7,32 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
)
-// FilterAction represents what to do with a filter containing a variable
+// FilterAction represents what to do with a filter containing a variable.
type FilterAction int
const (
- // KeepFilter maintains the original filter
+ // KeepFilter maintains the original filter.
KeepFilter FilterAction = iota
- // RemoveFilter completely removes the filter
+ // RemoveFilter completely removes the filter.
RemoveFilter
- // ReplaceWithExistsCheck replaces filter with an EXISTS check
+ // ReplaceWithExistsCheck replaces filter with an EXISTS check.
ReplaceWithExistsCheck
)
// FilterTransformer defines the callback function that decides
-// what to do with a filter containing a variable
+// what to do with a filter containing a variable.
type FilterTransformer func(variableName string, expr parser.Expr) FilterAction
-// QueryProcessor handles ClickHouse query modifications
+// QueryProcessor handles ClickHouse query modifications.
type QueryProcessor struct {
}
-// NewQueryProcessor creates a new processor
+// NewQueryProcessor creates a new processor.
func NewQueryProcessor() *QueryProcessor {
return &QueryProcessor{}
}
-// ProcessQuery finds variables in WHERE clauses and modifies them according to the transformer function
+// ProcessQuery finds variables in WHERE clauses and modifies them according to the transformer function.
func (qp *QueryProcessor) ProcessQuery(query string, transformer FilterTransformer) (string, error) {
p := parser.NewParser(query)
stmts, err := p.ParseStmts()
@@ -76,7 +76,7 @@ func (qp *QueryProcessor) ProcessQuery(query string, transformer FilterTransform
return resultBuilder.String(), nil
}
-// processWhereClause processes the WHERE clause in a SELECT statement
+// processWhereClause processes the WHERE clause in a SELECT statement.
func (qp *QueryProcessor) processWhereClause(selectQuery *parser.SelectQuery, transformer FilterTransformer) (bool, error) {
// First, process any subqueries in the FROM clause
if selectQuery.From != nil {
@@ -115,7 +115,7 @@ func (qp *QueryProcessor) processWhereClause(selectQuery *parser.SelectQuery, tr
return modified, nil
}
-// processFromClauseSubqueries recursively processes subqueries in the FROM clause
+// processFromClauseSubqueries recursively processes subqueries in the FROM clause.
func (qp *QueryProcessor) processFromClauseSubqueries(fromClause *parser.FromClause, transformer FilterTransformer) (bool, error) {
if fromClause == nil {
return false, nil
@@ -124,7 +124,7 @@ func (qp *QueryProcessor) processFromClauseSubqueries(fromClause *parser.FromCla
return qp.processExprSubqueries(fromClause.Expr, transformer)
}
-// processExprSubqueries processes subqueries found in expressions
+// processExprSubqueries processes subqueries found in expressions.
func (qp *QueryProcessor) processExprSubqueries(expr parser.Expr, transformer FilterTransformer) (bool, error) {
if expr == nil {
return false, nil
@@ -209,7 +209,7 @@ func (qp *QueryProcessor) processExprSubqueries(expr parser.Expr, transformer Fi
return modified, nil
}
-// transformExpr recursively processes expressions in the WHERE clause
+// transformExpr recursively processes expressions in the WHERE clause.
func (qp *QueryProcessor) transformExpr(expr parser.Expr, transformer FilterTransformer) (parser.Expr, bool, error) {
if expr == nil {
return nil, false, nil
@@ -347,7 +347,7 @@ func (qp *QueryProcessor) transformExpr(expr parser.Expr, transformer FilterTran
}
// isComplexExpression checks if an expression contains nested operations
-// that should not be treated as a simple variable reference
+// that should not be treated as a simple variable reference.
func (qp *QueryProcessor) isComplexExpression(expr parser.Expr) bool {
switch e := expr.(type) {
case *parser.BinaryOperation:
@@ -366,7 +366,7 @@ func (qp *QueryProcessor) isComplexExpression(expr parser.Expr) bool {
return false
}
-// findVariables finds all variables in an expression
+// findVariables finds all variables in an expression.
func (qp *QueryProcessor) findVariables(expr parser.Expr) []string {
var variables []string
@@ -415,7 +415,7 @@ func (qp *QueryProcessor) findVariables(expr parser.Expr) []string {
return variables
}
-// createExistsCheck creates an EXISTS check for a column/map field
+// createExistsCheck creates an EXISTS check for a column/map field.
func (qp *QueryProcessor) createExistsCheck(expr parser.Expr, _ string) (parser.Expr, bool, error) {
switch e := expr.(type) {
case *parser.BinaryOperation:
diff --git a/pkg/variables/clickhouse/transform.go b/pkg/variables/clickhouse/transform.go
index 40914dab90..75cd171c30 100644
--- a/pkg/variables/clickhouse/transform.go
+++ b/pkg/variables/clickhouse/transform.go
@@ -9,7 +9,7 @@ import (
"github.com/SigNoz/signoz/pkg/variables"
)
-// VariableValue represents a variable's assigned value
+// VariableValue represents a variable's assigned value.
type VariableValue struct {
Name string
Values []string
@@ -17,14 +17,14 @@ type VariableValue struct {
FieldType string // "scalar", "array", "map", etc.
}
-// QueryTransformer handles the transformation of queries based on variable values
+// QueryTransformer handles the transformation of queries based on variable values.
type QueryTransformer struct {
processor *QueryProcessor
variables map[string]VariableValue
originalSQL string
}
-// NewQueryTransformer creates a new transformer with the given SQL and variables
+// NewQueryTransformer creates a new transformer with the given SQL and variables.
func NewQueryTransformer(sql string, vars []VariableValue) *QueryTransformer {
varMap := make(map[string]VariableValue)
for _, v := range vars {
@@ -45,10 +45,10 @@ func NewQueryTransformer(sql string, vars []VariableValue) *QueryTransformer {
// for each variable, replace the `{{variable_name}}`, [[variable_name]], {{ .variable_name }}, {{.variable_name}}
// with $variable_name
for name := range varMap {
- sql = strings.Replace(sql, fmt.Sprintf("{{%s}}", name), fmt.Sprintf("$%s", name), -1)
- sql = strings.Replace(sql, fmt.Sprintf("[[%s]]", name), fmt.Sprintf("$%s", name), -1)
- sql = strings.Replace(sql, fmt.Sprintf("{{ .%s }}", name), fmt.Sprintf("$%s", name), -1)
- sql = strings.Replace(sql, fmt.Sprintf("{{.%s}}", name), fmt.Sprintf("$%s", name), -1)
+ sql = strings.ReplaceAll(sql, fmt.Sprintf("{{%s}}", name), fmt.Sprintf("$%s", name))
+ sql = strings.ReplaceAll(sql, fmt.Sprintf("[[%s]]", name), fmt.Sprintf("$%s", name))
+ sql = strings.ReplaceAll(sql, fmt.Sprintf("{{ .%s }}", name), fmt.Sprintf("$%s", name))
+ sql = strings.ReplaceAll(sql, fmt.Sprintf("{{.%s}}", name), fmt.Sprintf("$%s", name))
}
return &QueryTransformer{
@@ -58,12 +58,12 @@ func NewQueryTransformer(sql string, vars []VariableValue) *QueryTransformer {
}
}
-// Transform processes the query and returns a transformed version
+// Transform processes the query and returns a transformed version.
func (t *QueryTransformer) Transform() (string, error) {
return t.processor.ProcessQuery(t.originalSQL, t.transformFilter)
}
-// transformFilter is the callback function that decides what to do with each filter
+// transformFilter is the callback function that decides what to do with each filter.
func (t *QueryTransformer) transformFilter(variableName string, expr parser.Expr) FilterAction {
// Check if we have info about this variable
varInfo, exists := t.variables[variableName]
diff --git a/pkg/variables/variable_replace_visitor.go b/pkg/variables/variable_replace_visitor.go
index c31660b34e..06ffa21ffb 100644
--- a/pkg/variables/variable_replace_visitor.go
+++ b/pkg/variables/variable_replace_visitor.go
@@ -11,13 +11,13 @@ import (
"github.com/antlr4-go/antlr/v4"
)
-// ErrorListener collects syntax errors during parsing
+// ErrorListener collects syntax errors during parsing.
type ErrorListener struct {
*antlr.DefaultErrorListener
SyntaxErrors []error
}
-// NewErrorListener creates a new error listener
+// NewErrorListener creates a new error listener.
func NewErrorListener() *ErrorListener {
return &ErrorListener{
DefaultErrorListener: antlr.NewDefaultErrorListener(),
@@ -25,22 +25,22 @@ func NewErrorListener() *ErrorListener {
}
}
-// SyntaxError is called when a syntax error is encountered
+// SyntaxError is called when a syntax error is encountered.
func (e *ErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, ex antlr.RecognitionException) {
e.SyntaxErrors = append(e.SyntaxErrors, errors.NewInvalidInputf(errors.CodeInvalidInput, "line %d:%d %s", line, column, msg))
}
// variableReplacementVisitor implements the visitor interface
-// to replace variables in filter expressions with their actual values
+// to replace variables in filter expressions with their actual values.
type variableReplacementVisitor struct {
variables map[string]qbtypes.VariableItem
errors []string
}
-// specialSkipMarker is used to indicate that a condition should be removed
+// specialSkipMarker is used to indicate that a condition should be removed.
const specialSkipMarker = "__SKIP_CONDITION__"
-// ReplaceVariablesInExpression takes a filter expression and returns it with variables replaced
+// ReplaceVariablesInExpression takes a filter expression and returns it with variables replaced.
func ReplaceVariablesInExpression(expression string, variables map[string]qbtypes.VariableItem) (string, error) {
input := antlr.NewInputStream(expression)
lexer := grammar.NewFilterQueryLexer(input)
@@ -80,7 +80,7 @@ func ReplaceVariablesInExpression(expression string, variables map[string]qbtype
return result, nil
}
-// Visit dispatches to the specific visit method based on node type
+// Visit dispatches to the specific visit method based on node type.
func (v *variableReplacementVisitor) Visit(tree antlr.ParseTree) any {
if tree == nil {
return ""
@@ -517,7 +517,7 @@ func (v *variableReplacementVisitor) VisitKey(ctx *grammar.KeyContext) any {
return keyText
}
-// formatVariableValue formats a variable value for inclusion in the expression
+// formatVariableValue formats a variable value for inclusion in the expression.
func (v *variableReplacementVisitor) formatVariableValue(value any) string {
switch val := value.(type) {
case string: