middleware

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware including response caching, rate limiting, and compression for the gateway.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheStats

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

CacheStats tracks cache hit/miss metrics.

func (*CacheStats) Hits

func (cs *CacheStats) Hits() int64

Hits returns the total cache hits.

func (*CacheStats) Misses

func (cs *CacheStats) Misses() int64

Misses returns the total cache misses.

type CacheStore

type CacheStore interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
}

CacheStore is the interface for a cache backend. This decouples from the concrete cache extension, allowing the gateway to use any backend that implements this interface.

type CachedResponse

type CachedResponse struct {
	StatusCode int               `json:"statusCode"`
	Headers    map[string]string `json:"headers"`
	Body       []byte            `json:"body"`
	CachedAt   time.Time         `json:"cachedAt"`
	TTL        time.Duration     `json:"ttl"`
}

CachedResponse represents a cached HTTP response.

type CachingConfig

type CachingConfig struct {
	Enabled    bool          `json:"enabled" yaml:"enabled"`
	DefaultTTL time.Duration `json:"defaultTtl" yaml:"default_ttl"`
	MaxSize    int           `json:"maxSize" yaml:"max_size"`
	Methods    []string      `json:"methods,omitempty" yaml:"methods"`
	VaryBy     []string      `json:"varyBy,omitempty" yaml:"vary_by"`
}

CachingConfig holds response caching settings.

type CompressionConfig

type CompressionConfig struct {
	// Enabled enables response compression.
	Enabled bool `json:"enabled" yaml:"enabled"`

	// MinSize is the minimum response body size (bytes) to trigger compression.
	MinSize int `json:"minSize" yaml:"min_size"`

	// Level is the gzip compression level (1-9, or -1 for default).
	Level int `json:"level" yaml:"level"`

	// ContentTypes lists MIME types eligible for compression.
	// Empty means all compressible types.
	ContentTypes []string `json:"contentTypes,omitempty" yaml:"content_types"`
}

CompressionConfig configures response compression.

type CompressionMiddleware

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

CompressionMiddleware wraps an http.Handler with gzip compression.

func NewCompressionMiddleware

func NewCompressionMiddleware(config CompressionConfig) *CompressionMiddleware

NewCompressionMiddleware creates a new compression middleware.

func (*CompressionMiddleware) Wrap

Wrap returns a handler that compresses responses.

type DistributedRateLimiter

type DistributedRateLimiter struct {
	*RateLimiter
	// contains filtered or unexported fields
}

DistributedRateLimiter extends the basic RateLimiter with an external store for multi-instance rate limiting.

func NewDistributedRateLimiter

func NewDistributedRateLimiter(config RateLimitConfig, store RateLimitStore) *DistributedRateLimiter

NewDistributedRateLimiter creates a rate limiter backed by an external store. Falls back to local token bucket if the store is unavailable.

func (*DistributedRateLimiter) AllowDistributed

func (drl *DistributedRateLimiter) AllowDistributed(ctx context.Context, key string) bool

AllowDistributed checks the rate limit using the distributed store. Falls back to local limiter on store error.

type InMemoryCacheStore

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

InMemoryCacheStore provides a simple in-memory LRU cache for the gateway. It is used as the default cache backend when no external store is configured.

func NewInMemoryCacheStore

func NewInMemoryCacheStore(maxSize int) *InMemoryCacheStore

NewInMemoryCacheStore creates a new in-memory cache store.

func (*InMemoryCacheStore) CleanExpired

func (s *InMemoryCacheStore) CleanExpired()

CleanExpired removes all expired entries.

func (*InMemoryCacheStore) Delete

func (s *InMemoryCacheStore) Delete(_ context.Context, key string) error

func (*InMemoryCacheStore) Get

func (s *InMemoryCacheStore) Get(_ context.Context, key string) ([]byte, error)

func (*InMemoryCacheStore) Set

func (s *InMemoryCacheStore) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

type InMemoryRateLimitStore

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

InMemoryRateLimitStore is a local implementation of RateLimitStore using sliding window counters. Useful for testing or single-instance deployments.

func NewInMemoryRateLimitStore

func NewInMemoryRateLimitStore() *InMemoryRateLimitStore

NewInMemoryRateLimitStore creates a new in-memory rate limit store.

func (*InMemoryRateLimitStore) Allow

func (s *InMemoryRateLimitStore) Allow(_ context.Context, key string, limit float64, burst int, _ time.Duration) (bool, error)

Allow implements RateLimitStore using local token buckets.

type Logger

type Logger interface {
	Debug(msg string, fields ...log.Field)
}

Logger is a minimal logging interface used by middleware. It mirrors the subset of forge.Logger that caching needs, avoiding a direct import of the root bastion package.

type RateLimitConfig

type RateLimitConfig struct {
	Enabled        bool    `json:"enabled" yaml:"enabled"`
	RequestsPerSec float64 `json:"requestsPerSec" yaml:"requests_per_sec"`
	Burst          int     `json:"burst" yaml:"burst"`
	PerClient      bool    `json:"perClient" yaml:"per_client"`
	KeyHeader      string  `json:"keyHeader,omitempty" yaml:"key_header"`
}

RateLimitConfig holds rate limiting settings.

type RateLimitStore

type RateLimitStore interface {
	// Allow checks if a request identified by key is allowed under the given
	// rate limit. Returns true if allowed, false if rate-limited.
	// The implementation should atomically increment the counter.
	Allow(ctx context.Context, key string, limit float64, burst int, window time.Duration) (bool, error)
}

RateLimitStore is the interface for distributed rate limiting backends. Implementations must be safe for concurrent use.

type RateLimiter

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

RateLimiter implements token-bucket rate limiting.

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(r *http.Request) bool

Allow checks if a request is allowed.

func (*RateLimiter) AllowForKey

func (rl *RateLimiter) AllowForKey(key string) bool

AllowForKey checks rate limit for the given key.

func (*RateLimiter) AllowWithConfig

func (rl *RateLimiter) AllowWithConfig(r *http.Request, config *RateLimitConfig) bool

AllowWithConfig checks rate limit with a per-route override.

func (*RateLimiter) BucketCount

func (rl *RateLimiter) BucketCount() int

BucketCount returns the number of active per-client buckets. This is primarily useful for testing cleanup behavior.

func (*RateLimiter) Cleanup

func (rl *RateLimiter) Cleanup(maxAge time.Duration)

Cleanup removes stale buckets older than the given duration.

func (*RateLimiter) Config

func (rl *RateLimiter) Config() RateLimitConfig

Config returns the rate limiter's configuration.

type ResponseCache

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

ResponseCache provides HTTP response caching for the gateway. It supports:

  • Configurable cache backends (in-memory, external via CacheStore interface)
  • Per-route cache policies with TTL, vary-by headers, and method filtering
  • Cache-Control header respect (no-cache, no-store, max-age)
  • Automatic cache key generation based on method, path, query, and vary-by headers
  • Cache invalidation via admin API
  • Metrics (hits/misses)

func NewResponseCache

func NewResponseCache(config CachingConfig, logger Logger, store CacheStore) *ResponseCache

NewResponseCache creates a new response cache.

func (*ResponseCache) Get

func (rc *ResponseCache) Get(r *http.Request, route *Route) *CachedResponse

Get attempts to retrieve a cached response for the given request. Returns nil if not cached, cache is disabled, or the request is not cacheable.

func (*ResponseCache) Invalidate

func (rc *ResponseCache) Invalidate(ctx context.Context, method, path string) error

Invalidate removes a cached entry for the given request.

func (*ResponseCache) Set

func (rc *ResponseCache) Set(r *http.Request, route *Route, statusCode int, headers http.Header, body []byte)

Set stores a response in the cache.

func (*ResponseCache) Stats

func (rc *ResponseCache) Stats() *CacheStats

Stats returns the cache statistics.

func (*ResponseCache) WriteCachedResponse

func (rc *ResponseCache) WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)

WriteCachedResponse writes a cached response to the client.

type Route

type Route struct {
	Path    string
	Cache   *RouteCacheConfig
	Methods []string
}

Route is the minimal route representation needed by the cache middleware. The full Route type lives in the root bastion package.

type RouteCacheConfig

type RouteCacheConfig struct {
	Enabled bool          `json:"enabled"`
	TTL     time.Duration `json:"ttl,omitempty"`
	Methods []string      `json:"methods,omitempty"`
	VaryBy  []string      `json:"varyBy,omitempty"`
}

RouteCacheConfig defines per-route caching policy.

Jump to

Keyboard shortcuts

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