Skip to content

Commit a3f32b3

Browse files
fix(comment): add a dedicated comment parsing middleware (#8855)
## 📄 Summary - add a dedicated comment parsing middleware. This removes duplication and double parsing of referrer.
1 parent 9c2f127 commit a3f32b3

File tree

14 files changed

+344
-192
lines changed

14 files changed

+344
-192
lines changed

ee/query-service/app/server.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*h
257257
s.config.APIServer.Timeout.Max,
258258
).Wrap)
259259
r.Use(middleware.NewLogging(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes).Wrap)
260+
r.Use(middleware.NewComment().Wrap)
260261

261262
apiHandler.RegisterRoutes(r, am)
262263
apiHandler.RegisterLogsRoutes(r, am)

pkg/http/middleware/api_key.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/SigNoz/signoz/pkg/sqlstore"
1010
"github.com/SigNoz/signoz/pkg/types"
1111
"github.com/SigNoz/signoz/pkg/types/authtypes"
12+
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
1213
"github.com/SigNoz/signoz/pkg/valuer"
1314
)
1415

@@ -97,7 +98,12 @@ func (a *APIKey) Wrap(next http.Handler) http.Handler {
9798
return
9899
}
99100

100-
r = r.WithContext(ctx)
101+
comment := ctxtypes.CommentFromContext(ctx)
102+
comment.Set("auth_type", "api_key")
103+
comment.Set("user_id", claims.UserID)
104+
comment.Set("org_id", claims.OrgID)
105+
106+
r = r.WithContext(ctxtypes.NewContextWithComment(ctx, comment))
101107

102108
next.ServeHTTP(w, r)
103109

pkg/http/middleware/auth.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"github.com/SigNoz/signoz/pkg/sharder"
88
"github.com/SigNoz/signoz/pkg/types"
99
"github.com/SigNoz/signoz/pkg/types/authtypes"
10+
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
1011
"github.com/SigNoz/signoz/pkg/valuer"
1112
)
1213

@@ -50,7 +51,12 @@ func (a *Auth) Wrap(next http.Handler) http.Handler {
5051
return
5152
}
5253

53-
r = r.WithContext(ctx)
54+
comment := ctxtypes.CommentFromContext(ctx)
55+
comment.Set("auth_type", "jwt")
56+
comment.Set("user_id", claims.UserID)
57+
comment.Set("org_id", claims.OrgID)
58+
59+
r = r.WithContext(ctxtypes.NewContextWithComment(ctx, comment))
5460

5561
next.ServeHTTP(w, r)
5662
})

pkg/http/middleware/comment.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package middleware
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
7+
)
8+
9+
type Comment struct{}
10+
11+
func NewComment() *Comment {
12+
return &Comment{}
13+
}
14+
15+
func (middleware *Comment) Wrap(next http.Handler) http.Handler {
16+
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
17+
18+
comment := ctxtypes.CommentFromContext(req.Context())
19+
comment.Merge(ctxtypes.CommentFromHTTPRequest(req))
20+
21+
req = req.WithContext(ctxtypes.NewContextWithComment(req.Context(), comment))
22+
next.ServeHTTP(rw, req)
23+
})
24+
}

pkg/http/middleware/logging.go

Lines changed: 0 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,11 @@ package middleware
22

33
import (
44
"bytes"
5-
"context"
65
"log/slog"
76
"net"
87
"net/http"
9-
"net/url"
10-
"strings"
118
"time"
129

13-
"github.com/SigNoz/signoz/pkg/query-service/common"
14-
"github.com/SigNoz/signoz/pkg/types/authtypes"
1510
"github.com/gorilla/mux"
1611
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
1712
)
@@ -55,9 +50,6 @@ func (middleware *Logging) Wrap(next http.Handler) http.Handler {
5550
string(semconv.HTTPRouteKey), path,
5651
}
5752

58-
logCommentKVs := middleware.getLogCommentKVs(req)
59-
req = req.WithContext(context.WithValue(req.Context(), common.LogCommentKey, logCommentKVs))
60-
6153
badResponseBuffer := new(bytes.Buffer)
6254
writer := newBadResponseLoggingWriter(rw, badResponseBuffer)
6355
next.ServeHTTP(writer, req)
@@ -85,67 +77,3 @@ func (middleware *Logging) Wrap(next http.Handler) http.Handler {
8577
}
8678
})
8779
}
88-
89-
func (middleware *Logging) getLogCommentKVs(r *http.Request) map[string]string {
90-
referrer := r.Header.Get("Referer")
91-
92-
var path, dashboardID, alertID, page, client, viewName, tab string
93-
94-
if referrer != "" {
95-
referrerURL, _ := url.Parse(referrer)
96-
client = "browser"
97-
path = referrerURL.Path
98-
99-
if strings.Contains(path, "/dashboard") {
100-
// Split the path into segments
101-
pathSegments := strings.Split(referrerURL.Path, "/")
102-
// The dashboard ID should be the segment after "/dashboard/"
103-
// Loop through pathSegments to find "dashboard" and then take the next segment as the ID
104-
for i, segment := range pathSegments {
105-
if segment == "dashboard" && i < len(pathSegments)-1 {
106-
// Return the next segment, which should be the dashboard ID
107-
dashboardID = pathSegments[i+1]
108-
}
109-
}
110-
page = "dashboards"
111-
} else if strings.Contains(path, "/alerts") {
112-
urlParams := referrerURL.Query()
113-
alertID = urlParams.Get("ruleId")
114-
page = "alerts"
115-
} else if strings.Contains(path, "logs") && strings.Contains(path, "explorer") {
116-
page = "logs-explorer"
117-
viewName = referrerURL.Query().Get("viewName")
118-
} else if strings.Contains(path, "/trace") || strings.Contains(path, "traces-explorer") {
119-
page = "traces-explorer"
120-
viewName = referrerURL.Query().Get("viewName")
121-
} else if strings.Contains(path, "/services") {
122-
page = "services"
123-
tab = referrerURL.Query().Get("tab")
124-
if tab == "" {
125-
tab = "OVER_METRICS"
126-
}
127-
} else if strings.Contains(path, "/metrics") {
128-
page = "metrics-explorer"
129-
}
130-
} else {
131-
client = "api"
132-
}
133-
134-
var email string
135-
claims, err := authtypes.ClaimsFromContext(r.Context())
136-
if err == nil {
137-
email = claims.Email
138-
}
139-
140-
kvs := map[string]string{
141-
"path": path,
142-
"dashboardID": dashboardID,
143-
"alertID": alertID,
144-
"source": page,
145-
"client": client,
146-
"viewName": viewName,
147-
"servicesTab": tab,
148-
"email": email,
149-
}
150-
return kvs
151-
}

pkg/querier/api.go

Lines changed: 4 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import (
44
"context"
55
"encoding/json"
66
"net/http"
7-
"regexp"
87
"runtime/debug"
98

109
"github.com/SigNoz/signoz/pkg/analytics"
1110
"github.com/SigNoz/signoz/pkg/errors"
1211
"github.com/SigNoz/signoz/pkg/factory"
1312
"github.com/SigNoz/signoz/pkg/http/render"
1413
"github.com/SigNoz/signoz/pkg/types/authtypes"
14+
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
1515
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
1616
"github.com/SigNoz/signoz/pkg/valuer"
1717
"github.com/SigNoz/signoz/pkg/variables"
@@ -166,49 +166,9 @@ func (a *API) logEvent(ctx context.Context, referrer string, event *qbtypes.QBEv
166166
return
167167
}
168168

169-
properties["referrer"] = referrer
170-
171-
logsExplorerMatched, _ := regexp.MatchString(`/logs/logs-explorer(?:\?.*)?$`, referrer)
172-
traceExplorerMatched, _ := regexp.MatchString(`/traces-explorer(?:\?.*)?$`, referrer)
173-
metricsExplorerMatched, _ := regexp.MatchString(`/metrics-explorer/explorer(?:\?.*)?$`, referrer)
174-
dashboardMatched, _ := regexp.MatchString(`/dashboard/[a-zA-Z0-9\-]+/(new|edit)(?:\?.*)?$`, referrer)
175-
alertMatched, _ := regexp.MatchString(`/alerts/(new|edit)(?:\?.*)?$`, referrer)
176-
177-
switch {
178-
case dashboardMatched:
179-
properties["module_name"] = "dashboard"
180-
case alertMatched:
181-
properties["module_name"] = "rule"
182-
case metricsExplorerMatched:
183-
properties["module_name"] = "metrics-explorer"
184-
case logsExplorerMatched:
185-
properties["module_name"] = "logs-explorer"
186-
case traceExplorerMatched:
187-
properties["module_name"] = "traces-explorer"
188-
default:
189-
return
190-
}
191-
192-
if dashboardMatched {
193-
if dashboardIDRegex, err := regexp.Compile(`/dashboard/([a-f0-9\-]+)/`); err == nil {
194-
if matches := dashboardIDRegex.FindStringSubmatch(referrer); len(matches) > 1 {
195-
properties["dashboard_id"] = matches[1]
196-
}
197-
}
198-
199-
if widgetIDRegex, err := regexp.Compile(`widgetId=([a-f0-9\-]+)`); err == nil {
200-
if matches := widgetIDRegex.FindStringSubmatch(referrer); len(matches) > 1 {
201-
properties["widget_id"] = matches[1]
202-
}
203-
}
204-
}
205-
206-
if alertMatched {
207-
if alertIDRegex, err := regexp.Compile(`ruleId=(\d+)`); err == nil {
208-
if matches := alertIDRegex.FindStringSubmatch(referrer); len(matches) > 1 {
209-
properties["rule_id"] = matches[1]
210-
}
211-
}
169+
comments := ctxtypes.CommentFromContext(ctx).Map()
170+
for key, value := range comments {
171+
properties[key] = value
212172
}
213173

214174
if !event.HasData {

pkg/query-service/app/clickhouseReader/reader.go

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3640,28 +3640,8 @@ func readRowsForTimeSeriesResult(rows driver.Rows, vars []interface{}, columnNam
36403640
return seriesList, getPersonalisedError(rows.Err())
36413641
}
36423642

3643-
func logCommentKVs(ctx context.Context) map[string]string {
3644-
kv := ctx.Value(common.LogCommentKey)
3645-
if kv == nil {
3646-
return nil
3647-
}
3648-
logCommentKVs, ok := kv.(map[string]string)
3649-
if !ok {
3650-
return nil
3651-
}
3652-
return logCommentKVs
3653-
}
3654-
36553643
// GetTimeSeriesResultV3 runs the query and returns list of time series
36563644
func (r *ClickHouseReader) GetTimeSeriesResultV3(ctx context.Context, query string) ([]*v3.Series, error) {
3657-
3658-
ctxArgs := map[string]interface{}{"query": query}
3659-
for k, v := range logCommentKVs(ctx) {
3660-
ctxArgs[k] = v
3661-
}
3662-
3663-
defer utils.Elapsed("GetTimeSeriesResultV3", ctxArgs)()
3664-
36653645
// Hook up query progress reporting if requested.
36663646
queryId := ctx.Value("queryId")
36673647
if queryId != nil {
@@ -3725,20 +3705,12 @@ func (r *ClickHouseReader) GetTimeSeriesResultV3(ctx context.Context, query stri
37253705

37263706
// GetListResultV3 runs the query and returns list of rows
37273707
func (r *ClickHouseReader) GetListResultV3(ctx context.Context, query string) ([]*v3.Row, error) {
3728-
3729-
ctxArgs := map[string]interface{}{"query": query}
3730-
for k, v := range logCommentKVs(ctx) {
3731-
ctxArgs[k] = v
3732-
}
3733-
3734-
defer utils.Elapsed("GetListResultV3", ctxArgs)()
3735-
37363708
rows, err := r.db.Query(ctx, query)
3737-
37383709
if err != nil {
37393710
zap.L().Error("error while reading time series result", zap.Error(err))
37403711
return nil, errors.New(err.Error())
37413712
}
3713+
37423714
defer rows.Close()
37433715

37443716
var (

pkg/query-service/app/server.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ func (s *Server) createPublicServer(api *APIHandler, web web.Web) (*http.Server,
220220
).Wrap)
221221
r.Use(middleware.NewAPIKey(s.signoz.SQLStore, []string{"SIGNOZ-API-KEY"}, s.signoz.Instrumentation.Logger(), s.signoz.Sharder).Wrap)
222222
r.Use(middleware.NewLogging(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes).Wrap)
223+
r.Use(middleware.NewComment().Wrap)
223224

224225
am := middleware.NewAuthZ(s.signoz.Instrumentation.Logger())
225226

pkg/query-service/common/ctx.go

Lines changed: 0 additions & 5 deletions
This file was deleted.

pkg/query-service/rules/prom_rule_task.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"sync"
88
"time"
99

10-
"github.com/SigNoz/signoz/pkg/query-service/common"
10+
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
1111
ruletypes "github.com/SigNoz/signoz/pkg/types/ruletypes"
1212
"github.com/SigNoz/signoz/pkg/valuer"
1313
opentracing "github.com/opentracing/opentracing-go"
@@ -369,12 +369,10 @@ func (g *PromRuleTask) Eval(ctx context.Context, ts time.Time) {
369369
rule.SetEvaluationTimestamp(t)
370370
}(time.Now())
371371

372-
kvs := map[string]string{
373-
"alertID": rule.ID(),
374-
"source": "alerts",
375-
"client": "query-service",
376-
}
377-
ctx = context.WithValue(ctx, common.LogCommentKey, kvs)
372+
comment := ctxtypes.CommentFromContext(ctx)
373+
comment.Set("rule_id", rule.ID())
374+
comment.Set("auth_type", "internal")
375+
ctx = ctxtypes.NewContextWithComment(ctx, comment)
378376

379377
_, err := rule.Eval(ctx, ts)
380378
if err != nil {

0 commit comments

Comments
 (0)