Skip to content

Commit

Permalink
Merge pull request #80 from mysteriumnetwork/limit-max-requests
Browse files Browse the repository at this point in the history
Limit number of allowed parallel requests
  • Loading branch information
soffokl authored Feb 1, 2023
2 parents 189e88c + 411cc4b commit b3970eb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ func main() {
r.Use(mlog.GinLogFunc())
r.Use(apierror.ErrorHandler)

r.Use(LimitMiddleware(cfg.MaxRequestsLimit))

r.GET("/", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/swagger/index.html")
})
Expand Down Expand Up @@ -100,3 +102,16 @@ func printBanner() {
log.Info().Msg(" and it will be our privilege to make that future bright.")
log.Info().Msg(strings.Repeat("▱", 60))
}

func LimitMiddleware(size int) gin.HandlerFunc {
limit := make(chan struct{}, size)
return func(c *gin.Context) {
select {
case limit <- struct{}{}:
c.Next()
<-limit
default:
c.AbortWithStatus(http.StatusTooManyRequests)
}
}
}
9 changes: 9 additions & 0 deletions config/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ type Options struct {

UniverseJWTSecret string
SentinelURL string

MaxRequestsLimit int
}

func ReadDiscovery() (*Options, error) {
Expand Down Expand Up @@ -58,6 +60,12 @@ func ReadDiscovery() (*Options, error) {
return nil, err
}

maxRequestsLimit := OptionalEnv("MAX_REQUESTS_LIMIT", "1000")
limit, err := strconv.Atoi(maxRequestsLimit)
if err != nil {
return nil, fmt.Errorf("failed to parse max requests limit: %w", err)
}

return &Options{
QualityOracleURL: *qualityOracleURL,
QualityCacheTTL: *qualityCacheTTL,
Expand All @@ -66,6 +74,7 @@ func ReadDiscovery() (*Options, error) {
LocationAddress: *locationAddress,
LocationUser: locationUser,
LocationPass: locationPass,
MaxRequestsLimit: limit,
}, nil
}

Expand Down

0 comments on commit b3970eb

Please sign in to comment.