/*!
* @Author: richen
* @Date: 2026-04-24 16:20:39
* @License: BSD (3-Clause)
* @Copyright (c) - <richenlin(at)gmail.com>
* @HomePage: https://koatty.org/
*/
import { ChannelOptions } from '@grpc/grpc-js';
import { Http2SecureServer } from 'http2';
import { Http2Session } from 'http2';
import { IComponent } from 'koatty_core';
import { IncomingMessage } from 'http';
import { KoattyApplication } from 'koatty_core';
import { KoattyServer } from 'koatty_core';
import { NativeServer } from 'koatty_core';
import { Server } from '@grpc/grpc-js';
import { Server as Server_2 } from 'http';
import { Server as Server_3 } from 'https';
import { ServerResponse } from 'http';
import { ServiceDefinition } from '@grpc/grpc-js';
import { Socket } from 'net';
import { TLSSocket } from 'tls';
import { UntypedHandleCall } from '@grpc/grpc-js';
import * as WS from 'ws';

/**
 * Base server class with template method pattern
 * 模板方法模式：定义算法骨架，子类实现具体步骤
 * @template T - Options type extending ListeningOptions
 * @template S - Server instance type (defaults to any for backward compatibility)
 */
declare abstract class BaseServer<T extends ListeningOptions = ListeningOptions, S = any> implements KoattyServer {
    options: T;
    readonly protocol: string;
    status: number;
    listenCallback?: () => void;
    constructor(app: KoattyApplication, options: T);
    /**
     * 模板方法：服务器初始化流程
     * 定义了所有协议服务器的通用初始化步骤
     */
    /**
     * 模板方法：配置热更新流程
     */
    updateConfig(newConfig: Partial<T>): Promise<boolean>;
    /**
     * 模板方法：优雅关闭流程
     * 简化实现，直接执行关闭步骤
     */
    gracefulShutdown(options?: GracefulShutdownOptions): Promise<ShutdownResult>;
    /**
     * 执行带超时的异步操作
     */
    /**
     * 检测配置变更
     */
    /**
     * 设置连接池事件监听（公共逻辑）
     */
    /**
     * 设置定期清理（公共逻辑）
     */
    /**
     * 处理需要重启的配置变更
     */
    /**
     * 处理运行时配置变更
     */
    /**
     * 停止监控和清理（公共逻辑）
     */
    /**
     * 获取活跃连接数（公共逻辑）
     */
    /**
     * 获取连接统计信息（公共接口）
     */
    getConnectionStats(): ConnectionStats;
    /**
     * 获取连接池健康状态（公共接口）
     */
    getConnectionPoolHealth(): ConnectionPoolHealth;
    /**
     * 获取连接池指标（公共接口）
     */
    getConnectionPoolMetrics(): ConnectionPoolMetrics;
    /**
     * 初始化连接池（各协议自定义）
     */
    /**
     * 创建协议特定的服务器实例（各协议自定义）
     */
    /**
     * 配置服务器选项（各协议自定义）
     */
    /**
     * 协议特定的额外初始化（各协议自定义，可选实现）
     */
    /**
     * 分析配置变更影响（各协议自定义）
     */
    /**
     * 运行时配置变更处理（各协议自定义）
     */
    /**
     * 提取相关配置用于日志（各协议自定义）
     */
    /**
     * 停止接受新连接（各协议自定义）
     */
    /**
     * 等待现有连接完成（各协议自定义）
     */
    /**
     * 强制关闭剩余连接（各协议自定义）
     */
    /**
     * 强制关闭（各协议自定义）
     */
    /**
     * 启动服务器
     */
    abstract Start(listenCallback?: () => void): any;
    /**
     * 获取服务器状态
     */
    abstract getStatus(): number;
    /**
     * 获取原生服务器实例
     */
    abstract getNativeServer(): NativeServer;
    /**
     * 销毁服务器（抽象方法，各协议实现）
     * 内部应该调用 gracefulShutdown 进行优雅关闭
     */
    abstract destroy(): Promise<void>;
    /**
     * 停止服务器（向后兼容）
     */
    Stop(callback?: (err?: Error) => void): void;
}

/**
 * Base Server Options
 *
 * @export
 * @interface BaseServerOptions
 */
declare interface BaseServerOptions {
    hostname: string;
    port: number;
    protocol: string;
    trace?: boolean;
    connectionPool?: ConnectionPoolConfig;
    health?: HealthCheckConfig;
    ext?: {
        [key: string]: unknown;
    };
    [key: string]: unknown;
}

/**
 * 基础SSL配置
 */
declare interface BaseSSLConfig {
    enabled?: boolean;
    key?: string;
    cert?: string;
    ca?: string;
    passphrase?: string;
    ciphers?: string;
    honorCipherOrder?: boolean;
    secureProtocol?: string;
}

/**
 * Configuration change detection result
 */
declare interface ConfigChangeAnalysis {
    requiresRestart: boolean;
    changedKeys: string[];
    restartReason?: string;
    canApplyRuntime?: boolean;
}

/**
 * 统一连接池配置接口
 */
declare interface ConnectionPoolConfig {
    connectionTimeout?: number;
    maxConnections?: number;
    maxSessionMemory?: number;
    maxHeaderListSize?: number;
    keepAliveTimeout?: number;
    headersTimeout?: number;
    requestTimeout?: number;
    pingInterval?: number;
    pongTimeout?: number;
    heartbeatInterval?: number;
    protocolSpecific?: {
        maxSessionMemory?: number;
        maxHeaderListSize?: number;
        maxIdleTimeout?: number;
        maxUdpPayloadSize?: number;
        initialMaxStreamsBidi?: number;
        initialMaxStreamsUni?: number;
        maxReceiveMessageLength?: number;
        maxSendMessageLength?: number;
        keepAliveTime?: number;
        pingInterval?: number;
        pongTimeout?: number;
        heartbeatInterval?: number;
    };
    warmup?: {
        enabled?: boolean;
        initialConnections?: number;
        timeout?: number;
        retryCount?: number;
    };
}

/**
 * Connection pool event types
 */
declare enum ConnectionPoolEvent {
    CONNECTION_ADDED = "connection_added",
    CONNECTION_REMOVED = "connection_removed",
    CONNECTION_TIMEOUT = "connection_timeout",
    CONNECTION_ERROR = "connection_error",
    POOL_LIMIT_REACHED = "pool_limit_reached",
    HEALTH_STATUS_CHANGED = "health_status_changed"
}

/**
 * Event data type mapping for type-safe event handling
 */
declare interface ConnectionPoolEventMap {
    [ConnectionPoolEvent.CONNECTION_ADDED]: {
        connectionId: string;
    };
    [ConnectionPoolEvent.CONNECTION_REMOVED]: {
        connectionId: string;
        reason?: string;
    };
    [ConnectionPoolEvent.CONNECTION_TIMEOUT]: {
        connectionId: string;
        timeout: number;
    };
    [ConnectionPoolEvent.CONNECTION_ERROR]: {
        connectionId?: string;
        error: Error;
    };
    [ConnectionPoolEvent.POOL_LIMIT_REACHED]: {
        currentConnections: number;
        maxConnections?: number;
    };
    [ConnectionPoolEvent.HEALTH_STATUS_CHANGED]: {
        oldStatus: ConnectionPoolStatus;
        newStatus: ConnectionPoolStatus;
        health: ConnectionPoolHealth;
    };
}

/**
 * 连接池健康状态
 */
declare interface ConnectionPoolHealth {
    status: ConnectionPoolStatus;
    utilizationRatio: number;
    activeConnections: number;
    maxConnections: number;
    rejectedConnections: number;
    averageResponseTime: number;
    errorRate: number;
    message: string;
    lastUpdated: number;
}

/**
 * Abstract connection pool manager
 */
declare abstract class ConnectionPoolManager<T = any> {
    protected waitingQueue: Array<{
        resolve: (result: ConnectionRequestResult<T>) => void;
        reject: (error: Error) => void;
        options: ConnectionRequestOptions;
        timestamp: number;
    }>;
    constructor(protocol: string, config?: ConnectionPoolConfig);
    /**
     * 初始化指标
     */
    /**
     * 初始化健康状态
     */
    /**
     * Validate and normalize configuration
     */
    /**
     * 申请连接
     */
    requestConnection(options?: ConnectionRequestOptions): Promise<ConnectionRequestResult<T>>;
    /**
     * 释放连接
     */
    releaseConnection(connection: T, options?: {
        destroy?: boolean;
        error?: Error;
    }): Promise<boolean>;
    /**
     * Add connection to the pool
     */
    addConnection(connection: T, metadata?: any): Promise<boolean>;
    /**
     * Remove connection from pool
     */
    removeConnection(connection: T, reason?: string): Promise<void>;
    /**
     * Get active connection count
     */
    getActiveConnectionCount(): number;
    /**
     * Check if the connection is healthy
     */
    abstract isConnectionHealthy(connection: T): boolean;
    /**
     * Close all connections
     */
    closeAllConnections(timeout?: number): Promise<void>;
    /**
     * Protocol-specific connection validation
     */
    /**
     * Protocol-specific connection cleanup
     */
    /**
     * 获取可用连接
     */
    protected abstract getAvailableConnection(): Promise<{
        connection: T;
        id: string;
    } | null>;
    /**
     * 创建新连接
     */
    protected createNewConnection(options: ConnectionRequestOptions): Promise<{
        connection: T;
        id: string;
        metadata?: any;
    } | null>;
    /**
     * Check if new connections can be accepted
     */
    canAcceptConnection(): boolean;
    /**
     * Update connection pool health status
     */
    updateHealthStatus(): void;
    /**
     * Get connection pool health status
     */
    getHealth(): ConnectionPoolHealth;
    /**
     * Get connection pool metrics
     */
    getMetrics(): ConnectionPoolMetrics;
    /**
     * Get connection pool configuration
     */
    getConfig(): Readonly<ConnectionPoolConfig>;
    /**
     * Update connection pool configuration
     */
    updateConfig(newConfig: Partial<ConnectionPoolConfig>): Promise<boolean>;
    /**
     * Add event listener
     */
    on<E extends ConnectionPoolEvent>(event: E, listener: (data: ConnectionPoolEventMap[E]) => void): void;
    /**
     * Remove event listener
     */
    off<E extends ConnectionPoolEvent>(event: E, listener: (data: ConnectionPoolEventMap[E]) => void): void;
    /**
     * 辅助方法
     */
    /**
     * Trigger event with enhanced error handling
     */
    /**
     * Record connection event for statistics
     */
    /**
     * Record request latency
     */
    /**
     * Destroy connection pool manager
     */
    destroy(): Promise<void>;
    /**
     * Warm up connection pool with initial connections
     * Creates connections before they are needed to reduce latency
     * @param count Number of connections to warm up (default: from config)
     * @param options Warmup options
     * @returns Warmup result
     */
    warmup(count?: number, options?: {
        timeout?: number;
        retryCount?: number;
    }): Promise<{
        success: boolean;
        created: number;
        failed: number;
        duration: number;
        errors: Error[];
    }>;
    /**
     * Create a single warmup connection with retry logic
     */
    /**
     * 统一的连接获取接口 - 对外提供统一API
     */
    getConnection(options?: ConnectionRequestOptions): Promise<ConnectionRequestResult<T>>;
    /**
     * 统一的连接添加接口 - 协议无关的连接注册
     * 各协议通过此方法注册新连接到池中
     */
    registerConnection(connection: T, metadata?: any): Promise<boolean>;
    /**
     * 协议特定的连接处理器设置 - 子类实现
     */
    /**
     * 协议特定的连接创建逻辑 - 子类实现
     */
    protected abstract createProtocolConnection(options: ConnectionRequestOptions): Promise<{
        connection: T;
        metadata?: any;
    } | null>;
}

/**
 * 连接池指标
 */
declare interface ConnectionPoolMetrics extends ConnectionStats {
    protocol: string;
    poolConfig: ConnectionPoolConfig;
    health: ConnectionPoolHealth;
    performance: {
        throughput: number;
        latency: {
            p50: number;
            p95: number;
            p99: number;
        };
        memoryUsage: number;
        cpuUsage: number;
    };
    uptime: number;
}

/**
 * 连接池状态枚举
 */
declare enum ConnectionPoolStatus {
    HEALTHY = "healthy",
    DEGRADED = "degraded",
    OVERLOADED = "overloaded",
    UNAVAILABLE = "unavailable"
}

/**
 * 连接申请选项
 */
declare interface ConnectionRequestOptions {
    timeout?: number;
    priority?: 'low' | 'normal' | 'high';
    metadata?: Record<string, any>;
}

/**
 * 连接申请结果
 */
declare interface ConnectionRequestResult<T> {
    connection: T | null;
    success: boolean;
    error?: Error;
    waitTime: number;
    connectionId?: string;
}

/**
 * 连接统计信息接口
 */
declare interface ConnectionStats {
    activeConnections: number;
    totalConnections: number;
    connectionsPerSecond: number;
    averageLatency: number;
    errorRate: number;
}

export declare function createHealthCheckMiddleware(config?: HealthCheckConfig): (req: IncomingMessage, res: ServerResponse, next: () => Promise<void>) => Promise<void>;

export declare function createRateLimitMiddleware(options?: RateLimitOptions): (req: IncomingMessage, res: ServerResponse, next: () => Promise<void>) => Promise<void>;

/**
 * Dynamic Ring Buffer (Auto-resizing Circular Buffer)
 * 动态环形缓冲区 - 支持自动扩容和缩容
 *
 * Features:
 * - O(1) write operations (no array shifts or slices)
 * - O(1) amortized read operations
 * - Dynamic capacity adjustment based on usage
 * - Memory-efficient with upper and lower bounds
 * - Automatic overwrite of oldest data when full
 *
 * Use cases:
 * - High-frequency metrics collection
 * - Adaptive performance monitoring
 * - Memory-constrained environments
 */
export declare class DynamicRingBuffer<T = number> {
    /**
     * Create a dynamic ring buffer with auto-resize capability
     * @param initialCapacity Starting capacity
     * @param options Configuration options
     */
    constructor(initialCapacity: number, options?: {
        maxCapacity?: number;
        minCapacity?: number;
        autoResize?: boolean;
        resizeThreshold?: number;
        shrinkThreshold?: number;
        resizeFactor?: number;
        resizeCooldown?: number;
    });
    /**
     * Add an item to buffer with auto-resize
     * If buffer is full, triggers resize or overwrites oldest item
     * @param item Item to add
     */
    push(item: T): void;
    /**
     * Check if buffer should expand
     */
    /**
     * Check if buffer should shrink
     */
    /**
     * Expand buffer capacity
     */
    /**
     * Shrink buffer capacity
     */
    /**
     * Get all items in insertion order (oldest to newest)
     * @returns Array of items
     */
    toArray(): T[];
    /**
     * Get a sorted copy of buffer contents
     * @param compareFn Optional comparison function
     * @returns Sorted array
     */
    toSortedArray(compareFn?: (a: T, b: T) => number): T[];
    /**
     * Clear all items from buffer
     */
    clear(): void;
    /**
     * Get number of items currently in buffer
     * @returns Current item count
     */
    get length(): number;
    /**
     * Get current capacity of buffer
     * @returns Current capacity
     */
    get size(): number;
    /**
     * Get initial capacity
     * @returns Initial capacity
     */
    get initialSize(): number;
    /**
     * Get maximum capacity
     * @returns Maximum capacity
     */
    get maxSize(): number;
    /**
     * Get minimum capacity
     * @returns Minimum capacity
     */
    get minSize(): number;
    /**
     * Check if buffer is empty
     * @returns True if empty
     */
    isEmpty(): boolean;
    /**
     * Check if buffer is full
     * @returns True if full
     */
    isFull(): boolean;
    /**
     * Get utilization ratio (0-1)
     * @returns Utilization ratio
     */
    get utilization(): number;
    /**
     * Get an item at a specific index (0 = oldest, length-1 = newest)
     * @param index Index to retrieve
     * @returns Item at index or undefined if out of range
     */
    get(index: number): T | undefined;
    /**
     * Get oldest item without removing it
     * @returns Oldest item or undefined if buffer is empty
     */
    peek(): T | undefined;
    /**
     * Get newest item
     * @returns Newest item or undefined if buffer is empty
     */
    peekLast(): T | undefined;
    /**
     * Calculate percentile from buffer contents (e.g., 0.5 for median, 0.95 for P95)
     * @param percentile Percentile value between 0 and 1
     * @returns Percentile value or undefined if buffer is empty
     */
    getPercentile(percentile: number): T | undefined;
    /**
     * Get average of numeric buffer contents
     * @returns Average value or undefined if buffer is empty
     */
    getAverage(): number | undefined;
    /**
     * Iterate over buffer contents (oldest to newest)
     * @param callback Function to call for each item
     */
    forEach(callback: (item: T, index: number) => void): void;
    /**
     * Map buffer contents to a new array
     * @param callback Function to transform each item
     * @returns New array of transformed items
     */
    map<U>(callback: (item: T, index: number) => U): U[];
    /**
     * Filter buffer contents
     * @param predicate Function to test each item
     * @returns New array of items that pass test
     */
    filter(predicate: (item: T, index: number) => boolean): T[];
    /**
     * Reduce buffer contents to a single value
     * @param callback Reducer function
     * @param initialValue Initial value for accumulator
     * @returns Reduced value
     */
    reduce<U>(callback: (accumulator: U, item: T, index: number) => U, initialValue: U): U;
    /**
     * Manually trigger resize up
     * @param factor Optional resize factor override
     */
    resizeUpManual(factor?: number): void;
    /**
     * Manually trigger resize down
     * @param factor Optional resize factor override
     */
    resizeDownManual(factor?: number): void;
    /**
     * Get resize statistics
     */
    getStats(): {
        resizeCount: number;
        lastResizeTime: number;
        currentCapacity: number;
        utilization: number;
        resizeThreshold: number;
        shrinkThreshold: number;
    };
}

declare interface GracefulShutdownOptions {
    timeout?: number;
    drainDelay?: number;
    stepTimeout?: number;
}

/**
 * 简化的gRPC连接接口
 */
declare interface GrpcConnection {
    id: string;
    peer: string;
    metadata: any;
    cancelled: boolean;
    deadline?: Date;
    [key: string]: any;
}

/**
 * gRPC连接池管理器
 */
declare class GrpcConnectionPoolManager extends ConnectionPoolManager<GrpcConnection> {
    constructor(config?: ConnectionPoolConfig);
    /**
     * 验证gRPC连接
     */
    /**
     * 清理gRPC连接
     */
    /**
     * 获取可用连接
     */
    protected getAvailableConnection(): Promise<{
        connection: GrpcConnection;
        id: string;
    } | null>;
    /**
     * 检查连接是否健康
     */
    isConnectionHealthy(connection: GrpcConnection): boolean;
    /**
     * 添加gRPC连接（由服务器调用）
     */
    addGrpcConnection(peer: string, callMetadata?: any): Promise<boolean>;
    /**
     * 设置连接事件处理器
     */
    /**
     * 处理gRPC调用完成
     */
    handleCallComplete(connection: GrpcConnection, success: boolean): Promise<void>;
    /**
     * 更新调用指标
     */
    /**
     * 判断是否为一元调用
     */
    /**
     * 处理流响应发送
     */
    handleStreamResponse(connection: GrpcConnection, data: any): Promise<void>;
    /**
     * 清理过期连接
     */
    /**
     * 获取连接统计信息
     */
    getConnectionStats(): {
        grpcSpecific: {
            totalCalls: number;
            totalErrors: number;
            totalStreams: number;
            activeStreams: number;
            totalBytesReceived: number;
            totalBytesSent: number;
            errorRate: number;
            callMetrics: {
                totalUnarycalls: number;
                totalStreamingCalls: number;
                totalErrors: number;
                averageCallDuration: number;
                activeStreams: number;
            };
        };
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 获取gRPC特定指标
     */
    getGrpcMetrics(): {
        connections: {
            id: any;
            peer: any;
            callCount: any;
            errorCount: any;
            streamCount: any;
            activeStreams: any;
            totalBytesReceived: any;
            totalBytesSent: any;
            age: number;
            idle: number;
        }[];
        totalUnarycalls: number;
        totalStreamingCalls: number;
        totalErrors: number;
        averageCallDuration: number;
        activeStreams: number;
    };
    /**
     * 找到连接ID的辅助方法
     */
    /**
     * 创建连接ID
     */
    /**
     * 销毁连接池
     */
    destroy(): Promise<void>;
    /**
     * 协议特定的连接处理器设置
     */
    /**
     * 协议特定的连接创建逻辑
     */
    protected createProtocolConnection(_options: ConnectionRequestOptions): Promise<{
        connection: GrpcConnection;
        metadata?: any;
    } | null>;
}

export declare class GrpcServer extends BaseServer<GrpcServerOptions, Server> {
    options: GrpcServerOptions;
    constructor(app: KoattyApplication, options: GrpcServerOptions);
    /**
     * 初始化gRPC连接池
     */
    /**
     * 创建gRPC服务器实例
     */
    /**
     * 配置gRPC服务器选项
     */
    /**
     * gRPC特定的额外初始化
     */
    protected extractRelevantConfig(config: GrpcServerOptions): {
        hostname: string;
        port: number;
        protocol: string;
        sslEnabled: boolean;
        connectionPool: {
            maxConnections: number;
            keepAliveTime: number;
            keepAliveTimeout: number;
        };
    };
    /**
     * Create SSL credentials from configuration
     * @private
     */
    /**
     * Start Server with enhanced connection management
     */
    Start(listenCallback?: () => void): NativeServer;
    /**
     * Start connection monitoring and statistics collection
     * @private
     */
    /**
     * Register Service with enhanced logging and monitoring
     */
    RegisterService(impl: ServiceImplementation): void;
    /**
     * Get connection statistics
     */
    getConnectionStats(): ConnectionStats;
    /**
     * Get connection pool health
     */
    getConnectionPoolHealth(): ConnectionPoolHealth;
    /**
     * Get connection pool metrics
     */
    getConnectionPoolMetrics(): ConnectionPoolMetrics;
    /**
     * Get status
     */
    getStatus(): number;
    /**
     * Get native server
     */
    getNativeServer(): NativeServer;
    /**
     * 销毁服务器
     */
    destroy(): Promise<void>;
}

/**
 * gRPC Server Options with enhanced configuration
 */
declare interface GrpcServerOptions extends BaseServerOptions {
    channelOptions?: ChannelOptions;
    ssl?: SSLConfig;
    connectionPool?: ConnectionPoolConfig;
}

export declare interface HealthCheckConfig {
    enabled?: boolean;
    path?: string;
    readiness?: string;
    detailed?: boolean;
    memoryThresholdMB?: number;
}

export declare class HealthCheckMiddleware {
    constructor(config?: HealthCheckConfig);
    middleware(): (req: IncomingMessage, res: ServerResponse, next: () => Promise<void>) => Promise<void>;
}

export declare interface HealthCheckResponse {
    status: 'ok' | 'error';
    uptime: number;
    timestamp: string;
    details?: {
        memory?: NodeJS.MemoryUsage;
        cpu?: NodeJS.CpuUsage;
    };
}

/**
 * HTTP/2连接池管理器
 */
declare class Http2ConnectionPoolManager extends ConnectionPoolManager<Http2Session> {
    constructor(config?: ConnectionPoolConfig);
    /**
     * 验证HTTP/2会话
     */
    /**
     * 清理HTTP/2会话
     */
    /**
     * 获取可用会话
     */
    protected getAvailableConnection(): Promise<{
        connection: Http2Session;
        id: string;
    } | null>;
    /**
     * 创建新连接 - HTTP/2会话通常是被动接受的
     */
    protected createNewConnection(_options: ConnectionRequestOptions): Promise<{
        connection: Http2Session;
        id: string;
        metadata?: any;
    } | null>;
    /**
     * 检查会话是否健康
     */
    isConnectionHealthy(session: Http2Session): boolean;
    /**
     * 添加HTTP/2会话（由服务器调用）
     */
    addHttp2Session(session: Http2Session): Promise<boolean>;
    /**
     * 设置会话事件处理器
     */
    /**
     * 处理新流
     */
    /**
     * 启动会话ping（保留在TimerManager中，因为是动态创建的）
     */
    /**
     * 启动HTTP/2监控任务
     */
    /**
     * 向所有会话发送ping
     */
    /**
     * 执行健康检查
     */
    /**
     * 获取会话统计信息
     */
    getConnectionStats(): {
        availableSessions: number;
        goingAwaySessions: number;
        totalActiveStreams: number;
        totalStreams: number;
        totalStreamErrors: number;
        averageStreamsPerSession: number;
        utilizationRatio: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 获取会话详细信息
     */
    getSessionDetails(): Array<{
        id: string;
        remoteAddress: string;
        protocol: string;
        activeStreams: number;
        totalStreams: number;
        streamErrors: number;
        maxConcurrentStreams: number;
        isGoingAway: boolean;
        age: number;
        idle: number;
    }>;
    /**
     * 优雅关闭会话
     */
    gracefulCloseSession(session: Http2Session, timeout?: number): Promise<void>;
    /**
     * 找到会话ID的辅助方法
     */
    /**
     * 销毁连接池
     */
    destroy(): Promise<void>;
    /**
     * 设置协议特定的连接处理器
     */
    /**
     * 协议特定的连接创建逻辑
     */
    protected createProtocolConnection(_options: ConnectionRequestOptions): Promise<{
        connection: Http2Session;
        metadata?: any;
    } | null>;
}

/**
 * HTTP/2 Server implementation using template method pattern
 * 继承BaseServer，只实现HTTP/2特定的逻辑
 */
export declare class Http2Server extends BaseServer<Http2ServerOptions, Http2SecureServer> {
    constructor(app: KoattyApplication, options: Http2ServerOptions);
    /**
     * 初始化HTTP/2连接池
     */
    /**
     * 创建HTTP/2服务器实例
     */
    /**
     * 配置HTTP/2服务器选项
     */
    /**
     * HTTP/2特定的额外初始化
     */
    /**
     * 创建HTTP/2选项
     */
    /**
     * 创建SSL选项
     */
    /**
     * 自动SSL配置
     */
    /**
     * 手动SSL配置
     */
    /**
     * 双向TLS配置
     */
    /**
     * 设置会话处理
     */
    protected extractRelevantConfig(config: Http2ServerOptions): {
        hostname: string;
        port: number;
        protocol: string;
        sslMode: "auto" | "manual" | "mutual_tls";
        allowHTTP1: boolean;
        connectionPool: {
            maxConnections: number;
            maxSessionMemory: number;
            maxHeaderListSize: number;
        };
        http2Settings: {
            headerTableSize?: number;
            enablePush?: boolean;
            maxConcurrentStreams?: number;
            initialWindowSize?: number;
            maxFrameSize?: number;
            maxHeaderListSize?: number;
        };
    };
    /**
     * 检查SSL配置是否变更
     */
    /**
     * 检查HTTP/2配置是否变更
     */
    /**
     * 检查连接池配置是否变更
     */
    /**
     * 重写停止监控和清理方法以处理HTTP/2特定的监控间隔
     */
    Start(listenCallback?: () => void): NativeServer;
    getStatus(): number;
    getNativeServer(): NativeServer;
    /**
     * 启动连接池监控
     */
    /**
     * 获取HTTP/2统计信息
     */
    getHttp2Stats(): {
        availableSessions: number;
        goingAwaySessions: number;
        totalActiveStreams: number;
        totalStreams: number;
        totalStreamErrors: number;
        averageStreamsPerSession: number;
        utilizationRatio: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 获取当前连接状态
     */
    getConnectionsStatus(): {
        current: number;
        max: number;
    };
    /**
     * 销毁服务器
     */
    destroy(): Promise<void>;
}

/**
 * Enhanced HTTP/2 Server Options
 */
declare interface Http2ServerOptions extends BaseServerOptions {
    ssl?: SSL2Config;
    http2?: {
        maxHeaderListSize?: number;
        maxSessionMemory?: number;
        settings?: {
            headerTableSize?: number;
            enablePush?: boolean;
            maxConcurrentStreams?: number;
            initialWindowSize?: number;
            maxFrameSize?: number;
            maxHeaderListSize?: number;
        };
    };
    connectionPool?: ConnectionPoolConfig;
}

/**
 * HTTP/3连接池管理器
 */
declare class Http3ConnectionPoolManager extends ConnectionPoolManager<Http3Session> {
    constructor(config?: ConnectionPoolConfig);
    /**
     * 验证HTTP/3会话
     */
    /**
     * 清理HTTP/3会话
     */
    /**
     * 获取可用会话
     */
    protected getAvailableConnection(): Promise<{
        connection: Http3Session;
        id: string;
    } | null>;
    /**
     * 创建新连接 - HTTP/3会话通常是被动接受的
     */
    protected createNewConnection(_options: ConnectionRequestOptions): Promise<{
        connection: Http3Session;
        id: string;
        metadata?: any;
    } | null>;
    /**
     * 检查会话是否健康
     */
    isConnectionHealthy(session: Http3Session): boolean;
    /**
     * 添加HTTP/3会话（由服务器调用）
     */
    addHttp3Session(session: Http3Session): Promise<boolean>;
    /**
     * 设置会话事件处理器
     */
    /**
     * 处理新流
     */
    /**
     * 启动会话ping
     */
    /**
     * 启动HTTP/3监控任务
     */
    /**
     * 向所有会话发送ping
     */
    /**
     * 执行健康检查
     */
    /**
     * 更新会话统计信息（从 QUIC 库获取）
     */
    updateSessionStats(session: Http3Session, sessionId: string): void;
    /**
     * 获取会话统计信息
     */
    getConnectionStats(): {
        availableSessions: number;
        closingSessions: number;
        totalActiveStreams: number;
        totalStreams: number;
        totalStreamErrors: number;
        totalBytesSent: number;
        totalBytesReceived: number;
        totalPacketsLost: number;
        averageRtt: number;
        averageStreamsPerSession: number;
        utilizationRatio: number;
        packetLossRate: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 获取会话详细信息
     */
    getSessionDetails(): Array<{
        id: string;
        remoteAddress: string;
        protocol: string;
        activeStreams: number;
        totalStreams: number;
        streamErrors: number;
        maxConcurrentStreams: number;
        isClosing: boolean;
        bytesSent: number;
        bytesReceived: number;
        packetsLost: number;
        rtt: number;
        age: number;
        idle: number;
    }>;
    /**
     * 优雅关闭会话
     */
    gracefulCloseSession(session: Http3Session, timeout?: number): Promise<void>;
    /**
     * 找到会话ID的辅助方法
     */
    /**
     * 销毁连接池
     */
    destroy(): Promise<void>;
    /**
     * 设置协议特定的连接处理器
     */
    /**
     * 协议特定的连接创建逻辑
     */
    protected createProtocolConnection(_options: ConnectionRequestOptions): Promise<{
        connection: Http3Session;
        metadata?: any;
    } | null>;
}

/**
 * HTTP/3 Server implementation using template method pattern
 * 继承BaseServer，只实现HTTP/3特定的逻辑
 */
export declare class Http3Server extends BaseServer<Http3ServerOptions, any> {
    constructor(app: KoattyApplication, options: Http3ServerOptions);
    /**
     * 初始化HTTP/3连接池
     */
    /**
     * 创建HTTP/3服务器实例（使用 @matrixai/quic）
     * 注意：@matrixai/quic 是 ESM 模块，需要异步加载
     * 实际的可用性检查将在 Http3ServerAdapter.listen() 中进行
     */
    /**
     * 设置 HTTP/3 服务器的事件处理器
     */
    /**
     * 解析文件路径
     * HTTP/3 adapter 需要文件路径,如果是证书内容则需要写入临时文件
     */
    /**
     * 配置HTTP/3服务器选项
     */
    /**
     * HTTP/3特定的额外初始化
     */
    /**
     * 创建SSL选项
     */
    /**
     * 自动SSL配置
     */
    /**
     * 手动SSL配置
     */
    /**
     * 双向TLS配置
     */
    /**
     * 设置会话处理
     *
     * 注意：实际实现取决于使用的 QUIC 库的 API
     */
    /**
     * 设置流处理
     *
     * 注意：HTTP/3 中每个请求对应一个双向流
     */
    protected extractRelevantConfig(config: Http3ServerOptions): {
        hostname: string;
        port: number;
        protocol: string;
        sslMode: "auto" | "manual" | "mutual_tls";
        alpnProtocols: string[];
        connectionPool: {
            maxConnections: number;
            maxIdleTimeout: number;
        };
        quicSettings: {
            maxIdleTimeout?: number;
            maxUdpPayloadSize?: number;
            initialMaxData?: number;
            initialMaxStreamDataBidiLocal?: number;
            initialMaxStreamDataBidiRemote?: number;
            initialMaxStreamDataUni?: number;
            initialMaxStreamsBidi?: number;
            initialMaxStreamsUni?: number;
            ackDelayExponent?: number;
            maxAckDelay?: number;
            disableActiveMigration?: boolean;
        };
        http3Settings: {
            maxHeaderListSize?: number;
            maxFieldSectionSize?: number;
            qpackMaxTableCapacity?: number;
            qpackBlockedStreams?: number;
            settings?: {
                maxHeaderListSize?: number;
                qpackMaxTableCapacity?: number;
                qpackBlockedStreams?: number;
            };
        };
    };
    /**
     * 检查SSL配置是否变更
     */
    /**
     * 检查QUIC配置是否变更
     */
    /**
     * 检查HTTP/3配置是否变更
     */
    /**
     * 检查连接池配置是否变更
     */
    /**
     * 重写停止监控和清理方法
     */
    Start(listenCallback?: () => void): NativeServer;
    getStatus(): number;
    getNativeServer(): NativeServer;
    /**
     * 启动连接池监控
     */
    /**
     * 获取HTTP/3统计信息
     */
    getHttp3Stats(): {
        availableSessions: number;
        closingSessions: number;
        totalActiveStreams: number;
        totalStreams: number;
        totalStreamErrors: number;
        totalBytesSent: number;
        totalBytesReceived: number;
        totalPacketsLost: number;
        averageRtt: number;
        averageStreamsPerSession: number;
        utilizationRatio: number;
        packetLossRate: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 获取当前连接状态
     */
    getConnectionsStatus(): {
        current: number;
        max: number;
    };
    /**
     * 销毁服务器
     */
    destroy(): Promise<void>;
}

/**
 * HTTP/3 Server Options (QUIC-based)
 */
declare interface Http3ServerOptions extends BaseServerOptions {
    ssl?: SSL3Config;
    http3?: {
        maxHeaderListSize?: number;
        maxFieldSectionSize?: number;
        qpackMaxTableCapacity?: number;
        qpackBlockedStreams?: number;
        settings?: {
            maxHeaderListSize?: number;
            qpackMaxTableCapacity?: number;
            qpackBlockedStreams?: number;
        };
    };
    quic?: {
        maxIdleTimeout?: number;
        maxUdpPayloadSize?: number;
        initialMaxData?: number;
        initialMaxStreamDataBidiLocal?: number;
        initialMaxStreamDataBidiRemote?: number;
        initialMaxStreamDataUni?: number;
        initialMaxStreamsBidi?: number;
        initialMaxStreamsUni?: number;
        ackDelayExponent?: number;
        maxAckDelay?: number;
        disableActiveMigration?: boolean;
    };
    connectionPool?: ConnectionPoolConfig;
}

/**
 * HTTP/3 连接（Session）接口
 *
 * 注意：这是一个抽象接口，实际实现取决于使用的 QUIC 库
 * 例如：@node-rs/quic 的 Connection 对象
 */
declare interface Http3Session {
    destroyed: boolean;
    closed: boolean;
    localAddress?: string;
    localPort?: number;
    remoteAddress?: string;
    remotePort?: number;
    close(code?: number, reason?: string): void;
    ping?(callback: (err: Error | null, duration: number) => void): void;
    getStats?(): {
        bytesSent: number;
        bytesReceived: number;
        packetsLost: number;
        rtt: number;
    };
    on(event: 'close', listener: () => void): this;
    on(event: 'error', listener: (error: Error) => void): this;
    on(event: 'stream', listener: (stream: any) => void): this;
    on(event: string, listener: (...args: any[]) => void): this;
    once(event: 'close', listener: () => void): this;
    once(event: 'error', listener: (error: Error) => void): this;
    once(event: string, listener: (...args: any[]) => void): this;
}

/**
 * HTTP连接池管理器
 */
declare class HttpConnectionPoolManager extends ConnectionPoolManager<Socket> {
    constructor(config?: ConnectionPoolConfig);
    /**
     * 验证HTTP连接
     */
    /**
     * 清理HTTP连接
     */
    /**
     * 获取可用连接
     */
    protected getAvailableConnection(): Promise<{
        connection: Socket;
        id: string;
    } | null>;
    /**
     * 创建新连接
     */
    protected createNewConnection(_options: ConnectionRequestOptions): Promise<{
        connection: Socket;
        id: string;
        metadata?: any;
    } | null>;
    /**
     * 检查连接是否健康
     */
    isConnectionHealthy(connection: Socket): boolean;
    /**
     * 添加HTTP连接（由服务器调用）
     */
    addHttpConnection(connection: Socket): Promise<boolean>;
    /**
     * 处理HTTP请求完成
     */
    handleRequestComplete(connection: Socket, bytesSent?: number): Promise<void>;
    /**
     * 获取连接统计信息
     */
    getConnectionStats(): {
        availableConnections: number;
        totalRequests: number;
        totalBytesSent: number;
        totalBytesReceived: number;
        httpsConnections: number;
        httpConnections: number;
        averageRequestsPerConnection: number;
        utilizationRatio: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 设置Keep-Alive超时
     */
    setKeepAliveTimeout(timeout: number): void;
    /**
     * 获取连接详细信息
     */
    getConnectionDetails(): Array<{
        id: string;
        remoteAddress: string;
        protocol: string;
        requestCount: number;
        bytesSent: number;
        bytesReceived: number;
        age: number;
        idle: number;
    }>;
    /**
     * 销毁连接池
     */
    destroy(): Promise<void>;
    /**
     * 协议特定的连接处理器设置
     */
    /**
     * 协议特定的连接创建逻辑
     */
    protected createProtocolConnection(_options: ConnectionRequestOptions): Promise<{
        connection: Socket;
        metadata?: any;
    } | null>;
}

/**
 * HTTPS连接池管理器
 */
declare class HttpsConnectionPoolManager extends ConnectionPoolManager<TLSSocket> {
    constructor(config?: ConnectionPoolConfig);
    /**
     * 验证HTTPS连接
     */
    /**
     * 清理HTTPS连接
     */
    /**
     * 获取可用连接
     */
    protected getAvailableConnection(): Promise<{
        connection: TLSSocket;
        id: string;
    } | null>;
    /**
     * 创建新连接
     */
    protected createNewConnection(_options: ConnectionRequestOptions): Promise<{
        connection: TLSSocket;
        id: string;
        metadata?: any;
    } | null>;
    /**
     * 检查连接是否健康
     */
    isConnectionHealthy(connection: TLSSocket): boolean;
    /**
     * 添加HTTPS连接（由服务器调用）
     */
    addHttpsConnection(connection: TLSSocket): Promise<boolean>;
    /**
     * 计算连接安全评分
     */
    /**
     * 更新安全指标
     */
    /**
     * 设置连接事件处理器
     */
    /**
     * 处理HTTPS请求完成
     */
    handleRequestComplete(connection: TLSSocket, bytesSent?: number): Promise<void>;
    /**
     * 启动安全监控
     */
    /**
     * 获取连接统计信息
     */
    getConnectionStats(): {
        security: {
            totalHandshakes: number;
            successfulHandshakes: number;
            failedHandshakes: number;
            averageHandshakeTime: number;
        };
        total: number;
        active: number;
        available: number;
        authorized: number;
        unauthorized: number;
        totalRequests: number;
        totalBytesSent: number;
        totalBytesReceived: number;
        averageSecurityScore: number;
        protocols: Record<string, number>;
        ciphers: Record<string, number>;
    };
    /**
     * 获取安全指标
     */
    getSecurityMetrics(): {
        connectionSecurityScores: {
            id: any;
            securityScore: any;
            authorized: any;
            cipher: any;
            protocol: any;
        }[];
        totalHandshakes: number;
        successfulHandshakes: number;
        failedHandshakes: number;
        averageHandshakeTime: number;
    };
    /**
     * 设置Keep-Alive超时
     */
    setKeepAliveTimeout(timeout: number): void;
    /**
     * 获取连接详情
     */
    getConnectionDetails(): Array<{
        id: string;
        remoteAddress: string;
        protocol: string;
        cipher: string;
        authorized: boolean;
        securityScore: number;
        requestCount: number;
        bytesSent: number;
        bytesReceived: number;
        age: number;
        idle: number;
    }>;
    /**
     * 查找HTTPS连接ID
     */
    /**
     * 销毁连接池
     */
    destroy(): Promise<void>;
    /**
     * 设置协议特定的连接处理器
     */
    /**
     * 协议特定的连接创建逻辑
     */
    protected createProtocolConnection(_options: ConnectionRequestOptions): Promise<{
        connection: TLSSocket;
        metadata?: any;
    } | null>;
}

/**
 * HTTP Server implementation using template method pattern
 * 继承BaseServer，只实现HTTP特定的逻辑
 */
export declare class HttpServer extends BaseServer<HttpServerOptions, Server_2> {
    constructor(app: KoattyApplication, options: HttpServerOptions);
    /**
     * 初始化HTTP连接池
     */
    /**
     * 创建HTTP服务器实例
     */
    /**
     * 配置HTTP服务器选项
     */
    /**
     * HTTP特定的额外初始化
     */
    /**
     * 配置连接池设置
     */
    /**
     * 设置连接跟踪
     */
    protected extractRelevantConfig(config: HttpServerOptions): {
        hostname: string;
        port: number;
        protocol: string;
        connectionPool: {
            maxConnections: number;
            keepAliveTimeout: number;
            headersTimeout: number;
            requestTimeout: number;
        };
    };
    /**
     * 检查连接池配置是否变更
     */
    Start(listenCallback?: () => void): NativeServer;
    getStatus(): number;
    getNativeServer(): NativeServer;
    /**
     * 启动连接池监控
     */
    /**
     * 获取HTTP连接统计信息
     */
    getHttpConnectionStats(): {
        availableConnections: number;
        totalRequests: number;
        totalBytesSent: number;
        totalBytesReceived: number;
        httpsConnections: number;
        httpConnections: number;
        averageRequestsPerConnection: number;
        utilizationRatio: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 销毁服务器
     */
    destroy(): Promise<void>;
}

/**
 * HTTP Server Options extending base options
 */
declare interface HttpServerOptions extends BaseServerOptions {
    connectionPool?: ConnectionPoolConfig;
}

/**
 * HTTPS Server implementation using template method pattern
 * 继承BaseServer，只实现HTTPS特定的逻辑
 */
export declare class HttpsServer extends BaseServer<HttpsServerOptions, Server_3> {
    constructor(app: KoattyApplication, options: HttpsServerOptions);
    /**
     * 初始化HTTPS连接池
     */
    /**
     * 创建HTTPS服务器实例
     */
    /**
     * 配置HTTPS服务器选项
     */
    /**
     * HTTPS特定的额外初始化
     */
    /**
     * 创建SSL选项
     */
    /**
     * 自动SSL配置
     */
    /**
     * 手动SSL配置
     */
    /**
     * 双向TLS配置
     */
    /**
     * 设置连接处理
     */
    /**
     * 记录请求 TODO
     */
    protected extractRelevantConfig(config: HttpsServerOptions): {
        hostname: string;
        port: number;
        protocol: string;
        sslMode: "auto" | "manual" | "mutual_tls";
        connectionPool: {
            maxConnections: number;
            keepAliveTimeout: number;
            headersTimeout: number;
            requestTimeout: number;
        };
    };
    /**
     * 检查SSL配置是否变更
     */
    /**
     * 检查连接池配置是否变更
     */
    Start(listenCallback?: () => void): NativeServer;
    getStatus(): number;
    getNativeServer(): NativeServer;
    /**
     * 启动连接池监控
     */
    /**
     * 获取安全统计信息
     */
    getSecurityMetrics(): {
        sslMode: "auto" | "manual" | "mutual_tls";
        ciphers: string;
        secureProtocol: string;
        mutualTLS: boolean;
    };
    /**
     * 获取当前连接状态
     */
    getConnectionsStatus(): {
        current: number;
        max: number;
    };
    /**
     * 销毁服务器
     */
    destroy(): Promise<void>;
}

/**
 * Enhanced HTTPS Server Options
 */
declare interface HttpsServerOptions extends BaseServerOptions {
    ssl?: SSL1Config;
    connectionPool?: ConnectionPoolConfig;
}

/**
 * Implementation
 *
 * @interface Implementation
 */
declare interface Implementation {
    [methodName: string]: UntypedHandleCall;
}

export declare type KoattyProtocol = 'http' | "https" | 'http2' | 'http3' | 'grpc' | 'ws' | 'wss';

/**
 * listening options
 *
 * @interface ListeningOptions
 */
export declare interface ListeningOptions {
    hostname: string;
    port: number;
    protocol: string;
    trace?: boolean;
    ssl?: {
        [key: string]: unknown;
    } & BaseSSLConfig;
    ext?: {
        protoFile?: string;
        schemaFile?: string;
        [key: string]: unknown;
    };
    connectionPool?: ConnectionPoolConfig;
    [key: string]: unknown;
}

/**
 * Log context interface
 */
declare interface LogContext {
    module?: string;
    protocol?: string;
    serverId?: string;
    connectionId?: string;
    requestId?: string;
    userId?: string;
    sessionId?: string;
    traceId?: string;
    action?: string;
    [key: string]: unknown;
}

/**
 * Create Server
 *
 * @export
 * @param {KoattyApplication} app
 * @param {ListeningOptions} [opt]
 * @returns {*}  {KoattyServer}
 */
export declare function NewServe(app: KoattyApplication, opt?: ListeningOptions): KoattyServer;

/**
 * Performance metrics interface
 */
declare interface PerformanceMetrics {
    startTime: number;
    endTime?: number;
    duration?: number;
    memoryUsage?: NodeJS.MemoryUsage;
    [key: string]: unknown;
}

export declare interface RateLimitOptions {
    enabled?: boolean;
    windowMs?: number;
    max?: number;
    keyGenerator?: (req: IncomingMessage) => string;
    message?: string;
    skipSuccessfulRequests?: boolean;
}

export declare interface ReadinessResponse {
    status: 'ready' | 'not_ready';
    checks?: Record<string, boolean>;
    timestamp: string;
}

/**
 * Register connection pool metrics callback with Application instance
 *
 * @param {KoattyApplication} app - Application instance
 * @returns {void}
 */
export declare function registerConnectionPoolMetrics(app: KoattyApplication): void;

/**
 * Ring Buffer (Circular Buffer)
 * 环形缓冲区 - 固定大小的循环队列，覆盖最旧的数据
 *
 * Features:
 * - O(1) write operations (no array shifts or slices)
 * - O(1) amortized read operations
 * - Fixed memory footprint
 * - Automatic overwrite of oldest data when full
 */
export declare class RingBuffer<T = number> {
    /**
     * Create a ring buffer with fixed capacity
     * @param capacity Maximum number of items to store
     */
    constructor(capacity: number);
    /**
     * Add an item to the buffer
     * If buffer is full, overwrites the oldest item
     * @param item Item to add
     */
    push(item: T): void;
    /**
     * Get all items in insertion order (oldest to newest)
     * @returns Array of items
     */
    toArray(): T[];
    /**
     * Get a sorted copy of the buffer contents
     * @param compareFn Optional comparison function
     * @returns Sorted array
     */
    toSortedArray(compareFn?: (a: T, b: T) => number): T[];
    /**
     * Clear all items from the buffer
     */
    clear(): void;
    /**
     * Get the number of items currently in the buffer
     * @returns Current item count
     */
    get length(): number;
    /**
     * Get the maximum capacity of the buffer
     * @returns Buffer capacity
     */
    get size(): number;
    /**
     * Check if buffer is empty
     * @returns True if empty
     */
    isEmpty(): boolean;
    /**
     * Check if buffer is full
     * @returns True if full
     */
    isFull(): boolean;
    /**
     * Get an item at a specific index (0 = oldest, length-1 = newest)
     * @param index Index to retrieve
     * @returns Item at index or undefined if out of range
     */
    get(index: number): T | undefined;
    /**
     * Get the oldest item without removing it
     * @returns Oldest item or undefined if buffer is empty
     */
    peek(): T | undefined;
    /**
     * Get the newest item
     * @returns Newest item or undefined if buffer is empty
     */
    peekLast(): T | undefined;
    /**
     * Calculate percentile from buffer contents (e.g., 0.5 for median, 0.95 for P95)
     * @param percentile Percentile value between 0 and 1
     * @returns Percentile value or undefined if buffer is empty
     */
    getPercentile(percentile: number): T | undefined;
    /**
     * Get average of numeric buffer contents
     * @returns Average value or undefined if buffer is empty
     */
    getAverage(): number | undefined;
    /**
     * Iterate over buffer contents (oldest to newest)
     * @param callback Function to call for each item
     */
    forEach(callback: (item: T, index: number) => void): void;
    /**
     * Map buffer contents to a new array
     * @param callback Function to transform each item
     * @returns New array of transformed items
     */
    map<U>(callback: (item: T, index: number) => U): U[];
    /**
     * Filter buffer contents
     * @param predicate Function to test each item
     * @returns New array of items that pass the test
     */
    filter(predicate: (item: T, index: number) => boolean): T[];
    /**
     * Reduce buffer contents to a single value
     * @param callback Reducer function
     * @param initialValue Initial value for the accumulator
     * @returns Reduced value
     */
    reduce<U>(callback: (accumulator: U, item: T, index: number) => U, initialValue: U): U;
}

/**
 * Serve Component
 * Responsible for initializing and managing server
 *
 * Implements IComponent interface (base interface)
 *
 * Event bindings:
 * - loadServe: Initialize server
 * - appStop: Gracefully shutdown server
 */
export declare class ServeComponent implements IComponent {
    events?: Record<string, string[]>;
    /**
     * Initialize server
     */
    initServer(app: KoattyApplication): Promise<void>;
    /**
     * Gracefully shutdown server on app stop
     *
     * Note: Original appStop event handling triggered by terminus
     * is now unified to be handled by @OnEvent(AppEvent.appStop) decorator
     */
    stopServer(app: KoattyApplication): Promise<void>;
}

/**
 * ServiceImplementation
 *
 * @interface ServiceImplementation
 */
declare interface ServiceImplementation {
    service: ServiceDefinition;
    implementation: Implementation;
}

declare interface ShutdownResult {
    status: 'completed' | 'failed' | 'forced';
    totalTime: number;
    completedSteps: string[];
    failedSteps: Array<{
        step: string;
        error: string;
        timestamp: number;
    }>;
}

/**
 * Single protocol server
 */
export declare class SingleProtocolServer implements KoattyServer {
    server: NativeServer | null;
    readonly protocol: string;
    readonly options: ListeningOptions;
    status: number;
    listenCallback?: () => void;
    constructor(app: KoattyApplication, opt: ListeningOptions);
    /**
     * Initialize server instance without starting it
     * This allows RegisterService to be called before Start()
     */
    /**
     * Start server
     */
    Start(listenCallback?: () => void): any;
    /**
     * Stop server
     */
    Stop(callback?: () => void): void;
    /**
     * Register Service for gRPC server
     */
    RegisterService(impl: (...args: any[]) => any): any;
    /**
     * Get server status
     * @returns
     */
    getStatus(): number;
    /**
     * Get native server
     * @returns
     */
    getNativeServer(): NativeServer;
    /**
     * Get server health status
     * @returns Health status information
     */
    getHealthStatus(): {
        status: 'healthy' | 'degraded' | 'unhealthy';
        checks: {
            server: {
                status: string;
                uptime: number;
                protocol: string;
                port: number;
            };
            connectionPool?: {
                status: string;
                activeConnections: number;
                maxConnections: number;
                utilizationRate: number;
            };
        };
        timestamp: number;
    };
    /**
     * Get server metrics in Prometheus format
     * @returns Prometheus-formatted metrics
     */
    getMetrics(): string;
    /**
     * Create health check middleware for Express/Koa
     * @returns Middleware function
     */
    healthCheckMiddleware(): (ctx: any, next: () => Promise<void>) => Promise<void>;
    /**
     * Create server instance based on protocol
     */
}

/**
 * HTTPS使用的高级SSL配置
 */
declare interface SSL1Config extends BaseSSLConfig {
    mode: 'auto' | 'manual' | 'mutual_tls';
    requestCert?: boolean;
    rejectUnauthorized?: boolean;
    handshakeTimeout?: number;
    sessionTimeout?: number;
    SNICallback?: (servername: string, cb: (err: Error | null, ctx?: any) => void) => void;
    sessionIdContext?: string;
    ticketKeys?: Buffer;
    ALPNProtocols?: string[];
    [key: string]: unknown;
}

/**
 * HTTP/2使用的SSL配置（支持HTTP/1.1降级）
 */
declare interface SSL2Config extends SSL1Config {
    allowHTTP1?: boolean;
    [key: string]: unknown;
}

/**
 * HTTP/3使用的SSL配置（基于QUIC，必须使用TLS 1.3）
 */
declare interface SSL3Config extends BaseSSLConfig {
    mode: 'auto' | 'manual' | 'mutual_tls';
    requestCert?: boolean;
    rejectUnauthorized?: boolean;
    alpnProtocols?: string[];
    maxIdleTimeout?: number;
    initialMaxStreamsBidi?: number;
    initialMaxStreamsUni?: number;
    [key: string]: unknown;
}

/**
 * gRPC和WebSocket使用的简单SSL配置
 */
declare interface SSLConfig extends BaseSSLConfig {
    clientCertRequired?: boolean;
    [key: string]: unknown;
}

/**
 * Structured logger class based on koatty_logger
 * koatty_logger 2.4.0+ 已内置批量日志处理、采样、级别过滤等优化功能
 */
declare class StructuredLogger {
    static getInstance(): StructuredLogger;
    /**
     * Set global context for all logs
     * @param context Global context to merge with all log entries
     */
    setGlobalContext(context: LogContext): void;
    /**
     * Get current global context
     */
    getGlobalContext(): LogContext;
    /**
     * Clear global context
     */
    clearGlobalContext(): void;
    /**
     * Format log message with context
     * @param message Log message
     * @param context Additional context
     * @param data Additional data to log
     * @returns Formatted message string
     */
    /**
     * Log debug message
     * @param message Log message
     * @param context Additional context
     * @param data Additional data
     */
    debug(message: string, context?: LogContext, data?: unknown): void;
    /**
     * Log info message
     * @param message Log message
     * @param context Additional context
     * @param data Additional data
     */
    info(message: string, context?: LogContext, data?: unknown): void;
    /**
     * Log warning message
     * @param message Log message
     * @param context Additional context
     * @param data Additional data
     */
    warn(message: string, context?: LogContext, data?: unknown): void;
    /**
     * Log error message
     * @param message Log message
     * @param context Additional context
     * @param error Error object or additional data
     */
    error(message: string, context?: LogContext, error?: Error | unknown): void;
    /**
     * Create a child logger with merged context
     * @param context Context to merge
     * @returns New logger instance with merged context
     */
    child(context: LogContext): StructuredLogger;
    /**
     * Start performance measurement
     * @param label Performance measurement label
     * @returns Performance metrics object
     */
    startPerformanceMeasurement(label: string): PerformanceMetrics;
    /**
     * End performance measurement and log result
     * @param metrics Performance metrics from startPerformanceMeasurement
     * @param context Additional context
     */
    endPerformanceMeasurement(metrics: PerformanceMetrics, context?: LogContext): void;
    /**
     * Measure and log performance of async operation
     * @param label Performance measurement label
     * @param operation Async operation to measure
     * @param context Additional context
     * @returns Result of the operation
     */
    measureAsync<T>(label: string, operation: () => Promise<T>, context?: LogContext): Promise<T>;
    /**
     * Measure and log performance of sync operation
     * @param label Performance measurement label
     * @param operation Sync operation to measure
     * @param context Additional context
     * @returns Result of the operation
     */
    measureSync<T>(label: string, operation: () => T, context?: LogContext): T;
}

/**
 * 定时器信息接口
 */
declare interface TimerInfo {
    id: string;
    name: string;
    interval: number;
    callback: () => void;
    timer: NodeJS.Timeout;
    createdAt: number;
    lastExecuted?: number;
    priority?: 'high' | 'medium' | 'low';
    protocol?: string;
}

/**
 * 统一定时器管理器
 * 解决定时器资源泄漏和难以追踪的问题
 * Phase 3: 添加定时器优化功能
 */
declare class TimerManager {
    constructor(config?: Partial<TimerOptimizerConfig>);
    /**
     * 添加定时器 (传统方式)
     * @param name 定时器名称
     * @param callback 回调函数
     * @param interval 间隔时间(毫秒)
     * @returns 定时器ID
     */
    /**
     * 添加定时器 - 统一使用优化模式
     * @param name 定时器名称
     * @param callback 回调函数
     * @param interval 间隔时间(毫秒)
     * @returns 定时器ID
     */
    addTimer(name: string, callback: () => void, interval: number): string;
    /**
     * 添加优化定时器 - Phase 3
     * @param task 定时器任务
     * @returns 任务ID
     */
    addOptimizedTimer(task: Omit<TimerTask, 'id' | 'lastExecuted' | 'executionCount'>): string;
    /**
     * 创建物理定时器 - 用于合并定时器的底层实现
     */
    /**
     * 清理指定定时器 - 支持逻辑定时器清理
     * @param timerIdOrName 定时器ID或名称
     * @returns 是否成功清理
     */
    clearTimer(timerIdOrName: string): boolean;
    /**
     * 清理所有定时器 - 支持逻辑和物理定时器清理
     */
    clearAllTimers(): void;
    /**
     * 获取活跃定时器数量 - 返回逻辑定时器数量
     */
    getActiveTimerCount(): number;
    /**
     * 获取所有定时器名称 - 返回逻辑定时器名称
     */
    getTimerNames(): string[];
    /**
     * 获取定时器详细信息
     */
    getTimerInfo(timerId: string): TimerInfo | undefined;
    /**
     * 获取所有定时器统计信息 - 返回逻辑定时器统计
     */
    getTimerStats(): {
        totalTimers: number;
        timers: Array<{
            id: string;
            name: string;
            interval: number;
            uptime: number;
            lastExecuted?: number;
            priority: string;
            executionCount: number;
        }>;
    };
    /**
     * 检查是否存在指定定时器 - 支持逻辑和物理定时器
     */
    hasTimer(timerId: string): boolean;
    /**
     * 确定定时器优先级 - Phase 3 优化
     */
    /**
     * 从定时器名称提取协议 - Phase 3 优化
     */
    /**
     * 选择最佳频率 - Phase 3 优化
     */
    /**
     * 优化定时器 - Phase 3 核心优化逻辑
     */
    /**
     * 创建合并定时器 - Phase 3 优化
     */
    /**
     * 执行任务批次 - Phase 3 优化
     */
    /**
     * 判断是否应该执行任务（自适应频率）- Phase 3 优化
     */
    /**
     * 更新平均执行时间 - Phase 3 优化
     */
    /**
     * 清理合并定时器 - Phase 3 优化
     */
    /**
     * 获取优化统计信息 - Phase 3 优化
     */
    getOptimizationStats(): {
        performance: {
            totalTasks: number;
            executedTasks: number;
            averageExecutionTime: number;
            lastOptimization: number;
        };
        consolidation: {
            activeTimers: number;
            totalTasks: number;
            tasksByFrequency: {
                [k: string]: number;
            };
            tasksByPriority: {
                high: number;
                medium: number;
                low: number;
            };
        };
        config: TimerOptimizerConfig;
    };
    /**
     * 演示Phase 3优化功能 - 创建优化版本的TimerManager实例
     */
    static createOptimizedInstance(): TimerManager;
    /**
     * 演示定时器优化效果
     */
    demonstrateOptimization(): {
        before: {
            timerCount: number;
            intervals: number[];
        };
        after: {
            consolidatedTimers: number;
            frequencies: number[];
            estimatedReduction: string;
        };
    };
    /**
     * 安全销毁管理器
     */
    destroy(): void;
}

/**
 * 定时器优化配置
 */
declare interface TimerOptimizerConfig {
    enableConsolidation: boolean;
    enableAdaptiveFrequency: boolean;
    maxTimersPerFrequency: number;
    loadThreshold: number;
}

/**
 * 定时器任务接口 - Phase 3 优化
 */
declare interface TimerTask {
    id: string;
    name: string;
    callback: () => void;
    interval: number;
    priority: 'high' | 'medium' | 'low';
    protocol?: string;
    lastExecuted?: number;
    executionCount?: number;
}

/**
 * Unregister connection pool metrics callback from Application instance
 *
 * @param {KoattyApplication} app - Application instance
 * @returns {void}
 */
export declare function unregisterConnectionPoolMetrics(app: KoattyApplication): void;

/**
 * WebSocket连接池管理器
 */
declare class WebSocketConnectionPoolManager extends ConnectionPoolManager<WS.WebSocket> {
    constructor(config?: ConnectionPoolConfig);
    /**
     * 验证WebSocket连接
     */
    /**
     * 清理WebSocket连接
     */
    /**
     * 获取可用连接
     */
    protected getAvailableConnection(): Promise<{
        connection: WS.WebSocket;
        id: string;
    } | null>;
    /**
     * 创建新连接 - 支持主动创建WebSocket连接（用于客户端模式或测试）
     */
    protected createNewConnection(options: ConnectionRequestOptions): Promise<{
        connection: WS.WebSocket;
        id: string;
        metadata?: any;
    } | null>;
    /**
     * 检查连接是否健康
     */
    isConnectionHealthy(connection: WS.WebSocket): boolean;
    /**
     * 协议特定的连接处理器设置
     */
    /**
     * 协议特定的连接创建逻辑
     */
    protected createProtocolConnection(_options: ConnectionRequestOptions): Promise<{
        connection: WS.WebSocket;
        metadata?: any;
    } | null>;
    /**
     * 添加WebSocket连接（对外接口，使用统一的registerConnection）
     */
    addWebSocketConnection(connection: WS.WebSocket, request?: IncomingMessage): Promise<boolean>;
    /**
     * 启动心跳监控
     */
    /**
     * 向所有连接发送ping
     */
    /**
     * 清理死连接
     */
    /**
     * 清理过期连接
     */
    cleanupStaleConnections(): number;
    /**
     * 获取连接统计信息
     */
    getConnectionStats(): {
        availableConnections: number;
        healthyConnections: number;
        utilizationRatio: number;
        protocol: string;
        poolConfig: ConnectionPoolConfig;
        health: ConnectionPoolHealth;
        performance: {
            throughput: number;
            latency: {
                p50: number;
                p95: number;
                p99: number;
            };
            memoryUsage: number;
            cpuUsage: number;
        };
        uptime: number;
        activeConnections: number;
        totalConnections: number;
        connectionsPerSecond: number;
        averageLatency: number;
        errorRate: number;
    };
    /**
     * 找到连接ID的辅助方法
     */
    /**
     * 销毁连接池
     */
    /**
     * 重写添加连接方法，确保WebSocket连接正确设置
     */
    addConnection(connection: WS.WebSocket, metadata?: any): Promise<boolean>;
    destroy(): Promise<void>;
}

/**
 * WebSocket Server Options extending base options
 */
declare interface WebSocketServerOptions extends BaseServerOptions {
    wsOptions?: WS.ServerOptions;
    ssl?: SSLConfig;
    connectionPool?: ConnectionPoolConfig;
}

/**
 * WebSocket Server implementation using template method pattern
 * 继承BaseServer，只实现WebSocket特定的逻辑
 */
export declare class WsServer extends BaseServer<WebSocketServerOptions, WS.WebSocketServer> {
    readonly httpServer: Server_2 | Server_3;
    socket: any;
    constructor(app: KoattyApplication, options: WebSocketServerOptions);
    /**
     * 初始化WebSocket连接池
     */
    /**
     * 创建WebSocket服务器实例
     */
    /**
     * 配置WebSocket服务器选项
     */
    /**
     * WebSocket特定的额外初始化
     */
    /**
     * 创建HTTP/HTTPS服务器
     */
    /**
     * 设置WebSocket升级处理
     */
    /**
     * 确保升级处理器已绑定到HTTP服务器
     */
    /**
     * 设置WebSocket连接处理
     */
    /**
     * 处理新的WebSocket连接
     */
    /**
     * 设置WebSocket事件处理器
     */
    protected extractRelevantConfig(config: WebSocketServerOptions): {
        hostname: string;
        port: number;
        protocol: string;
        isSecure: boolean;
        connectionPool: {
            maxConnections: number | undefined;
            pingInterval: number | undefined;
            pongTimeout: number | undefined;
            heartbeatInterval: number | undefined;
        } | null;
        wsOptions: WS.ServerOptions | undefined;
    };
    /**
     * 检查SSL配置是否变更
     */
    /**
     * 检查连接池配置是否变更
     */
    Start(listenCallback?: () => void): NativeServer;
    getStatus(): number;
    getNativeServer(): NativeServer;
    /**
     * 启动连接池监控
     */
    /**
     * 获取WebSocket连接统计信息
     */
    getWebSocketConnectionStats(): {
        current: number;
        max: number;
    };
    /**
     * 获取当前连接状态
     */
    getConnectionsStatus(): {
        current: number;
        max: number;
    };
    /**
     * 销毁服务器
     */
    destroy(): Promise<void>;
}

export { }
