Skip to content

Commit

Permalink
feat(promhandler): set query timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Nov 3, 2023
1 parent 0057880 commit 81cafe8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/oteldb/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ func (app *App) trySetupProm() error {
s, err := promapi.NewServer(prom,
promapi.WithTracerProvider(app.metrics.TracerProvider()),
promapi.WithMeterProvider(app.metrics.MeterProvider()),
promapi.WithMiddleware(promhandler.TimeoutMiddleware()),
)
if err != nil {
return err
Expand Down
20 changes: 20 additions & 0 deletions internal/promhandler/promhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/go-faster/errors"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/middleware"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/storage"
Expand Down Expand Up @@ -427,3 +428,22 @@ func fail(kind promapi.FailErrorType, err error) *promapi.FailStatusCode {
},
}
}

// TimeoutMiddleware sets request timeout by given parameter, if set.
func TimeoutMiddleware() promapi.Middleware {
return func(req middleware.Request, next middleware.Next) (middleware.Response, error) {
q := req.Raw.URL.Query()
if q.Has("timeout") {
timeout, err := parseDuration(q.Get("timeout"))
if err != nil {
return middleware.Response{}, validationErr("parse timeout", err)
}

var cancel context.CancelFunc
req.Context, cancel = context.WithTimeout(req.Context, timeout)
defer cancel()
}
resp, err := next(req)
return resp, err
}
}

0 comments on commit 81cafe8

Please sign in to comment.