Skip to content
This repository was archived by the owner on Nov 7, 2025. It is now read-only.

Commit 459ace6

Browse files
authored
Refactoring : changing routerV2 to dispatcher (#1216)
Currently, we have two `router_v2.go` files, which is very confusing: - one is member of `frontend_connector` package and is responsible for dispatching - second is a member of `quesma` package and contains logic for `http` routing definition This PR updates the first one.
1 parent a048ec7 commit 459ace6

File tree

3 files changed

+48
-48
lines changed

3 files changed

+48
-48
lines changed

quesma/frontend_connectors/basic_http_frontend_connector.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ type BasicHTTPFrontendConnector struct {
2222
mutex sync.Mutex
2323
responseMutator func(w http.ResponseWriter) http.ResponseWriter
2424
endpoint string
25-
routerInstance *RouterV2
25+
dispatcher *Dispatcher
2626
logManager *clickhouse.LogManager
2727
registry schema.Registry
2828
config *config.QuesmaConfiguration
@@ -40,8 +40,8 @@ func (h *BasicHTTPFrontendConnector) GetChildComponents() []interface{} {
4040
components = append(components, h.router)
4141
}
4242

43-
if h.routerInstance != nil {
44-
components = append(components, h.routerInstance)
43+
if h.dispatcher != nil {
44+
components = append(components, h.dispatcher)
4545
}
4646
return components
4747
}
@@ -52,18 +52,18 @@ func (h *BasicHTTPFrontendConnector) SetDependencies(deps quesma_api.Dependencie
5252
h.logger = deps.Logger()
5353

5454
deps.PhoneHomeAgent().FailedRequestsCollector(func() int64 {
55-
return h.routerInstance.FailedRequests.Load()
55+
return h.dispatcher.FailedRequests.Load()
5656
})
5757
}
5858

5959
func NewBasicHTTPFrontendConnector(endpoint string, config *config.QuesmaConfiguration) *BasicHTTPFrontendConnector {
6060

6161
return &BasicHTTPFrontendConnector{
62-
endpoint: endpoint,
63-
config: config,
64-
routerInstance: NewRouterV2(config),
65-
logManager: nil,
66-
registry: nil,
62+
endpoint: endpoint,
63+
config: config,
64+
dispatcher: NewDispatcher(config),
65+
logManager: nil,
66+
registry: nil,
6767
responseMutator: func(w http.ResponseWriter) http.ResponseWriter {
6868
return w
6969
},
@@ -127,7 +127,7 @@ func (h *BasicHTTPFrontendConnector) finalHandler(w http.ResponseWriter, req *ht
127127
h.phoneHomeClient.UserAgentCounters().Add(ua, 1)
128128
}
129129

130-
h.routerInstance.Reroute(req.Context(), w, req, reqBody, h.router, h.logManager, h.registry)
130+
h.dispatcher.Reroute(req.Context(), w, req, reqBody, h.router, h.logManager, h.registry)
131131
}
132132

133133
func (h *BasicHTTPFrontendConnector) Listen() error {
@@ -175,8 +175,8 @@ func ReadRequestBody(request *http.Request) ([]byte, error) {
175175
return reqBody, nil
176176
}
177177

178-
func (h *BasicHTTPFrontendConnector) GetRouterInstance() *RouterV2 {
179-
return h.routerInstance
178+
func (h *BasicHTTPFrontendConnector) GetDispatcherInstance() *Dispatcher {
179+
return h.dispatcher
180180
}
181181

182182
func (h *BasicHTTPFrontendConnector) AddMiddleware(middleware http.Handler) {

quesma/frontend_connectors/router_v2.go renamed to quesma/frontend_connectors/dispatcher.go

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,12 @@ import (
3232
"time"
3333
)
3434

35-
func responseFromElasticV2(ctx context.Context, elkResponse *http.Response, w http.ResponseWriter) {
35+
func responseFromElastic(ctx context.Context, elkResponse *http.Response, w http.ResponseWriter) {
3636
if id, ok := ctx.Value(tracing.RequestIdCtxKey).(string); ok {
3737
logger.Debug().Str(logger.RID, id).Msg("responding from Elasticsearch")
3838
}
3939

40-
copyHeadersV2(w, elkResponse)
40+
copyHeaders(w, elkResponse)
4141
w.Header().Set(QuesmaSourceHeader, QuesmaSourceElastic)
4242
// io.Copy calls WriteHeader implicitly
4343
w.WriteHeader(elkResponse.StatusCode)
@@ -49,7 +49,7 @@ func responseFromElasticV2(ctx context.Context, elkResponse *http.Response, w ht
4949
elkResponse.Body.Close()
5050
}
5151

52-
func responseFromQuesmaV2(ctx context.Context, unzipped []byte, w http.ResponseWriter, quesmaResponse *quesma_api.Result, zip bool) {
52+
func responseFromQuesma(ctx context.Context, unzipped []byte, w http.ResponseWriter, quesmaResponse *quesma_api.Result, zip bool) {
5353
if quesmaResponse == nil {
5454
logger.Error().Msg("responseFromQuesmaV2: quesmaResponse is nil")
5555
return
@@ -75,7 +75,7 @@ func responseFromQuesmaV2(ctx context.Context, unzipped []byte, w http.ResponseW
7575
}
7676
}
7777

78-
type RouterV2 struct {
78+
type Dispatcher struct {
7979
Config *config.QuesmaConfiguration
8080
RequestPreprocessors quesma_api.ProcessorChain
8181

@@ -86,11 +86,11 @@ type RouterV2 struct {
8686
phoneHomeAgent diag.PhoneHomeClient
8787
}
8888

89-
func (r *RouterV2) SetDependencies(deps quesma_api.Dependencies) {
89+
func (r *Dispatcher) SetDependencies(deps quesma_api.Dependencies) {
9090
r.debugInfoCollector = deps.DebugInfoCollector()
9191
r.phoneHomeAgent = deps.PhoneHomeAgent()
9292
}
93-
func NewRouterV2(config *config.QuesmaConfiguration) *RouterV2 {
93+
func NewDispatcher(config *config.QuesmaConfiguration) *Dispatcher {
9494
tr := &http.Transport{
9595
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
9696
}
@@ -101,18 +101,18 @@ func NewRouterV2(config *config.QuesmaConfiguration) *RouterV2 {
101101
requestProcessors := quesma_api.ProcessorChain{}
102102
requestProcessors = append(requestProcessors, quesma_api.NewTraceIdPreprocessor())
103103

104-
return &RouterV2{
104+
return &Dispatcher{
105105
Config: config,
106106
RequestPreprocessors: requestProcessors,
107107
HttpClient: client,
108108
}
109109
}
110110

111-
func (r *RouterV2) RegisterPreprocessor(preprocessor quesma_api.RequestPreprocessor) {
111+
func (r *Dispatcher) RegisterPreprocessor(preprocessor quesma_api.RequestPreprocessor) {
112112
r.RequestPreprocessors = append(r.RequestPreprocessors, preprocessor)
113113
}
114114

115-
func (r *RouterV2) errorResponseV2(ctx context.Context, err error, w http.ResponseWriter) {
115+
func (r *Dispatcher) errorResponse(ctx context.Context, err error, w http.ResponseWriter) {
116116
r.FailedRequests.Add(1)
117117

118118
msg := "Internal Quesma Error.\nPlease contact support if the problem persists."
@@ -140,10 +140,10 @@ func (r *RouterV2) errorResponseV2(ctx context.Context, err error, w http.Respon
140140

141141
// We should not send our error message to the client. There can be sensitive information in it.
142142
// We will send ID of failed request instead
143-
responseFromQuesmaV2(ctx, []byte(fmt.Sprintf("%s\nRequest ID: %s\n", msg, requestId)), w, result, false)
143+
responseFromQuesma(ctx, []byte(fmt.Sprintf("%s\nRequest ID: %s\n", msg, requestId)), w, result, false)
144144
}
145145

146-
func (*RouterV2) closedIndexResponse(ctx context.Context, w http.ResponseWriter, pattern string) {
146+
func (*Dispatcher) closedIndexResponse(ctx context.Context, w http.ResponseWriter, pattern string) {
147147
// TODO we should return a proper status code here (400?)
148148
w.WriteHeader(http.StatusOK)
149149

@@ -170,7 +170,7 @@ func (*RouterV2) closedIndexResponse(ctx context.Context, w http.ResponseWriter,
170170

171171
}
172172

173-
func (r *RouterV2) ElasticFallback(decision *quesma_api.Decision,
173+
func (r *Dispatcher) ElasticFallback(decision *quesma_api.Decision,
174174
ctx context.Context, w http.ResponseWriter,
175175
req *http.Request, reqBody []byte, logManager *clickhouse.LogManager, schemaRegistry schema.Registry) {
176176

@@ -181,7 +181,7 @@ func (r *RouterV2) ElasticFallback(decision *quesma_api.Decision,
181181
if decision.Err != nil {
182182
w.Header().Set(QuesmaSourceHeader, QuesmaSourceClickhouse)
183183
AddProductAndContentHeaders(req.Header, w.Header())
184-
r.errorResponseV2(ctx, decision.Err, w)
184+
r.errorResponse(ctx, decision.Err, w)
185185
return
186186
}
187187

@@ -224,7 +224,7 @@ func (r *RouterV2) ElasticFallback(decision *quesma_api.Decision,
224224
rawResponse := <-r.sendHttpRequestToElastic(ctx, req, reqBody, true)
225225
response := rawResponse.response
226226
if response != nil {
227-
responseFromElasticV2(ctx, response, w)
227+
responseFromElastic(ctx, response, w)
228228
} else {
229229
w.Header().Set(QuesmaSourceHeader, QuesmaSourceElastic)
230230
w.WriteHeader(500)
@@ -233,11 +233,11 @@ func (r *RouterV2) ElasticFallback(decision *quesma_api.Decision,
233233
}
234234
}
235235
} else {
236-
r.errorResponseV2(ctx, end_user_errors.ErrNoConnector.New(fmt.Errorf("no connector found")), w)
236+
r.errorResponse(ctx, end_user_errors.ErrNoConnector.New(fmt.Errorf("no connector found")), w)
237237
}
238238
}
239239

240-
func (r *RouterV2) Reroute(ctx context.Context, w http.ResponseWriter, req *http.Request, reqBody []byte, router quesma_api.Router, logManager *clickhouse.LogManager, schemaRegistry schema.Registry) {
240+
func (r *Dispatcher) Reroute(ctx context.Context, w http.ResponseWriter, req *http.Request, reqBody []byte, router quesma_api.Router, logManager *clickhouse.LogManager, schemaRegistry schema.Registry) {
241241
defer recovery.LogAndHandlePanic(ctx, func(err error) {
242242
w.WriteHeader(500)
243243
w.Write(queryparser.InternalQuesmaError("Unknown Quesma error"))
@@ -270,7 +270,7 @@ func (r *RouterV2) Reroute(ctx context.Context, w http.ResponseWriter, req *http
270270
}
271271
dispatcher := &quesma_api.Dispatcher{}
272272
if handlersPipe != nil {
273-
quesmaResponse, err := recordRequestToClickhouseV2(req.URL.Path, r.debugInfoCollector, func() (*quesma_api.Result, error) {
273+
quesmaResponse, err := recordRequestToClickhouse(req.URL.Path, r.debugInfoCollector, func() (*quesma_api.Result, error) {
274274
var result *quesma_api.Result
275275
result, err = handlersPipe.Handler(ctx, quesmaRequest, w)
276276

@@ -318,10 +318,10 @@ func (r *RouterV2) Reroute(ctx context.Context, w http.ResponseWriter, req *http
318318
}
319319
AddProductAndContentHeaders(req.Header, w.Header())
320320

321-
responseFromQuesmaV2(ctx, unzipped, w, quesmaResponse, zip)
321+
responseFromQuesma(ctx, unzipped, w, quesmaResponse, zip)
322322

323323
} else {
324-
r.errorResponseV2(ctx, err, w)
324+
r.errorResponse(ctx, err, w)
325325
}
326326
} else {
327327
if router.GetFallbackHandler() != nil {
@@ -350,15 +350,15 @@ func preprocessRequest(ctx context.Context, quesmaRequest *quesma_api.Request, r
350350
return processedRequest, ctx, nil
351351
}
352352

353-
type elasticResultV2 struct {
353+
type elasticResult struct {
354354
response *http.Response
355355
error error
356356
took time.Duration
357357
}
358358

359-
func (r *RouterV2) sendHttpRequestToElastic(ctx context.Context, req *http.Request,
360-
reqBody []byte, isManagement bool) chan elasticResultV2 {
361-
elkResponseChan := make(chan elasticResultV2)
359+
func (r *Dispatcher) sendHttpRequestToElastic(ctx context.Context, req *http.Request,
360+
reqBody []byte, isManagement bool) chan elasticResult {
361+
elkResponseChan := make(chan elasticResult)
362362

363363
// If Quesma is exposing unauthenticated API but underlying Elasticsearch requires authentication, we should add the
364364
if r.Config.DisableAuth && req.Header.Get("Authorization") == "" && r.Config.Elasticsearch.User != "" {
@@ -377,7 +377,7 @@ func (r *RouterV2) sendHttpRequestToElastic(ctx context.Context, req *http.Reque
377377
}
378378

379379
go func() {
380-
elkResponseChan <- recordRequestToElasticV2(req.URL.Path, r.debugInfoCollector, func() elasticResultV2 {
380+
elkResponseChan <- recordRequestToElastic(req.URL.Path, r.debugInfoCollector, func() elasticResult {
381381

382382
isWrite := elasticsearch.IsWriteRequest(req)
383383

@@ -400,23 +400,23 @@ func (r *RouterV2) sendHttpRequestToElastic(ctx context.Context, req *http.Reque
400400

401401
resp, err := r.sendHttpRequest(ctx, r.Config.Elasticsearch.Url.String(), req, reqBody)
402402
took := span.End(err)
403-
return elasticResultV2{resp, err, took}
403+
return elasticResult{resp, err, took}
404404
})
405405
}()
406406
return elkResponseChan
407407
}
408408

409-
func isResponseOkV2(resp *http.Response) bool {
409+
func isResponseOk(resp *http.Response) bool {
410410
return resp != nil && resp.StatusCode >= 200 && resp.StatusCode < 500
411411
}
412412

413-
func isIngestV2(path string) bool {
413+
func isIngest(path string) bool {
414414
return strings.HasSuffix(path, routes.BulkPath) // We may add more methods in future such as `_put` or `_create`
415415
}
416416

417-
func recordRequestToClickhouseV2(path string, qmc diag.DebugInfoCollector, requestFunc func() (*quesma_api.Result, error)) (*quesma_api.Result, error) {
417+
func recordRequestToClickhouse(path string, qmc diag.DebugInfoCollector, requestFunc func() (*quesma_api.Result, error)) (*quesma_api.Result, error) {
418418
statName := ui.RequestStatisticKibana2Clickhouse
419-
if isIngestV2(path) {
419+
if isIngest(path) {
420420
statName = ui.RequestStatisticIngest2Clickhouse
421421
}
422422
now := time.Now()
@@ -427,15 +427,15 @@ func recordRequestToClickhouseV2(path string, qmc diag.DebugInfoCollector, reque
427427
return response, err
428428
}
429429

430-
func recordRequestToElasticV2(path string, qmc diag.DebugInfoCollector, requestFunc func() elasticResultV2) elasticResultV2 {
430+
func recordRequestToElastic(path string, qmc diag.DebugInfoCollector, requestFunc func() elasticResult) elasticResult {
431431
statName := ui.RequestStatisticKibana2Elasticsearch
432-
if isIngestV2(path) {
432+
if isIngest(path) {
433433
statName = ui.RequestStatisticIngest2Elasticsearch
434434
}
435435
now := time.Now()
436436
response := requestFunc()
437437
if qmc != nil {
438-
qmc.RecordRequest(statName, time.Since(now), !isResponseOkV2(response.response))
438+
qmc.RecordRequest(statName, time.Since(now), !isResponseOk(response.response))
439439
}
440440
return response
441441
}
@@ -470,7 +470,7 @@ func PeekBodyV2(r *http.Request) ([]byte, error) {
470470
return reqBody, nil
471471
}
472472

473-
func copyHeadersV2(w http.ResponseWriter, elkResponse *http.Response) {
473+
func copyHeaders(w http.ResponseWriter, elkResponse *http.Response) {
474474
for key, values := range elkResponse.Header {
475475
for _, value := range values {
476476
if key != HttpHeaderContentLength {
@@ -482,7 +482,7 @@ func copyHeadersV2(w http.ResponseWriter, elkResponse *http.Response) {
482482
}
483483
}
484484

485-
func (r *RouterV2) sendHttpRequest(ctx context.Context, address string, originalReq *http.Request, originalReqBody []byte) (*http.Response, error) {
485+
func (r *Dispatcher) sendHttpRequest(ctx context.Context, address string, originalReq *http.Request, originalReqBody []byte) (*http.Response, error) {
486486
req, err := http.NewRequestWithContext(ctx, originalReq.Method, address+originalReq.URL.String(), bytes.NewBuffer(originalReqBody))
487487

488488
if err != nil {

quesma/frontend_connectors/elastic_http_frontend_connector.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func NewElasticHttpIngestFrontendConnector(endpoint string,
2525
BasicHTTPFrontendConnector: NewBasicHTTPFrontendConnector(endpoint, config),
2626
}
2727
fallback := func(ctx context.Context, req *quesma_api.Request, writer http.ResponseWriter) (*quesma_api.Result, error) {
28-
fc.BasicHTTPFrontendConnector.GetRouterInstance().ElasticFallback(req.Decision, ctx, writer, req.OriginalRequest, []byte(req.Body), logManager, registry)
28+
fc.BasicHTTPFrontendConnector.GetDispatcherInstance().ElasticFallback(req.Decision, ctx, writer, req.OriginalRequest, []byte(req.Body), logManager, registry)
2929
return nil, nil
3030
}
3131

@@ -48,7 +48,7 @@ func NewElasticHttpQueryFrontendConnector(endpoint string,
4848
BasicHTTPFrontendConnector: NewBasicHTTPFrontendConnector(endpoint, config),
4949
}
5050
fallback := func(ctx context.Context, req *quesma_api.Request, writer http.ResponseWriter) (*quesma_api.Result, error) {
51-
fc.BasicHTTPFrontendConnector.GetRouterInstance().ElasticFallback(req.Decision, ctx, writer, req.OriginalRequest, []byte(req.Body), logManager, registry)
51+
fc.BasicHTTPFrontendConnector.GetDispatcherInstance().ElasticFallback(req.Decision, ctx, writer, req.OriginalRequest, []byte(req.Body), logManager, registry)
5252
return nil, nil
5353
}
5454
router.AddFallbackHandler(fallback)

0 commit comments

Comments
 (0)