1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
11 // RequestCounter is an http.Handler that tracks the number of
12 // requests in progress.
13 type RequestCounter interface {
16 // Current() returns the number of requests in progress.
19 // Max() returns the maximum number of concurrent requests
20 // that will be accepted.
24 type limiterHandler struct {
25 requests chan struct{}
29 // NewRequestLimiter returns a RequestCounter that delegates up to
30 // maxRequests at a time to the given handler, and responds 503 to all
31 // incoming requests beyond that limit.
32 func NewRequestLimiter(maxRequests int, handler http.Handler) RequestCounter {
33 return &limiterHandler{
34 requests: make(chan struct{}, maxRequests),
39 func (h *limiterHandler) Current() int {
40 return len(h.requests)
43 func (h *limiterHandler) Max() int {
44 return cap(h.requests)
47 func (h *limiterHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
49 case h.requests <- struct{}{}:
51 // reached max requests
52 resp.WriteHeader(http.StatusServiceUnavailable)
55 h.handler.ServeHTTP(resp, req)