|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "log/slog" |
| 6 | + "net/http" |
| 7 | + "sync/atomic" |
| 8 | + |
| 9 | + "github.com/grafana/grafana-image-renderer/pkg/config" |
| 10 | + "github.com/grafana/grafana-image-renderer/pkg/service" |
| 11 | + "github.com/pbnjay/memory" |
| 12 | + "github.com/prometheus/client_golang/prometheus" |
| 13 | + "go.opentelemetry.io/otel/attribute" |
| 14 | + "go.opentelemetry.io/otel/codes" |
| 15 | + "go.opentelemetry.io/otel/trace" |
| 16 | +) |
| 17 | + |
| 18 | +var ( |
| 19 | + MetricRateLimiterRequests = prometheus.NewCounterVec(prometheus.CounterOpts{ |
| 20 | + Name: "http_rate_limiter_requests_total", |
| 21 | + Help: "Number of HTTP requests that pass through the rate-limiter, and their outcomes.", |
| 22 | + }, []string{"result", "why"}) |
| 23 | + MetricRateLimiterSlots = prometheus.NewGaugeVec(prometheus.GaugeOpts{ |
| 24 | + Name: "http_rate_limiter_slots", |
| 25 | + Help: "The number of total available slots for handling requests, based on memory.", |
| 26 | + }, []string{"type"}) |
| 27 | +) |
| 28 | + |
| 29 | +// Limiter unifies the limiter types. |
| 30 | +type Limiter interface { |
| 31 | + Limit(http.Handler) http.Handler |
| 32 | +} |
| 33 | + |
| 34 | +type noOpLimiter struct{} |
| 35 | + |
| 36 | +func (noOpLimiter) Limit(next http.Handler) http.Handler { |
| 37 | + return next |
| 38 | +} |
| 39 | + |
| 40 | +type processBasedLimiter struct { |
| 41 | + svc *service.ProcessStatService |
| 42 | + cfg config.RateLimitConfig |
| 43 | + running *atomic.Uint32 |
| 44 | + logger *slog.Logger |
| 45 | +} |
| 46 | + |
| 47 | +func (p processBasedLimiter) Limit(next http.Handler) http.Handler { |
| 48 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 49 | + tracer := tracer(r.Context()) |
| 50 | + ctx, span := tracer.Start(r.Context(), "processBasedLimiter.Limit") |
| 51 | + defer span.End() |
| 52 | + |
| 53 | + fits, why := p.canFitRequest(ctx) |
| 54 | + span.SetAttributes(attribute.Bool("accepted", fits), attribute.String("reason", why)) |
| 55 | + |
| 56 | + if !fits { |
| 57 | + span.SetStatus(codes.Error, "rate limit exceeded") |
| 58 | + span.SetAttributes(attribute.Bool("accepted", false), attribute.String("reason", why)) |
| 59 | + MetricRateLimiterRequests.WithLabelValues("rejected", why).Inc() |
| 60 | + |
| 61 | + w.Header().Set("Retry-After", "5") |
| 62 | + w.WriteHeader(http.StatusTooManyRequests) |
| 63 | + _, _ = w.Write([]byte("server is too busy, try again later")) |
| 64 | + return |
| 65 | + } else { |
| 66 | + p.running.Add(1) |
| 67 | + MetricRateLimiterRequests.WithLabelValues("accepted", why).Inc() |
| 68 | + // From sync.AddUint32: |
| 69 | + // > AddUint32 atomically adds delta to *addr and returns the new value. |
| 70 | + // > To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)). |
| 71 | + // > In particular, to decrement x, do AddUint32(&x, ^uint32(0)). |
| 72 | + // > Consider using the more ergonomic and less error-prone [Uint32.Add] instead. |
| 73 | + defer p.running.Add(^uint32(0)) // decrement |
| 74 | + |
| 75 | + next.ServeHTTP(w, r) |
| 76 | + } |
| 77 | + }) |
| 78 | +} |
| 79 | + |
| 80 | +func (p processBasedLimiter) canFitRequest(ctx context.Context) (bool, string) { |
| 81 | + tracer := tracer(ctx) |
| 82 | + _, span := tracer.Start(ctx, "processBasedLimiter.canFitRequest", trace.WithAttributes( |
| 83 | + attribute.Int64("headroom", int64(p.cfg.Headroom)), |
| 84 | + attribute.Int64("min_memory_per_browser", int64(p.cfg.MinMemoryPerBrowser)), |
| 85 | + attribute.Int64("min_limit", int64(p.cfg.MinLimit)), |
| 86 | + attribute.Int64("max_limit", int64(p.cfg.MaxLimit)), |
| 87 | + attribute.Int64("max_available", int64(p.cfg.MaxAvailable)))) |
| 88 | + defer span.End() |
| 89 | + |
| 90 | + currentlyRunning := p.running.Load() |
| 91 | + span.SetAttributes(attribute.Int64("currently_running", int64(currentlyRunning))) |
| 92 | + if currentlyRunning < p.cfg.MinLimit { |
| 93 | + return true, "below minimum limit" |
| 94 | + } else if p.cfg.MaxLimit > 0 && currentlyRunning >= p.cfg.MaxLimit { |
| 95 | + return false, "hit maximum limit" |
| 96 | + } |
| 97 | + |
| 98 | + totalMemory := memory.TotalMemory() |
| 99 | + if p.cfg.MaxAvailable > 0 && totalMemory > p.cfg.MaxAvailable { |
| 100 | + span.AddEvent("capping total memory to configured maximum") |
| 101 | + totalMemory = p.cfg.MaxAvailable |
| 102 | + } |
| 103 | + freeMemory := memory.FreeMemory() |
| 104 | + span.SetAttributes( |
| 105 | + attribute.Int64("total_memory", int64(totalMemory)), |
| 106 | + attribute.Int64("free_memory", int64(freeMemory))) |
| 107 | + |
| 108 | + if totalMemory != 0 { |
| 109 | + totalSlots := totalMemory / p.cfg.MinMemoryPerBrowser |
| 110 | + MetricRateLimiterSlots.WithLabelValues("total").Set(float64(totalSlots)) |
| 111 | + MetricRateLimiterSlots.WithLabelValues("free").Set(float64(totalSlots - uint64(currentlyRunning))) |
| 112 | + span.SetAttributes(attribute.Int64("total_slots", int64(totalSlots))) |
| 113 | + if currentlyRunning >= uint32(totalSlots) { |
| 114 | + return false, "no memory slots exist based on total memory" |
| 115 | + } |
| 116 | + } else { |
| 117 | + span.AddEvent("unable to determine total memory, skipping total memory slot check") |
| 118 | + } |
| 119 | + |
| 120 | + if freeMemory != 0 { |
| 121 | + // Calculate whether we have enough for another slot. |
| 122 | + minRequired := max(p.cfg.MinMemoryPerBrowser, uint64(p.svc.PeakMemory)) |
| 123 | + span.SetAttributes(attribute.Int64("min_required_per_browser", int64(minRequired))) |
| 124 | + if freeMemory < p.cfg.Headroom { |
| 125 | + return false, "free memory smaller than required headroom" |
| 126 | + } else if freeMemory-p.cfg.Headroom < minRequired { |
| 127 | + return false, "not enough free memory without headroom for another browser" |
| 128 | + } |
| 129 | + // We have enough free memory. |
| 130 | + } else { |
| 131 | + span.AddEvent("unable to determine free memory, skipping free memory check") |
| 132 | + } |
| 133 | + |
| 134 | + return true, "sufficient memory slots exist" |
| 135 | +} |
| 136 | + |
| 137 | +func NewRateLimiter(svc *service.ProcessStatService, cfg config.RateLimitConfig) (Limiter, error) { |
| 138 | + if cfg.Disabled { |
| 139 | + return noOpLimiter{}, nil |
| 140 | + } |
| 141 | + |
| 142 | + return processBasedLimiter{ |
| 143 | + svc: svc, |
| 144 | + cfg: cfg, |
| 145 | + running: &atomic.Uint32{}, |
| 146 | + logger: slog.With("middleware", "rate_limiter"), |
| 147 | + }, nil |
| 148 | +} |
0 commit comments