/**
 * Redis-Backed Distributed Rate Limiter
 *
 * Provides distributed rate limiting using Redis for multi-instance deployments.
 * Implements sliding window rate limiting with atomic Lua scripts for accuracy.
 *
 * Features:
 * - Sliding window algorithm for accurate rate limiting
 * - Multiple windows (per-minute, per-hour, burst)
 * - Atomic operations using Redis Lua scripts
 * - Per-user, per-IP, per-endpoint, and tenant-level limits
 * - Graceful fallback to in-memory when Redis is unavailable
 * - Rate limit headers in response
 * - OpenTelemetry tracing integration
 *
 * @packageDocumentation
 */
import type { FastifyRequest, FastifyReply, FastifyPluginAsync } from 'fastify';
/**
 * Rate limit window configuration
 */
export interface RateLimitWindow {
    /** Maximum requests allowed in this window */
    limit: number;
    /** Window duration in seconds */
    windowSeconds: number;
}
/**
 * Multi-window rate limit configuration
 */
export interface MultiWindowRateLimitConfig {
    /** Per-minute rate limit */
    perMinute?: RateLimitWindow;
    /** Per-hour rate limit */
    perHour?: RateLimitWindow;
    /** Burst limit (per-second) */
    burst?: RateLimitWindow;
}
/**
 * Rate limiter configuration
 */
export interface RedisRateLimiterConfig {
    /** Redis key prefix for rate limit data */
    keyPrefix: string;
    /** Default rate limits for all requests */
    defaultLimits: MultiWindowRateLimitConfig;
    /** Per-endpoint overrides (URL pattern -> limits) */
    endpointOverrides?: Record<string, Partial<MultiWindowRateLimitConfig>>;
    /** Per-tenant limit multipliers (tenantId -> multiplier) */
    tenantMultipliers?: Record<string, number>;
    /** Global tenant limits (separate from per-endpoint) */
    tenantGlobalLimits?: MultiWindowRateLimitConfig;
    /** Skip rate limiting for certain requests */
    skip?: (request: FastifyRequest) => boolean;
    /** Custom error message */
    errorMessage?: string;
    /** Enable graceful degradation (allow requests when Redis fails) */
    gracefulDegradation?: boolean;
    /** Log warnings when falling back to in-memory */
    logFallbackWarnings?: boolean;
}
/**
 * Rate limit check result
 */
export interface RateLimitCheckResult {
    /** Whether the request is allowed */
    allowed: boolean;
    /** Results per window */
    windows: {
        minute?: WindowResult;
        hour?: WindowResult;
        burst?: WindowResult;
    };
    /** Which window caused the rejection (if any) */
    limitedBy?: 'minute' | 'hour' | 'burst';
    /** Retry-after value in seconds */
    retryAfter?: number;
    /** Whether result came from fallback (in-memory) */
    fromFallback: boolean;
}
/**
 * Result for a single rate limit window
 */
export interface WindowResult {
    /** Current request count in window */
    current: number;
    /** Maximum allowed requests */
    limit: number;
    /** Remaining requests in window */
    remaining: number;
    /** Unix timestamp when window resets */
    resetAt: number;
}
/**
 * Redis-backed distributed rate limiter
 */
export declare class RedisRateLimiter {
    private config;
    private redis;
    private fallbackStore;
    private scriptSha;
    private multiWindowScriptSha;
    private redisAvailable;
    private lastHealthCheck;
    private healthCheckIntervalMs;
    private readonly instanceId;
    constructor(config?: Partial<RedisRateLimiterConfig>);
    /**
     * Initialize Redis connection and load Lua scripts
     */
    initialize(): Promise<void>;
    /**
     * Check rate limit and periodic Redis health
     */
    private checkRedisAvailability;
    /**
     * Generate rate limit key
     */
    private generateKey;
    /**
     * Check rate limit for a request using multiple windows
     */
    checkMultiWindow(identifier: string, type: 'user' | 'ip' | 'endpoint' | 'tenant', limits: MultiWindowRateLimitConfig): Promise<RateLimitCheckResult>;
    /**
     * Check multi-window rate limit using Redis
     */
    private checkMultiWindowRedis;
    /**
     * Check multi-window rate limit using in-memory fallback
     */
    private checkMultiWindowInMemory;
    /**
     * Get effective limits for a request
     */
    getEffectiveLimits(endpoint: string, tenantId?: string): MultiWindowRateLimitConfig;
    /**
     * Match endpoint against pattern (supports wildcards)
     */
    private matchEndpoint;
    /**
     * Merge limit configurations
     */
    private mergeLimits;
    /**
     * Apply multiplier to limits
     */
    private applyMultiplier;
    /**
     * Get statistics
     */
    getStats(): {
        redisAvailable: boolean;
        fallbackActiveKeys: number;
        instanceId: string;
    };
    /**
     * Stop the rate limiter
     */
    stop(): void;
}
/** Type for preHandler hook function */
type PreHandlerFn = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
/**
 * Get or create the global Redis rate limiter
 */
export declare function getRedisRateLimiter(config?: Partial<RedisRateLimiterConfig>): Promise<RedisRateLimiter>;
/**
 * Reset the global rate limiter (for testing)
 */
export declare function resetRedisRateLimiter(): void;
/**
 * Create Redis-backed rate limiting middleware for per-user limits
 *
 * @param config - Rate limiter configuration
 * @returns Fastify preHandler hook
 *
 * @example
 * ```typescript
 * server.post('/api/data', {
 *   preHandler: await redisRateLimitPerUser({
 *     defaultLimits: {
 *       perMinute: { limit: 100, windowSeconds: 60 },
 *       perHour: { limit: 1000, windowSeconds: 3600 },
 *       burst: { limit: 10, windowSeconds: 1 },
 *     },
 *   }),
 * }, handler);
 * ```
 */
export declare function redisRateLimitPerUser(config?: Partial<RedisRateLimiterConfig>): Promise<PreHandlerFn>;
/**
 * Create Redis-backed rate limiting middleware for per-IP limits
 * (for unauthenticated endpoints)
 */
export declare function redisRateLimitPerIp(config?: Partial<RedisRateLimiterConfig>): Promise<PreHandlerFn>;
/**
 * Create Redis-backed rate limiting middleware for tenant-level global limits
 */
export declare function redisRateLimitPerTenant(config?: Partial<RedisRateLimiterConfig>): Promise<PreHandlerFn>;
/**
 * Rate limiter factory options
 */
export interface RateLimiterFactoryOptions extends Partial<RedisRateLimiterConfig> {
    /** Force in-memory mode (for testing) */
    forceInMemory?: boolean;
}
/**
 * Create rate limiter middleware based on environment.
 *
 * Returns Redis-backed limiter in production and in-memory in development.
 *
 * @param options - Rate limiter options
 * @returns Object with middleware functions for different rate limiting strategies
 *
 * @example
 * ```typescript
 * const rateLimiter = await createRateLimiter({
 *   defaultLimits: {
 *     perMinute: { limit: 100, windowSeconds: 60 },
 *   },
 * });
 *
 * server.post('/api/data', {
 *   preHandler: rateLimiter.perUser,
 * }, handler);
 * ```
 */
export declare function createRateLimiter(options?: RateLimiterFactoryOptions): Promise<{
    /** Per-user rate limiting (falls back to per-IP for unauthenticated) */
    perUser: PreHandlerFn;
    /** Per-IP rate limiting */
    perIp: PreHandlerFn;
    /** Per-tenant global rate limiting */
    perTenant: PreHandlerFn;
    /** Get rate limiter statistics */
    getStats: () => {
        redisAvailable: boolean;
        fallbackActiveKeys: number;
        instanceId: string;
    };
    /** Stop the rate limiter */
    stop: () => void;
}>;
/**
 * Plugin options for registering Redis rate limiting
 */
export interface RedisRateLimitPluginOptions extends RateLimiterFactoryOptions {
    /** Enable global tenant rate limiting */
    enableGlobalTenantLimit?: boolean;
    /** Paths to skip rate limiting */
    skipPaths?: string[];
}
/**
 * Register Redis rate limiting plugin for Fastify
 *
 * @example
 * ```typescript
 * await server.register(redisRateLimitPlugin, {
 *   defaultLimits: {
 *     perMinute: { limit: 100, windowSeconds: 60 },
 *     perHour: { limit: 1000, windowSeconds: 3600 },
 *     burst: { limit: 10, windowSeconds: 1 },
 *   },
 *   enableGlobalTenantLimit: true,
 *   skipPaths: ['/health', '/ready', '/metrics'],
 * });
 * ```
 */
export declare const redisRateLimitPlugin: FastifyPluginAsync<RedisRateLimitPluginOptions>;
declare module 'fastify' {
    interface FastifyInstance {
        vorionRedisRateLimiter: Awaited<ReturnType<typeof createRateLimiter>>;
        vorionRedisRateLimitPerUser: PreHandlerFn;
        vorionRedisRateLimitPerIp: PreHandlerFn;
        vorionRedisRateLimitPerTenant: PreHandlerFn;
    }
}
export {};
//# sourceMappingURL=redis-rate-limiter.d.ts.map