# 数据模型:通用HTTP客户端多平台账户管理 **版本**: 1.0.0 **创建日期**: 2025-09-28 **目标**: 定义HTTP客户端库的核心实体、关系和数据流 ## 核心实体 ### HttpClient 统一HTTP客户端的主要实体,管理所有平台请求。 ```typescript interface HttpClient { // 标识 id: string name: string // 配置 globalConfig: GlobalConfig adapters: Map // 状态 status: 'active' | 'paused' | 'closed' health: HealthStatus metrics: PerformanceMetrics // 连接管理 connectionPools: Map activeRequests: Set // 关系 accounts: Map requestHistory: RequestLog[] } ``` ### PlatformAccount 代表单个交易平台上的账户。 ```typescript interface PlatformAccount { // 标识 accountId: string platform: PlatformType alias?: string // 认证信息 credentials: AccountCredentials authContext: AuthenticationContext // 配置 config: PlatformAccountConfig // 状态 status: 'active' | 'suspended' | 'expired' lastActivity: Date // 统计 requestCount: number successRate: number averageResponseTime: number // 关系 activeRequests: Map rateLimitState: RateLimitState } ``` ### HTTPRequest 标准化的HTTP请求实体。 ```typescript interface HTTPRequest { // 标识 id: string correlationId?: string idempotencyKey?: string // 路由信息 platform: PlatformType accountId: string // HTTP配置 method: HttpMethod url: string headers: Record body?: RequestBody // 选项 timeout: TimeoutConfig retry: RetryConfig proxy: ProxyConfig // 状态 status: RequestStatus createdAt: Date startedAt?: Date completedAt?: Date // 关系 response?: HTTPResponse attempts: RequestAttempt[] } ``` ### HTTPResponse 标准化的HTTP响应实体。 ```typescript interface HTTPResponse { // 关联 requestId: string // HTTP信息 status: number statusText: string headers: Record data: ResponseData // 元数据 metadata: ResponseMetadata // 平台特定 platformData?: Record rateLimit?: RateLimitInfo // 时间信息 receivedAt: Date processedAt: Date // 验证 validated: boolean validationErrors?: ValidationError[] } ``` ### AuthenticationContext 管理平台特定的认证信息和状态。 ```typescript interface AuthenticationContext { // 标识 accountId: string platform: PlatformType // 认证配置 authType: AuthType algorithm?: SignatureAlgorithm // 凭据引用 credentialManagerRef: string // 状态 isValid: boolean expiresAt?: Date lastRefresh: Date // 签名信息 nonce?: number timestamp?: number // 错误状态 lastError?: AuthError failureCount: number } ``` ### PlatformConfiguration 存储平台特定的配置和限制。 ```typescript interface PlatformConfiguration { // 平台标识 platform: PlatformType // 网络配置 baseUrl: string endpoints: EndpointConfig // 超时配置 timeouts: TimeoutConfig // 重试配置 retryPolicy: RetryConfig // 速率限制 rateLimits: RateLimitConfig[] // 认证配置 authConfig: AuthConfig // 代理配置 proxyConfig?: ProxyConfig // 性能参数 connectionPool: ConnectionPoolConfig // 验证规则 requestValidation: ValidationRule[] responseValidation: ValidationRule[] } ``` ## 实体关系 ### 主要关系 ```mermaid erDiagram HttpClient ||--o{ PlatformAccount : manages HttpClient ||--o{ HTTPRequest : processes HttpClient ||--|| GlobalConfig : configured_by PlatformAccount ||--|| AuthenticationContext : authenticated_by PlatformAccount ||--o{ HTTPRequest : initiates PlatformAccount ||--|| PlatformConfiguration : configured_by HTTPRequest ||--o| HTTPResponse : produces HTTPRequest ||--o{ RequestAttempt : includes AuthenticationContext }|--|| CredentialManager : uses PlatformConfiguration ||--o{ RateLimitConfig : defines PlatformConfiguration ||--o{ ValidationRule : contains ``` ### 关系说明 1. **HttpClient ↔ PlatformAccount**: 一对多关系,一个客户端管理多个平台账户 2. **PlatformAccount ↔ HTTPRequest**: 一对多关系,一个账户可发起多个请求 3. **HTTPRequest ↔ HTTPResponse**: 一对一关系,每个请求产生一个响应 4. **PlatformAccount ↔ AuthenticationContext**: 一对一关系,每个账户有唯一认证上下文 5. **AuthenticationContext ↔ CredentialManager**: 多对一关系,多个上下文共享凭据管理器 ## 数据流 ### 请求处理流程 ```mermaid sequenceDiagram participant Client as 调用方 participant HC as HttpClient participant PA as PlatformAccount participant Auth as AuthContext participant Adapter as PlatformAdapter participant API as 平台API Client->>HC: request(HttpClientRequest) HC->>PA: 获取账户信息 PA->>Auth: 获取认证上下文 Auth->>Auth: 验证凭据有效性 HC->>Adapter: prepareRequest() Adapter->>Auth: 签名请求 Auth-->>Adapter: 签名结果 Adapter->>API: 发送HTTP请求 API-->>Adapter: HTTP响应 Adapter->>HC: processResponse() HC->>Client: HttpClientResponse ``` ### 状态变化 #### 请求状态转换 ```mermaid stateDiagram-v2 [*] --> Created : 创建请求 Created --> Queued : 加入队列 Queued --> Preparing : 预处理 Preparing --> Authenticating : 认证签名 Authenticating --> Sending : 发送请求 Sending --> Waiting : 等待响应 Waiting --> Processing : 处理响应 Processing --> Completed : 完成 Processing --> Failed : 失败 Sending --> Retrying : 重试 Waiting --> Retrying : 超时重试 Retrying --> Sending : 重新发送 Retrying --> Failed : 重试耗尽 Failed --> [*] Completed --> [*] ``` #### 账户状态转换 ```mermaid stateDiagram-v2 [*] --> Initializing : 初始化 Initializing --> Active : 认证成功 Initializing --> Suspended : 认证失败 Active --> Processing : 处理请求 Processing --> Active : 请求完成 Processing --> RateLimited : 触发限制 RateLimited --> Active : 限制解除 Active --> Suspended : 多次失败 Suspended --> Active : 重新激活 Active --> Expired : 凭据过期 Expired --> Active : 更新凭据 Suspended --> [*] Expired --> [*] ``` ## 数据验证规则 ### 请求验证 ```typescript interface RequestValidationRules { // 基本验证 requiredFields: string[] // 平台特定验证 platformRules: { [K in PlatformType]: { urlPattern: RegExp methodAllowed: HttpMethod[] bodySchema?: JSONSchema headerRequired?: string[] } } // 业务验证 accountValidation: { mustBeActive: boolean rateLimitCheck: boolean balanceCheck?: boolean } } ``` ### 响应验证 ```typescript interface ResponseValidationRules { // HTTP状态验证 expectedStatus: number[] // 内容验证 contentType: string[] dataSchema?: JSONSchema // 平台特定验证 platformValidation: { [K in PlatformType]: { errorCodeMapping: Record successIndicators: string[] rateLimitHeaders?: string[] } } } ``` ## 性能模型 ### 度量实体 ```typescript interface PerformanceMetrics { // 时间指标 responseTime: { average: number p95: number p99: number } // 成功率指标 successRate: { overall: number byPlatform: Record byTimeWindow: TimeWindowMetrics[] } // 吞吐量指标 throughput: { requestsPerSecond: number concurrentRequests: number peakConcurrency: number } // 资源使用 resourceUsage: { connectionPoolUtilization: number memoryUsage: number cpuUsage: number } } ``` ### 容量规划 ```typescript interface CapacityModel { // 目标性能 targets: { maxResponseTime: number // 100ms minSuccessRate: number // 99.9% maxConcurrency: number // 1000 } // 资源限制 limits: { maxConnectionsPerPlatform: number // 20 maxQueueSize: number // 100 maxRetryAttempts: number // 3 } // 扩展策略 scaling: { connectionPoolGrowth: 'linear' | 'exponential' queueOverflowStrategy: 'drop' | 'block' | 'spillover' rateLimitHandling: 'queue' | 'reject' | 'delay' } } ``` --- **实体总结**: 6个核心实体,15个支持实体,完整的状态管理和数据流定义,为后续实现提供清晰的数据模型基础。