Skip to content

Commit

Permalink
Fix: timeout middleware (#234)
Browse files Browse the repository at this point in the history
  • Loading branch information
aopoltorzhicky committed Jul 3, 2024
1 parent f0afa8d commit d3dc094
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
7 changes: 6 additions & 1 deletion cmd/api/handler/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ func handleError(c echo.Context, err error, noRows NoRows) error {
if err.Error() == errCancelRequest {
return nil
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
if errors.Is(err, context.DeadlineExceeded) {
return c.JSON(http.StatusRequestTimeout, Error{
Message: "timeout",
})
}
if errors.Is(err, context.Canceled) {
return c.JSON(http.StatusBadGateway, Error{
Message: err.Error(),
})
Expand Down
8 changes: 2 additions & 6 deletions cmd/api/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,7 @@ func initEcho(cfg ApiConfig, db postgres.Storage, env string) *echo.Echo {
if cfg.RequestTimeout > 0 {
timeout = time.Duration(cfg.RequestTimeout) * time.Second
}
e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{
Skipper: websocketSkipper,
Timeout: timeout,
ErrorMessage: `{"message":"timeout"}`,
}))
e.Use(RequestTimeout(timeout))

e.Use(middleware.GzipWithConfig(middleware.GzipConfig{
Skipper: gzipSkipper,
Expand Down Expand Up @@ -281,7 +277,7 @@ func initHandlers(ctx context.Context, e *echo.Echo, cfg Config, db postgres.Sto
searchHandler := handler.NewSearchHandler(db.Search, db.Address, db.Blocks, db.Tx, db.Namespace, db.Validator, db.Rollup)
v1.GET("/search", searchHandler.Search)

ttlCache := cache.NewTTLCache(cache.Config{MaxEntitiesCount: 1000}, time.Minute*15)
ttlCache := cache.NewTTLCache(cache.Config{MaxEntitiesCount: 1000}, time.Minute*30)
ttlCacheMiddleware := cache.Middleware(ttlCache, nil)

addressHandlers := handler.NewAddressHandler(db.Address, db.Tx, db.BlobLogs, db.Message, db.Delegation, db.Undelegation, db.Redelegation, db.VestingAccounts, db.Grants, db.State, cfg.Indexer.Name)
Expand Down
19 changes: 19 additions & 0 deletions cmd/api/timeout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

import (
"context"
"time"

"github.com/labstack/echo/v4"
)

func RequestTimeout(timeout time.Duration) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
timeoutCtx, cancel := context.WithTimeout(c.Request().Context(), timeout)
c.SetRequest(c.Request().WithContext(timeoutCtx))
defer cancel()
return next(c)
}
}
}

0 comments on commit d3dc094

Please sign in to comment.