# 平台适配器接口契约 **版本**: 1.0.0 **创建日期**: 2025-09-28 **目标**: 定义各交易平台HTTP适配器的统一接口 ## 接口定义 ### IPlatformAdapter 平台适配器的统一接口,每个交易平台实现此接口。 ```typescript interface IPlatformAdapter { /** 平台标识 */ readonly platform: string; /** 平台基础URL */ readonly baseUrl: string; /** * 执行HTTP请求 * @param request 请求配置 * @returns 响应数据 */ request(request: PlatformRequest): Promise>; /** * 预处理请求(添加认证、格式化等) * @param request 原始请求 * @returns 处理后的请求 */ prepareRequest(request: PlatformRequest): Promise; /** * 设置代理配置 * @param proxyConfig 代理配置 */ setProxyConfig(proxyConfig: ProxyConfig | null): Promise; /** * 获取当前代理状态 * @returns 代理状态信息 */ getProxyStatus(): Promise; /** * 后处理响应(解析、验证等) * @param response 原始响应 * @returns 处理后的响应 */ processResponse(response: RawResponse): Promise>; /** * 检查平台健康状态 * @returns 健康状态 */ checkHealth(): Promise; /** * 获取平台特定配置 * @returns 配置信息 */ getConfig(): PlatformConfig; /** * 验证平台配置 * @returns 配置是否有效 */ validateConfig(): boolean; } ``` ### PlatformRequest 平台请求接口。 ```typescript interface PlatformRequest { /** 账户标识 */ accountId: string; /** HTTP方法 */ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; /** 请求路径(相对于baseUrl) */ path: string; /** 请求头 */ headers?: Record; /** 请求体 */ body?: any; /** 查询参数 */ params?: Record; /** 请求选项 */ options?: PlatformRequestOptions; } ``` ### PlatformRequestOptions 平台请求选项。 ```typescript interface PlatformRequestOptions { /** 是否需要认证 */ requiresAuth?: boolean; // 默认true /** 认证类型 */ authType?: 'signature' | 'apikey' | 'none'; /** 超时配置 */ timeout?: number; /** 是否启用重试 */ enableRetry?: boolean; /** 平台特定选项 */ platformSpecific?: Record; } ``` ### PreparedRequest 预处理后的请求。 ```typescript interface PreparedRequest { /** 完整URL */ url: string; /** HTTP方法 */ method: string; /** 请求头(包含认证信息) */ headers: Record; /** 请求体 */ body?: string | Buffer; /** 超时配置 */ timeout: TimeoutConfig; } ``` ### PlatformResponse 平台响应接口。 ```typescript interface PlatformResponse { /** 响应状态码 */ status: number; /** 响应数据 */ data: T; /** 响应头 */ headers: Record; /** 平台特定元数据 */ metadata: PlatformMetadata; } ``` ### PlatformMetadata 平台元数据。 ```typescript interface PlatformMetadata { /** 平台名称 */ platform: string; /** 请求ID */ requestId: string; /** 服务器时间戳 */ serverTime?: Date; /** 速率限制信息 */ rateLimit?: RateLimitInfo; /** 平台特定数据 */ platformData?: Record; } ``` ### RateLimitInfo 速率限制信息。 ```typescript interface RateLimitInfo { /** 限制数量 */ limit: number; /** 剩余数量 */ remaining: number; /** 重置时间 */ resetTime: Date; /** 重置间隔(秒) */ resetInterval: number; } ``` ### PlatformConfig 平台配置接口。 ```typescript interface PlatformConfig { /** 平台名称 */ name: string; /** 基础URL */ baseUrl: string; /** 默认超时配置 */ defaultTimeout: TimeoutConfig; /** 重试配置 */ retryConfig: RetryConfig; /** 速率限制配置 */ rateLimits: RateLimitConfig; /** 认证配置 */ authConfig: AuthConfig; /** 代理配置 */ proxyConfig?: ProxyConfig; } ``` ### AuthConfig 认证配置。 ```typescript interface AuthConfig { /** 认证类型 */ type: 'signature' | 'apikey' | 'bearer'; /** 签名算法 */ algorithm?: 'ed25519' | 'hmac-sha256' | 'eip-191'; /** 认证头名称 */ headerNames: { timestamp?: string; signature?: string; apiKey?: string; nonce?: string; }; /** 是否需要时间戳 */ requiresTimestamp: boolean; /** 时间戳容忍度(毫秒) */ timestampTolerance?: number; } ``` ### ProxyConfig 代理配置。 ```typescript interface ProxyConfig { /** 是否启用代理 */ enabled: boolean; /** 代理URL */ url?: string; /** 代理认证 */ auth?: { username: string; password: string; }; /** 代理类型 */ type?: 'http' | 'https' | 'socks4' | 'socks5'; /** 会话配置 */ session?: { prefix: string; suffix: string; rotation: boolean; sticky?: boolean; }; /** 连接配置 */ connection?: { timeout?: number; keepAlive?: boolean; maxIdleTime?: number; }; /** 故障转移配置 */ failover?: { enabled: boolean; maxRetries: number; delay: number; fallbackToDirect?: boolean; }; } ``` ### ProxyStatus 代理状态信息。 ```typescript interface ProxyStatus { /** 代理是否启用 */ enabled: boolean; /** 当前使用的代理URL */ currentProxy?: string; /** 连接状态 */ status: 'connected' | 'connecting' | 'disconnected' | 'error'; /** 连接统计 */ stats: { totalRequests: number; successfulRequests: number; failedRequests: number; averageResponseTime: number; lastRequestTime?: Date; }; /** 健康状态 */ health: { isHealthy: boolean; lastHealthCheck?: Date; consecutiveFailures: number; }; /** 代理池状态(如果使用代理池) */ pool?: { totalProxies: number; activeProxies: number; currentProxyIndex: number; }; /** 错误信息 */ lastError?: { code: string; message: string; timestamp: Date; }; } ``` ## 平台特定实现 ### Pacifica适配器 ```typescript interface IPacificaAdapter extends IPlatformAdapter { /** Ed25519签名请求 */ signRequest(request: PacificaSignRequest): Promise; /** 获取账户nonce */ getAccountNonce(accountId: string): Promise; /** 序列化订单消息 */ serializeOrder(order: PacificaOrder): Uint8Array; } ``` ### Aster适配器 ```typescript interface IAsterAdapter extends IPlatformAdapter { /** EIP-191签名请求 */ signMessage(message: string, accountId: string): Promise; /** 获取订单哈希 */ getOrderHash(order: AsterOrder): string; /** WebSocket认证 */ authenticateWebSocket(accountId: string): Promise; } ``` ### Binance适配器 ```typescript interface IBinanceAdapter extends IPlatformAdapter { /** HMAC-SHA256签名 */ generateSignature(queryString: string, accountId: string): Promise; /** 获取服务器时间 */ getServerTime(): Promise; /** 处理订单响应 */ parseOrderResponse(response: any): BinanceOrderResult; } ``` ## 扩展机制 ### 平台注册工厂 ```typescript interface IPlatformAdapterFactory { /** 注册新平台适配器 */ register(platform: string, adapter: IPlatformAdapter): void; /** 创建平台适配器实例 */ create(platform: string, config: PlatformConfig): IPlatformAdapter; /** 获取已注册的平台列表 */ getRegisteredPlatforms(): string[]; /** 检查平台是否已注册 */ isRegistered(platform: string): boolean; /** 注销平台适配器 */ unregister(platform: string): void; } ``` ### 平台配置模板 ```typescript interface IPlatformConfigTemplate { /** 生成默认配置 */ generateDefault(platform: string): PlatformConfig; /** 验证配置完整性 */ validate(config: PlatformConfig): ValidationResult; /** 合并配置 */ merge(base: PlatformConfig, override: Partial): PlatformConfig; /** 从环境变量加载配置 */ loadFromEnv(platform: string): Partial; } ``` ## 错误处理 ### PlatformError 平台特定错误类。 ```typescript class PlatformError extends HttpClientError { constructor( platform: string, message: string, code: string, public readonly platformCode?: string, details?: any ) { super(`[${platform}] ${message}`, code, details); this.name = 'PlatformError'; } } ``` ### 平台错误映射 | 平台 | 原始错误 | 标准错误代码 | 重试建议 | |------|----------|--------------|----------| | Pacifica | `invalid_signature` | `AUTH_FAILED` | 不重试 | | Pacifica | `rate_limit_exceeded` | `RATE_LIMITED` | 延迟重试 | | Aster | `unauthorized` | `AUTH_FAILED` | 不重试 | | Aster | `too_many_requests` | `RATE_LIMITED` | 延迟重试 | | Binance | `INVALID_SIGNATURE` | `AUTH_FAILED` | 不重试 | | Binance | `-1003` | `RATE_LIMITED` | 延迟重试 | ## 性能要求 ### 响应时间目标 - Pacifica: < 80ms - Aster: < 100ms - Binance: < 120ms ### 并发限制 - Pacifica: 100 req/s - Aster: 50 req/s - Binance: 1200 req/min ### 连接池配置 - 每平台最大连接数: 20 - 连接空闲超时: 30秒 - 连接重用: 启用 ## 测试要求 ### 契约测试 - 每个接口方法必须有契约测试 - 测试必须使用真实API端点 - 测试数据不能包含生产凭据 ### 集成测试 - 端到端请求流程测试 - 错误处理测试 - 性能基准测试 ### 模拟测试 - 网络异常模拟 - 平台故障模拟 - 速率限制模拟 --- **实施注意**: 每个平台适配器应独立实现,确保平台特定逻辑封装良好,便于维护和测试。