From 5c5a1ab496ea07c38a885b260dea14aa952f08b9 Mon Sep 17 00:00:00 2001 From: crozzy Date: Thu, 30 Jun 2022 15:41:35 -0700 Subject: [PATCH] logging: log when request is rate-limited Currently there is no indication in the logs that a request has been rate-limited. Signed-off-by: crozzy --- httptransport/concurrentlimit.go | 8 ++++++++ httptransport/concurrentlimit_test.go | 6 +++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/httptransport/concurrentlimit.go b/httptransport/concurrentlimit.go index 8af8322e53..025985b40f 100644 --- a/httptransport/concurrentlimit.go +++ b/httptransport/concurrentlimit.go @@ -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" ) @@ -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 } diff --git a/httptransport/concurrentlimit_test.go b/httptransport/concurrentlimit_test.go index 8afec6b58f..126292ec2f 100644 --- a/httptransport/concurrentlimit_test.go +++ b/httptransport/concurrentlimit_test.go @@ -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. @@ -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 {