Skip to content

Commit

Permalink
logging: log when request is rate-limited
Browse files Browse the repository at this point in the history
Currently there is no indication in the logs that
a request has been rate-limited.

Signed-off-by: crozzy <joseph.crosland@gmail.com>
  • Loading branch information
crozzy committed Jul 1, 2022
1 parent 4e44f7e commit 5c5a1ab
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 8 additions & 0 deletions httptransport/concurrentlimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/quay/zlog"
"golang.org/x/sync/semaphore"
)

Expand Down Expand Up @@ -37,6 +38,13 @@ func (l *limitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if sem != nil {
if !sem.TryAcquire(1) {
concurrentLimitedCounter.WithLabelValues(endpt, r.Method).Add(1)
zlog.Info(r.Context()).
Str("remote_addr", r.RemoteAddr).
Str("method", r.Method).
Str("request_uri", r.RequestURI).
Int("status", http.StatusTooManyRequests).
Msg("rate limited HTTP request")

apiError(w, http.StatusTooManyRequests, "server handling too many requests")
return
}
Expand Down
6 changes: 5 additions & 1 deletion httptransport/concurrentlimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@ package httptransport

import (
"context"
"net"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"

"github.com/quay/zlog"
"golang.org/x/sync/semaphore"
)

func TestConcurrentRequests(t *testing.T) {
ctx := context.Background()
ctx = zlog.Test(ctx, t)
sem := semaphore.NewWeighted(1)
// Ret controls when the http server returns.
// Ready is strobed once the first request is seen.
Expand All @@ -29,10 +33,10 @@ func TestConcurrentRequests(t *testing.T) {
w.WriteHeader(http.StatusNoContent)
}),
})
srv.Config.BaseContext = func(_ net.Listener) context.Context { return ctx }
defer srv.Close()
c := srv.Client()

ctx := context.Background()
done := make(chan struct{})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
Expand Down

0 comments on commit 5c5a1ab

Please sign in to comment.