Skip to content

Koatty/koatty_serve

Repository files navigation

koatty_serve

高性能多协议服务器框架,为Koatty提供统一的HTTP、HTTPS、HTTP/2、WebSocket、gRPC服务支持。采用现代化架构设计,具备企业级的配置管理、连接池、优雅关闭、健康检查和性能监控功能。

🚀 核心特性

🏗️ 统一架构设计

  • 模板方法模式: 基于BaseServer的统一服务器架构
  • 多协议支持: HTTP、HTTPS、HTTP/2、WebSocket、WSS、gRPC
  • 配置统一管理: ConfigHelper提供一致的配置接口
  • 连接池系统: 高性能的协议专用连接池管理

🔧 企业级配置管理

  • 🔄 统一配置接口: 所有协议使用相同的配置模式
  • 🔥 配置热重载: 智能检测配置变更,自动决定重启策略
  • 📋 类型安全: 完整的TypeScript类型定义和验证
  • 🎛️ 默认值管理: 智能的默认配置和环境适配

🏊‍♂️ 高性能连接池

  • 协议专用池: 每种协议优化的连接池实现
  • 📊 智能监控: 实时连接统计和健康检查
  • 🔄 自动清理: 过期连接自动清理和资源回收
  • 🎯 负载均衡: 智能连接分配和负载管理

🛡️ 企业级运维

  • 🔄 优雅关闭: 五步式优雅关闭流程
  • 🏥 健康检查: 多层次健康状态监控
  • 📊 性能监控: 实时指标收集和历史数据
  • 📝 结构化日志: 统一的日志系统和链路追踪

📦 安装

npm install koatty_serve
# 或者
yarn add koatty_serve
# 或者
pnpm add koatty_serve

🎯 快速开始

基础HTTP服务器

import { HttpServer } from "koatty_serve";
import { ConfigHelper } from "koatty_serve/config";

const app = new KoattyApplication();

// 使用ConfigHelper创建配置
const config = ConfigHelper.createHttpConfig({
  hostname: '127.0.0.1',
  port: 3000,
  connectionPool: {
    maxConnections: 1000,
    connectionTimeout: 30000
  }
});

// 创建HTTP服务器
const server = new HttpServer(app, config);

server.Start(() => {
  console.log('HTTP服务器已启动: http://127.0.0.1:3000');
});

HTTPS服务器

import { HttpsServer } from "koatty_serve";
import { ConfigHelper } from "koatty_serve/config";

const httpsConfig = ConfigHelper.createHttpsConfig({
  hostname: '0.0.0.0',
  port: 443,
  ssl: {
    mode: 'auto',
    key: './ssl/server.key',
    cert: './ssl/server.crt'
  },
  connectionPool: {
    maxConnections: 2000,
    keepAliveTimeout: 65000
  }
});

const httpsServer = new HttpsServer(app, httpsConfig);
httpsServer.Start(() => {
  console.log('HTTPS服务器已启动: https://0.0.0.0:443');
});

gRPC服务器

import { GrpcServer } from "koatty_serve";
import { ConfigHelper } from "koatty_serve/config";

const grpcConfig = ConfigHelper.createGrpcConfig({
  hostname: '127.0.0.1',
  port: 50051,
  ssl: {
    enabled: true,
    keyFile: './certs/server.key',
    certFile: './certs/server.crt',
    clientCertRequired: false
  },
  connectionPool: {
    maxConnections: 500,
    protocolSpecific: {
      keepAliveTime: 30000,
      maxReceiveMessageLength: 4 * 1024 * 1024,
      maxSendMessageLength: 4 * 1024 * 1024
    }
  }
});

const grpcServer = new GrpcServer(app, grpcConfig);
grpcServer.Start(() => {
  console.log('gRPC服务器已启动: 127.0.0.1:50051');
});

WebSocket服务器

import { WsServer } from "koatty_serve";
import { ConfigHelper } from "koatty_serve/config";

const wsConfig = ConfigHelper.createWebSocketConfig({
  hostname: '127.0.0.1',
  port: 8080,
  ssl: {
    enabled: false
  },
  connectionPool: {
    maxConnections: 5000,
    connectionTimeout: 60000,
    protocolSpecific: {
      pingInterval: 30000,
      pongTimeout: 5000,
      heartbeatInterval: 60000
    }
  }
});

const wsServer = new WsServer(app, wsConfig);
wsServer.Start(() => {
  console.log('WebSocket服务器已启动: ws://127.0.0.1:8080');
});

🏗️ 架构设计

BaseServer模板方法模式

所有协议服务器都继承自BaseServer抽象类,实现统一的生命周期管理:

abstract class BaseServer<T extends BaseServerOptions> {
  // 模板方法:定义服务器初始化流程
  protected initializeServer(): void {
    this.initializeConnectionPool();
    this.createProtocolServer();
    this.configureServerOptions();
    this.performProtocolSpecificInitialization();
  }
  
  // 模板方法:定义配置更新流程
  async updateConfig(newConfig: Partial<T>): Promise<void> {
    const analysis = this.analyzeConfigChanges(changedKeys, oldConfig, newConfig);
    if (analysis.requiresRestart) {
      await this.gracefulRestart(newConfig);
    } else {
      this.applyConfigChanges(changedKeys, newConfig);
    }
  }
  
  // 模板方法:定义优雅关闭流程
  async gracefulShutdown(options?: ShutdownOptions): Promise<void> {
    // 五步式关闭流程
    await this.stopAcceptingNewConnections(traceId);
    await this.waitDrainDelay(options.drainDelay, traceId);
    await this.waitForConnectionCompletion(timeout, traceId);
    await this.forceCloseRemainingConnections(traceId);
    this.stopMonitoringAndCleanup(traceId);
  }
  
  // 抽象方法:子类必须实现
  protected abstract initializeConnectionPool(): void;
  protected abstract createProtocolServer(): void;
  protected abstract configureServerOptions(): void;
}

统一配置管理

ConfigHelper提供了统一的配置创建接口:

export class ConfigHelper {
  // HTTP配置
  static createHttpConfig(options: HttpConfigOptions): HttpServerOptions;
  
  // HTTPS配置  
  static createHttpsConfig(options: HttpsConfigOptions): HttpsServerOptions;
  
  // HTTP/2配置
  static createHttp2Config(options: Http2ConfigOptions): Http2ServerOptions;
  
  // gRPC配置
  static createGrpcConfig(options: GrpcConfigOptions): GrpcServerOptions;
  
  // WebSocket配置
  static createWebSocketConfig(options: WebSocketConfigOptions): WebSocketServerOptions;
}

连接池架构

每种协议都有专门优化的连接池管理器:

// HTTP连接池
class HttpConnectionPoolManager extends ConnectionPoolManager<Socket> {
  // HTTP特定的连接管理
}

// gRPC连接池  
class GrpcConnectionPoolManager extends ConnectionPoolManager<GrpcConnection> {
  // gRPC特定的连接管理
  async addGrpcConnection(peer: string, metadata: any): Promise<boolean>;
}

// WebSocket连接池
class WebSocketConnectionPoolManager extends ConnectionPoolManager<WebSocket> {
  // WebSocket特定的连接管理
  async addWebSocketConnection(ws: WebSocket, request: IncomingMessage): Promise<boolean>;
}

🔧 配置管理

配置类型系统

// 基础服务器选项
interface BaseServerOptions {
  hostname: string;
  port: number;
  protocol: KoattyProtocol;
  trace?: boolean;
  ext?: Record<string, any>;
  connectionPool?: ConnectionPoolConfig;
}

// SSL配置层次
interface BaseSSLConfig {
  key?: string;
  cert?: string;
  ca?: string;
  passphrase?: string;
  ciphers?: string;
  honorCipherOrder?: boolean;
  secureProtocol?: string;
}

interface SSLConfig extends BaseSSLConfig {
  enabled: boolean;
  keyFile?: string;
  certFile?: string;
  caFile?: string;
  clientCertRequired?: boolean;
}

interface SSL1Config extends BaseSSLConfig {
  mode: 'auto' | 'manual' | 'mutual_tls';
  requestCert?: boolean;
  rejectUnauthorized?: boolean;
}

配置热重载

// 智能配置更新
const result = await server.updateConfig({
  connectionPool: {
    maxConnections: 2000,      // 运行时更新
    connectionTimeout: 60000   // 运行时更新
  }
});

// 关键配置变更(自动重启)
await server.updateConfig({
  hostname: '0.0.0.0',  // 触发优雅重启
  port: 8080,           // 触发优雅重启
  ssl: {                // 触发优雅重启
    mode: 'mutual_tls'
  }
});

🏊‍♂️ 连接池管理

统一连接池配置

interface ConnectionPoolConfig {
  maxConnections?: number;        // 最大连接数
  connectionTimeout?: number;     // 连接超时
  keepAliveTimeout?: number;      // Keep-Alive超时
  requestTimeout?: number;        // 请求超时
  headersTimeout?: number;        // 头部超时
  
  // 协议特定配置
  protocolSpecific?: {
    // HTTP/2特定
    maxSessionMemory?: number;
    maxHeaderListSize?: number;
    
    // gRPC特定
    keepAliveTime?: number;
    maxReceiveMessageLength?: number;
    maxSendMessageLength?: number;
    
    // WebSocket特定
    pingInterval?: number;
    pongTimeout?: number;
    heartbeatInterval?: number;
  };
}

连接池监控

// 获取连接池统计
const stats = server.connectionPool.getMetrics();
console.log('连接池统计:', {
  activeConnections: stats.activeConnections,
  totalConnections: stats.totalConnections,
  connectionsPerSecond: stats.connectionsPerSecond,
  averageLatency: stats.averageLatency,
  errorRate: stats.errorRate
});

// 获取连接池健康状态
const health = server.connectionPool.getHealth();
console.log('连接池健康:', health.status); // 'healthy' | 'degraded' | 'overloaded'

🛡️ 优雅关闭

五步式关闭流程

interface ShutdownOptions {
  timeout?: number;           // 总超时时间 (默认30秒)
  drainDelay?: number;        // 排空延迟 (默认5秒)
  stepTimeout?: number;       // 单步超时 (默认6秒)
  skipSteps?: string[];       // 跳过的步骤
}

// 执行优雅关闭
await server.gracefulShutdown({
  timeout: 45000,
  drainDelay: 10000,
  stepTimeout: 8000
});

关闭步骤详解

  1. 停止接受新连接: 关闭服务器监听,拒绝新连接
  2. 等待排空延迟: 给负载均衡器时间发现服务下线
  3. 等待连接完成: 等待现有连接的请求处理完毕
  4. 强制关闭连接: 终止超时的连接
  5. 清理资源: 停止监控任务,清理连接池

信号处理

terminus模块会自动处理进程信号(SIGTERM、SIGINT等),并调用server.Stop()方法执行优雅关闭流程。

server.Stop()方法内部会自动调用gracefulShutdown(),无需应用层手动处理:

🔐 SSL/TLS配置

HTTPS/HTTP2 SSL配置

const httpsConfig = ConfigHelper.createHttpsConfig({
  hostname: '0.0.0.0',
  port: 443,
  ssl: {
    mode: 'mutual_tls',          // auto | manual | mutual_tls
    key: './ssl/server.key',
    cert: './ssl/server.crt',
    ca: './ssl/ca.crt',
    passphrase: 'your-passphrase',
    ciphers: 'ECDHE-RSA-AES128-GCM-SHA256:!RC4:!LOW:!MD5:!aNULL',
    honorCipherOrder: true,
    secureProtocol: 'TLSv1_2_method',
    requestCert: true,
    rejectUnauthorized: true
  }
});

gRPC SSL配置

const grpcConfig = ConfigHelper.createGrpcConfig({
  hostname: '0.0.0.0',
  port: 50051,
  ssl: {
    enabled: true,
    keyFile: './certs/server.key',
    certFile: './certs/server.crt',
    caFile: './certs/ca.crt',
    clientCertRequired: true
  }
});

📚 API参考

服务器类

  • HttpServer - HTTP服务器实现
  • HttpsServer - HTTPS服务器实现
  • Http2Server - HTTP/2服务器实现
  • WsServer - WebSocket服务器实现
  • GrpcServer - gRPC服务器实现

配置类

  • ConfigHelper - 统一配置创建器
  • ConnectionPoolConfig - 连接池配置接口
  • BaseServerOptions - 基础服务器选项
  • SSLConfig, SSL1Config, SSL2Config - SSL配置接口

连接池类

  • HttpConnectionPoolManager - HTTP连接池
  • HttpsConnectionPoolManager - HTTPS连接池
  • Http2ConnectionPoolManager - HTTP/2连接池
  • WebSocketConnectionPoolManager - WebSocket连接池
  • GrpcConnectionPoolManager - gRPC连接池

🤝 贡献

欢迎提交Issue和Pull Request!

About

Provide http1/2, websocket, gRPC server for Koatty.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published