/**
 * Redis Circuit Breaker and Resilience
 *
 * Provides circuit breaker protection and graceful fallbacks for Redis operations
 * to prevent cascading failures when Redis is unavailable or degraded.
 *
 * Features:
 * - Circuit breaker with CLOSED -> OPEN -> HALF_OPEN states
 * - Graceful fallbacks when Redis is unavailable:
 *   - Rate limiting: allow requests with warning
 *   - Locks: in-memory mutex (single instance only)
 *   - Cache: bypass cache, query DB directly
 * - 5 second timeout for all Redis operations
 * - Metrics export for monitoring
 *
 * @packageDocumentation
 */
import { CircuitState, CircuitBreakerOpenError } from './circuit-breaker.js';
import type { CircuitBreaker } from './circuit-breaker.js';
export { CircuitState, CircuitBreakerOpenError };
/**
 * Redis operation timeout in milliseconds (5 seconds)
 */
export declare const REDIS_OPERATION_TIMEOUT_MS = 5000;
/**
 * Redis circuit breaker service name
 */
export declare const REDIS_SERVICE_NAME = "redis";
/**
 * Get the Redis circuit breaker instance
 */
export declare function getRedisCircuitBreaker(): CircuitBreaker;
/**
 * Check if the Redis circuit is currently open
 */
export declare function isRedisCircuitOpen(): Promise<boolean>;
/**
 * Get Redis circuit breaker status for monitoring
 */
export declare function getRedisCircuitStatus(): Promise<{
    name: string;
    state: CircuitState;
    failureCount: number;
    failureThreshold: number;
    resetTimeoutMs: number;
    timeUntilReset: number | null;
}>;
/**
 * Execute a Redis operation with circuit breaker protection and timeout.
 *
 * @param fn - The Redis operation to execute
 * @param options - Optional configuration
 * @returns The result of the Redis operation
 * @throws CircuitBreakerOpenError when circuit is open
 * @throws TimeoutError when operation exceeds timeout
 *
 * @example
 * ```typescript
 * const value = await withRedisCircuitBreaker(
 *   async () => redis.get('mykey'),
 *   { operationName: 'getKey' }
 * );
 * ```
 */
export declare function withRedisCircuitBreaker<T>(fn: () => Promise<T>, options?: {
    operationName?: string;
    timeoutMs?: number;
}): Promise<T>;
/**
 * Execute a Redis operation with circuit breaker protection,
 * returning a result object instead of throwing on circuit open.
 *
 * @param fn - The Redis operation to execute
 * @param options - Optional configuration
 * @returns Result object with success flag and result/error
 */
export declare function withRedisCircuitBreakerResult<T>(fn: () => Promise<T>, options?: {
    operationName?: string;
    timeoutMs?: number;
}): Promise<{
    success: boolean;
    result?: T;
    error?: Error;
    circuitOpen: boolean;
}>;
/**
 * Rate limiting with graceful Redis fallback.
 *
 * When Redis is down:
 * - Logs a warning
 * - Allows the request to proceed (fail-open for availability)
 * - Returns a result indicating fallback mode
 *
 * @param key - Rate limit key (e.g., 'ratelimit:tenant:123:minute')
 * @param limit - Maximum requests allowed in the window
 * @param windowSeconds - Window duration in seconds
 * @returns Rate limit result with remaining requests and fallback status
 *
 * @example
 * ```typescript
 * const result = await rateLimitWithFallback(
 *   `ratelimit:${tenantId}:minute`,
 *   100,
 *   60
 * );
 *
 * if (!result.allowed) {
 *   return reply.status(429).send({ error: 'Rate limit exceeded' });
 * }
 *
 * if (result.fallbackMode) {
 *   // Log that we're operating without rate limit protection
 *   logger.warn({ tenantId }, 'Rate limiting in fallback mode');
 * }
 * ```
 */
export declare function rateLimitWithFallback(key: string, limit: number, windowSeconds: number): Promise<{
    allowed: boolean;
    remaining: number;
    resetAt: number;
    fallbackMode: boolean;
}>;
/**
 * Distributed lock with graceful Redis fallback.
 *
 * When Redis is down:
 * - Falls back to in-memory mutex (single instance only!)
 * - Logs a warning about single-instance limitation
 * - Still provides mutual exclusion within the current process
 *
 * @param key - Lock key
 * @param ownerId - Unique identifier for the lock owner
 * @param ttlMs - Lock time-to-live in milliseconds
 * @param options - Optional configuration
 * @returns Lock result with fallback status
 *
 * @example
 * ```typescript
 * const lock = await acquireLockWithFallback(
 *   `lock:order:${orderId}`,
 *   `worker:${workerId}`,
 *   30000 // 30 seconds
 * );
 *
 * if (!lock.acquired) {
 *   return { error: 'Could not acquire lock' };
 * }
 *
 * try {
 *   if (lock.fallbackMode) {
 *     logger.warn({ orderId }, 'Using in-memory lock - not distributed!');
 *   }
 *   // Process order...
 * } finally {
 *   await releaseLockWithFallback(lock.key, lock.ownerId);
 * }
 * ```
 */
export declare function acquireLockWithFallback(key: string, ownerId: string, ttlMs: number, options?: {
    waitTimeoutMs?: number;
}): Promise<{
    acquired: boolean;
    key: string;
    ownerId: string;
    fallbackMode: boolean;
    release: () => Promise<boolean>;
}>;
/**
 * Release a distributed lock with fallback support.
 *
 * @param key - Lock key
 * @param ownerId - Lock owner identifier
 * @returns Whether the lock was successfully released
 */
export declare function releaseLockWithFallback(key: string, ownerId: string): Promise<boolean>;
/**
 * Cache get with graceful Redis fallback.
 *
 * When Redis is down:
 * - Returns null/undefined (cache miss)
 * - Caller should then query the database directly
 * - Logs a warning about cache bypass
 *
 * @param key - Cache key
 * @param options - Optional configuration
 * @returns Cached value or null if not found or Redis unavailable
 *
 * @example
 * ```typescript
 * const cached = await cacheGetWithFallback<UserData>(`user:${userId}`);
 *
 * if (cached.value) {
 *   return cached.value;
 * }
 *
 * if (cached.fallbackMode) {
 *   logger.debug({ userId }, 'Cache bypassed - querying database');
 * }
 *
 * // Query database and optionally cache the result
 * const user = await db.select().from(users).where(eq(users.id, userId));
 * await cacheSetWithFallback(`user:${userId}`, user, 300);
 * return user;
 * ```
 */
export declare function cacheGetWithFallback<T>(key: string, options?: {
    parse?: boolean;
}): Promise<{
    value: T | null;
    fallbackMode: boolean;
}>;
/**
 * Cache set with graceful Redis fallback.
 *
 * When Redis is down:
 * - Logs a warning about cache write failure
 * - Returns false to indicate the value was not cached
 * - Does not throw an error
 *
 * @param key - Cache key
 * @param value - Value to cache
 * @param ttlSeconds - Time-to-live in seconds
 * @returns Whether the value was successfully cached
 */
export declare function cacheSetWithFallback<T>(key: string, value: T, ttlSeconds: number): Promise<{
    success: boolean;
    fallbackMode: boolean;
}>;
/**
 * Cache delete with graceful Redis fallback.
 *
 * @param key - Cache key to delete
 * @returns Whether the key was successfully deleted
 */
export declare function cacheDeleteWithFallback(key: string): Promise<{
    success: boolean;
    fallbackMode: boolean;
}>;
/**
 * Force the Redis circuit breaker to open state.
 */
export declare function forceRedisCircuitOpen(): Promise<void>;
/**
 * Force the Redis circuit breaker to closed state.
 */
export declare function forceRedisCircuitClose(): Promise<void>;
/**
 * Reset the Redis circuit breaker.
 */
export declare function resetRedisCircuit(): Promise<void>;
/**
 * Redis health check with circuit breaker status.
 */
export declare function checkRedisHealthWithCircuit(): Promise<{
    healthy: boolean;
    latencyMs?: number;
    error?: string;
    circuit: {
        state: CircuitState;
        failureCount: number;
        failureThreshold: number;
        timeUntilReset: number | null;
    };
}>;
/**
 * Stop the in-memory mutex fallback.
 * Call this during graceful shutdown.
 */
export declare function stopInMemoryMutex(): void;
//# sourceMappingURL=redis-resilience.d.ts.map