/**
 * Distributed State Provider for Redis-Backed Security Features
 *
 * Provides a unified interface for distributed state management across
 * multi-instance deployments. Features include:
 * - Generic key-value operations with TTL
 * - Atomic increment for rate limiting
 * - Pub/sub for cache invalidation
 * - Connection health checking
 * - Graceful fallback behavior when Redis unavailable
 *
 * @packageDocumentation
 * @module security/distributed-state
 */
import type { Redis } from 'ioredis';
/**
 * Configuration for the Redis state provider
 */
export interface RedisStateConfig {
    /** Redis URL (overrides host/port if provided) */
    url?: string;
    /** Redis host */
    host: string;
    /** Redis port */
    port: number;
    /** Redis password */
    password?: string;
    /** Redis database number */
    db: number;
    /** Key prefix for all operations */
    keyPrefix: string;
    /** Connection pool size (max connections) */
    maxConnections: number;
    /** Connection timeout in ms */
    connectTimeoutMs: number;
    /** Command timeout in ms */
    commandTimeoutMs: number;
    /** Retry strategy - max retries */
    maxRetries: number;
    /** Retry delay base in ms (exponential backoff applied) */
    retryDelayMs: number;
    /** Max retry delay in ms */
    maxRetryDelayMs: number;
    /** Enable keep-alive for connections */
    keepAlive: boolean;
    /** Keep-alive interval in ms */
    keepAliveIntervalMs: number;
    /** Enable lazy connect (don't connect until first command) */
    lazyConnect: boolean;
    /** Enable fallback to in-memory when Redis unavailable */
    enableFallback: boolean;
    /** Fallback cache max size */
    fallbackMaxSize: number;
    /** Health check interval in ms */
    healthCheckIntervalMs: number;
}
/**
 * Default configuration values
 */
export declare const DEFAULT_REDIS_STATE_CONFIG: RedisStateConfig;
/**
 * Health status of the Redis connection
 */
export interface RedisHealthStatus {
    /** Whether Redis is healthy */
    healthy: boolean;
    /** Response latency in ms */
    latencyMs?: number;
    /** Last successful ping timestamp */
    lastPingAt?: Date;
    /** Error message if unhealthy */
    error?: string;
    /** Whether currently using fallback mode */
    usingFallback: boolean;
    /** Number of operations in fallback cache */
    fallbackCacheSize: number;
}
/**
 * Result of an atomic increment operation
 */
export interface IncrementResult {
    /** New value after increment */
    value: number;
    /** TTL remaining in seconds */
    ttlSeconds: number;
    /** Whether this was the first increment (key created) */
    isNew: boolean;
}
/**
 * Cache invalidation event
 */
export interface InvalidationEvent {
    /** Type of invalidation */
    type: 'key' | 'pattern' | 'all';
    /** Key or pattern to invalidate */
    key?: string;
    /** Timestamp of the event */
    timestamp: Date;
    /** Source instance identifier */
    sourceInstance?: string;
}
/**
 * Subscriber callback for invalidation events
 */
export type InvalidationCallback = (event: InvalidationEvent) => void | Promise<void>;
/**
 * Redis-backed distributed state provider for security features
 *
 * @example
 * ```typescript
 * const provider = new RedisStateProvider({
 *   url: process.env.REDIS_URL,
 *   keyPrefix: 'vorion:security:',
 * });
 *
 * // Store a value with TTL
 * await provider.set('session:abc123', JSON.stringify(sessionData), 3600);
 *
 * // Atomic increment for rate limiting
 * const result = await provider.increment('ratelimit:user:123', 60);
 * if (result.value > 100) {
 *   throw new Error('Rate limit exceeded');
 * }
 * ```
 */
export declare class RedisStateProvider {
    private readonly config;
    private client;
    private subscriber;
    private readonly fallbackCache;
    private readonly invalidationCallbacks;
    private isHealthy;
    private lastPingAt;
    private healthCheckInterval;
    private readonly instanceId;
    /**
     * Create a new RedisStateProvider
     *
     * @param config - Configuration options
     */
    constructor(config?: Partial<RedisStateConfig>);
    /**
     * Get or create the Redis client
     */
    private getClient;
    /**
     * Build Redis connection options
     */
    private buildRedisOptions;
    /**
     * Wait for Redis connection to be ready
     */
    private waitForConnection;
    /**
     * Setup event handlers for the Redis client
     */
    private setupEventHandlers;
    /**
     * Start periodic health checks
     */
    private startHealthCheck;
    /**
     * Execute a Redis command with fallback handling
     */
    private executeWithFallback;
    /**
     * Get the full key with prefix
     */
    private prefixKey;
    /**
     * Get a value by key
     *
     * @param key - The key to get
     * @returns The value or null if not found
     */
    get(key: string): Promise<string | null>;
    /**
     * Set a value with optional TTL
     *
     * @param key - The key to set
     * @param value - The value to store
     * @param ttlSeconds - Optional TTL in seconds
     */
    set(key: string, value: string, ttlSeconds?: number): Promise<void>;
    /**
     * Set a value only if it doesn't exist
     *
     * @param key - The key to set
     * @param value - The value to store
     * @param ttlSeconds - Optional TTL in seconds
     * @returns true if the key was set, false if it already existed
     */
    setNX(key: string, value: string, ttlSeconds?: number): Promise<boolean>;
    /**
     * Delete a key
     *
     * @param key - The key to delete
     * @returns true if the key was deleted
     */
    delete(key: string): Promise<boolean>;
    /**
     * Check if a key exists
     *
     * @param key - The key to check
     * @returns true if the key exists
     */
    exists(key: string): Promise<boolean>;
    /**
     * Set the TTL on an existing key
     *
     * @param key - The key to update
     * @param ttlSeconds - TTL in seconds
     * @returns true if the TTL was set
     */
    expire(key: string, ttlSeconds: number): Promise<boolean>;
    /**
     * Get the TTL of a key
     *
     * @param key - The key to check
     * @returns TTL in seconds, -1 if no TTL, -2 if key doesn't exist
     */
    ttl(key: string): Promise<number>;
    /**
     * Atomically increment a counter with optional TTL
     *
     * This is the core operation for rate limiting. Uses MULTI/EXEC for atomicity.
     *
     * @param key - The key to increment
     * @param ttlSeconds - TTL in seconds (applied only on first increment)
     * @returns The new value and TTL info
     *
     * @example
     * ```typescript
     * const result = await provider.increment('ratelimit:api:user123', 60);
     * if (result.value > 100) {
     *   throw new RateLimitError('Too many requests');
     * }
     * ```
     */
    increment(key: string, ttlSeconds?: number): Promise<IncrementResult>;
    /**
     * Atomically increment by a specific amount
     *
     * @param key - The key to increment
     * @param amount - Amount to increment by
     * @param ttlSeconds - TTL in seconds (applied only on first increment)
     * @returns The new value
     */
    incrementBy(key: string, amount: number, ttlSeconds?: number): Promise<number>;
    /**
     * Get multiple counters at once
     *
     * @param keys - Keys to get
     * @returns Map of key to value (0 if not exists)
     */
    getCounters(keys: string[]): Promise<Map<string, number>>;
    /**
     * Subscribe to cache invalidation events
     *
     * @param callback - Function to call when invalidation event received
     */
    subscribeToInvalidations(callback: InvalidationCallback): Promise<void>;
    /**
     * Publish a cache invalidation event
     *
     * @param event - The invalidation event to publish
     */
    publishInvalidation(event: Omit<InvalidationEvent, 'timestamp' | 'sourceInstance'>): Promise<void>;
    /**
     * Invalidate a specific key and notify other instances
     *
     * @param key - Key to invalidate
     */
    invalidateKey(key: string): Promise<void>;
    /**
     * Invalidate all keys matching a pattern
     *
     * @param pattern - Pattern to match (e.g., 'session:*')
     */
    invalidatePattern(pattern: string): Promise<void>;
    /**
     * Ping Redis to check connectivity
     *
     * @returns Latency in milliseconds
     */
    ping(): Promise<number>;
    /**
     * Get the current health status
     *
     * @returns Health status object
     */
    getHealthStatus(): Promise<RedisHealthStatus>;
    /**
     * Check if Redis is currently healthy
     */
    get healthy(): boolean;
    /**
     * Close all connections
     */
    close(): Promise<void>;
    /**
     * Get the raw Redis client (for advanced operations)
     * Use with caution - prefer the high-level API
     */
    getRawClient(): Promise<Redis>;
    /**
     * Clear the fallback cache
     */
    clearFallbackCache(): void;
    /**
     * Cleanup expired entries in fallback cache
     */
    cleanupFallbackCache(): void;
}
/**
 * Get or create the singleton RedisStateProvider
 *
 * @param config - Optional configuration (only used on first call)
 * @returns The singleton RedisStateProvider instance
 */
export declare function getRedisStateProvider(config?: Partial<RedisStateConfig>): RedisStateProvider;
/**
 * Reset the singleton instance (primarily for testing)
 */
export declare function resetRedisStateProvider(): Promise<void>;
/**
 * Create a new RedisStateProvider instance (for testing or isolated use)
 */
export declare function createRedisStateProvider(config?: Partial<RedisStateConfig>): RedisStateProvider;
export default RedisStateProvider;
//# sourceMappingURL=distributed-state.d.ts.map