/**
 * Database Connection Pool Manager
 *
 * Provides advanced connection pooling capabilities for the Vorion security platform
 * with health monitoring, automatic reconnection, and comprehensive metrics.
 *
 * Features:
 * - Configurable pool size (min/max connections)
 * - Connection lifecycle management with validation
 * - Overflow queue with timeout for burst handling
 * - Health checks with ping and query validation
 * - Automatic reconnection on failure
 * - Dead connection eviction
 * - Slow query detection
 * - Transaction support with auto-commit/rollback
 * - Comprehensive Prometheus metrics
 *
 * @packageDocumentation
 */
import { Pool, PoolClient } from 'pg';
import { VorionError, TimeoutError } from './errors.js';
/**
 * Configuration for the Vorion connection pool
 */
export interface ConnectionPoolConfig {
    /** Database host */
    host: string;
    /** Database port */
    port: number;
    /** Database name */
    database: string;
    /** Database user */
    user: string;
    /** Database password */
    password: string;
    /** Minimum number of connections to maintain (default: 5) */
    minConnections?: number;
    /** Maximum number of connections allowed (default: 20) */
    maxConnections?: number;
    /** Time in ms before idle connections are closed (default: 30000) */
    idleTimeoutMs?: number;
    /** Time in ms to wait for a connection from the pool (default: 5000) */
    connectionTimeoutMs?: number;
    /** Maximum number of clients waiting for a connection (default: 100) */
    maxWaitingClients?: number;
    /** Whether to validate connections before returning them (default: true) */
    validateOnBorrow?: boolean;
    /** Interval in ms for eviction of dead connections (default: 60000) */
    evictionRunIntervalMs?: number;
    /** Statement timeout in ms for queries (default: 30000) */
    statementTimeoutMs?: number;
    /** Threshold in ms for slow query logging (default: 1000) */
    slowQueryThresholdMs?: number;
    /** SSL configuration for secure connections */
    ssl?: boolean | {
        rejectUnauthorized?: boolean;
    };
    /** Application name for PostgreSQL (useful for monitoring) */
    applicationName?: string;
}
/**
 * Pool statistics for monitoring
 */
export interface PoolStats {
    /** Number of active (in-use) connections */
    activeConnections: number;
    /** Number of idle connections */
    idleConnections: number;
    /** Total connections in the pool */
    totalConnections: number;
    /** Number of clients waiting for a connection */
    waitingClients: number;
    /** Pool utilization percentage (0-100) */
    utilizationPercent: number;
    /** Maximum pool size */
    maxConnections: number;
    /** Minimum pool size */
    minConnections: number;
    /** Total connections created since pool start */
    connectionsCreated: number;
    /** Total connections destroyed since pool start */
    connectionsDestroyed: number;
    /** Total successful checkouts */
    checkoutsTotal: number;
    /** Total check-ins */
    checkinsTotal: number;
    /** Total validation failures */
    validationFailures: number;
    /** Total connection errors */
    connectionErrors: number;
    /** Pool health status */
    healthy: boolean;
    /** Last health check timestamp */
    lastHealthCheck: string | null;
    /** Eviction run count */
    evictionRuns: number;
    /** Connections evicted since start */
    connectionsEvicted: number;
}
/**
 * Error thrown when pool is exhausted and timeout occurs
 */
export declare class PoolExhaustedError extends VorionError {
    readonly waitTimeMs: number;
    readonly poolStats: Partial<PoolStats>;
    code: string;
    statusCode: number;
    constructor(message: string, waitTimeMs: number, poolStats: Partial<PoolStats>);
}
/**
 * Error thrown when connection validation fails
 */
export declare class ConnectionValidationError extends VorionError {
    code: string;
    statusCode: number;
    constructor(message: string, details?: Record<string, unknown>);
}
/**
 * Error thrown when acquiring a connection times out
 */
export declare class ConnectionAcquireTimeoutError extends TimeoutError {
    readonly waitTimeMs: number;
    readonly poolStats: Partial<PoolStats>;
    code: string;
    constructor(message: string, waitTimeMs: number, poolStats: Partial<PoolStats>);
}
/**
 * Advanced database connection pool manager with health monitoring,
 * automatic reconnection, and comprehensive metrics.
 *
 * @example
 * ```typescript
 * const manager = ConnectionPoolManager.getInstance();
 *
 * // Initialize with configuration
 * await manager.initialize({
 *   host: 'localhost',
 *   port: 5432,
 *   database: 'vorion',
 *   user: 'vorion',
 *   password: 'secret',
 *   minConnections: 5,
 *   maxConnections: 20,
 * });
 *
 * // Use withConnection for automatic resource management
 * const users = await manager.withConnection(async (client) => {
 *   const result = await client.query('SELECT * FROM users WHERE active = $1', [true]);
 *   return result.rows;
 * });
 *
 * // Use transaction for transactional operations
 * await manager.transaction(async (client) => {
 *   await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [100, fromId]);
 *   await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [100, toId]);
 * });
 *
 * // Get pool statistics
 * const stats = manager.getStats();
 * console.log(`Pool utilization: ${stats.utilizationPercent}%`);
 *
 * // Shutdown gracefully
 * await manager.shutdown();
 * ```
 */
export declare class ConnectionPoolManager {
    private static instance;
    private pool;
    private config;
    private connections;
    private waitingQueue;
    private evictionInterval;
    private metricsInterval;
    private isShuttingDown;
    private isInitialized;
    private stats;
    private constructor();
    /**
     * Get the singleton instance of the connection pool manager
     */
    static getInstance(): ConnectionPoolManager;
    /**
     * Reset the singleton instance (primarily for testing)
     */
    static resetInstance(): void;
    /**
     * Initialize the connection pool with the given configuration
     */
    initialize(config?: Partial<ConnectionPoolConfig>): Promise<void>;
    /**
     * Warm up the pool by creating minimum number of connections
     */
    private warmUp;
    /**
     * Acquire a connection from the pool
     */
    acquire(): Promise<PoolClient>;
    /**
     * Acquire a connection with timeout handling
     */
    private acquireWithTimeout;
    /**
     * Release a connection back to the pool
     */
    release(client: PoolClient, destroy?: boolean): void;
    /**
     * Execute a callback with automatic connection management
     */
    withConnection<T>(callback: (client: PoolClient) => Promise<T>, operationName?: string): Promise<T>;
    /**
     * Execute a transaction with automatic commit/rollback
     */
    transaction<T>(callback: (client: PoolClient) => Promise<T>, operationName?: string): Promise<T>;
    /**
     * Validate a connection
     */
    private validateConnection;
    /**
     * Destroy a connection
     */
    private destroyConnection;
    /**
     * Start the eviction process for dead/idle connections
     */
    private startEvictionProcess;
    /**
     * Run eviction of dead/idle connections
     */
    private runEviction;
    /**
     * Start metrics collection interval
     */
    private startMetricsCollection;
    /**
     * Update Prometheus metrics
     */
    private updateMetrics;
    /**
     * Get pool statistics
     */
    getStats(): PoolStats;
    /**
     * Perform a health check on the pool
     */
    healthCheck(): Promise<{
        healthy: boolean;
        latencyMs: number;
        stats: PoolStats;
        error?: string;
    }>;
    /**
     * Shutdown the pool gracefully
     */
    shutdown(timeoutMs?: number): Promise<void>;
    /**
     * Check if the pool is initialized
     */
    isPoolInitialized(): boolean;
    /**
     * Get the underlying pg Pool (for advanced usage)
     */
    getUnderlyingPool(): Pool | null;
}
/**
 * Get the global connection pool manager instance.
 * The pool is automatically initialized on first access if configuration is available.
 *
 * @example
 * ```typescript
 * const pool = getPool();
 *
 * // Use the pool
 * const result = await pool.withConnection(async (client) => {
 *   return client.query('SELECT * FROM users');
 * });
 * ```
 */
export declare function getConnectionPool(): ConnectionPoolManager;
/**
 * Initialize the connection pool with custom configuration.
 * Call this once at application startup.
 *
 * @example
 * ```typescript
 * await initializeConnectionPool({
 *   minConnections: 10,
 *   maxConnections: 50,
 *   validateOnBorrow: true,
 * });
 * ```
 */
export declare function initializeConnectionPool(config?: Partial<ConnectionPoolConfig>): Promise<ConnectionPoolManager>;
/**
 * Shutdown the connection pool gracefully.
 * Call this during application shutdown.
 *
 * @example
 * ```typescript
 * process.on('SIGTERM', async () => {
 *   await shutdownConnectionPool();
 *   process.exit(0);
 * });
 * ```
 */
export declare function shutdownConnectionPool(timeoutMs?: number): Promise<void>;
export default ConnectionPoolManager;
//# sourceMappingURL=db-pool.d.ts.map