ratelimit

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2024 License: MIT Imports: 6 Imported by: 1

Documentation

Overview

Package ratelimit implements rate limiting with groupcache.

Index

Constants

View Source
const DefaultGroupcacheSizeBytes = 10_000_000

DefaultGroupcacheSizeBytes is default for unspecified Options GroupcacheSizeBytes.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter struct {
	// contains filtered or unexported fields
}

Limiter implements rate limiting.

func New

func New(options Options) *Limiter

New creates a rate limiter.

func (*Limiter) Consume

func (l *Limiter) Consume(ctx context.Context, key string) (bool, error)

Consume attempts to consume the rate limiter. It returns true if the rate limiter allows access, or false if the rate limiter denies access. If a non-nil error is returned, the bool value is undefined, don't rely on it.

func (*Limiter) MetricsExporter

func (l *Limiter) MetricsExporter() *modernprogram.Group

MetricsExporter creates a metrics exporter for Prometheus.

Usage example

exporter := limiter.MetricsExporter()
labels := map[string]string{
	"app": "app1",
}
namespace := ""
collector := groupcache_exporter.NewExporter(namespace, labels, exporter)
prometheus.MustRegister(collector)
go func() {
	http.Handle(metricsRoute, promhttp.Handler())
	log.Fatal(http.ListenAndServe(metricsPort, nil))
}()

type Options

type Options struct {
	// Interval is the measurement interval.
	// For example, if Interval is 10s, and Slots is 20,
	// the rate limiter will accept 20 requests at every
	// 10 seconds.
	Interval time.Duration

	// Slots is the amount of requests the rate limiter
	// accepts per Interval.
	// For example, if Interval is 10s, and Slots is 20,
	// the rate limiter will accept 20 requests at every
	// 10 seconds.
	Slots int

	// GroupcacheWorkspace is required groupcache workspace.
	GroupcacheWorkspace *groupcache.Workspace

	// GroupcacheName gives a unique cache name. If unspecified, defaults to rate-limit.
	GroupcacheName string

	// GroupcacheSizeBytes limits the cache size. If unspecified, defaults to 10MB.
	GroupcacheSizeBytes int64

	// Logf provides logging function, if undefined defaults to log.Printf
	Logf func(format string, v ...any)

	// Debug enables debug logging.
	Debug bool
}

Options define parameters for rate limiting.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL