Skip to content

Commit

Permalink
Moves throttiling logic from backend to middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Apr 7, 2024
1 parent 12444e6 commit f90ef88
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 16 deletions.
16 changes: 0 additions & 16 deletions backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,12 @@ type RequestFactory func(req Request) (*http.Request, error)
type HTTPBackend struct {
factory RequestFactory
client *http.Client
sem chan struct{}
}

const (
MaxConcurrentRequests = 50
)

func NewBackend(factory RequestFactory) *HTTPBackend {
return &HTTPBackend{
factory: factory,
client: &http.Client{},
sem: make(chan struct{}, MaxConcurrentRequests),
}
}

Expand All @@ -31,17 +25,7 @@ func (b *HTTPBackend) Handle(conn Connection, r Request) error {
return err
}

ctx := r.Context()

select {
case <-ctx.Done():
return ctx.Err()
case b.sem <- struct{}{}:
}

resp, err := b.client.Do(httpReq)
<-b.sem

if err != nil {
return err
}
Expand Down
1 change: 1 addition & 0 deletions examples/http_backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func main() {
connRegistry := wasabi.NewDefaultConnectionRegistry()
dispatcher := wasabi.NewPipeDispatcher(backend)
dispatcher.Use(ErrHandler)
dispatcher.Use(request.NewTrottlerMiddleware(10))

server := wasabi.NewServer(Port)
channel := wasabi.NewDefaultChannel("/", dispatcher, connRegistry)
Expand Down
22 changes: 22 additions & 0 deletions middleware/request/throttler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package request

import "github.com/ksysoev/wasabi"

type token struct{}

func NewTrottlerMiddleware(limit uint) func(next wasabi.RequestHandler) wasabi.RequestHandler {
sem := make(chan token, limit)

return func(next wasabi.RequestHandler) wasabi.RequestHandler {
return wasabi.RequestHandlerFunc(func(conn wasabi.Connection, req wasabi.Request) error {

Check failure on line 11 in middleware/request/throttler.go

View workflow job for this annotation

GitHub Actions / tests

unnecessary leading newline (whitespace)

select {
case sem <- token{}:
defer func() { <-sem }()
return next.Handle(conn, req)
case <-conn.Context().Done():
return conn.Context().Err()
}
})
}
}

0 comments on commit f90ef88

Please sign in to comment.