# 后端架构

<cite>
**本文引用的文件**
- [server/src/app.ts](file://server/src/app.ts)
- [server/src/config/index.ts](file://server/src/config/index.ts)
- [server/src/middleware/auth.ts](file://server/src/middleware/auth.ts)
- [server/src/middleware/errorHandler.ts](file://server/src/middleware/errorHandler.ts)
- [server/src/middleware/performance.ts](file://server/src/middleware/performance.ts)
- [server/src/middleware/security.ts](file://server/src/middleware/security.ts)
- [server/src/middleware/rate-limiter.ts](file://server/src/middleware/rate-limiter.ts)
- [server/src/services/logger.service.ts](file://server/src/services/logger.service.ts)
- [server/src/services/sentry.service.ts](file://server/src/services/sentry.service.ts)
- [server/src/modules/auth/auth.controller.ts](file://server/src/modules/auth/auth.controller.ts)
- [server/src/models/index.ts](file://server/src/models/index.ts)
- [server/src/modules/tts/tts.service.ts](file://server/src/modules/tts/tts.service.ts)
- [server/src/services/redis.service.ts](file://server/src/services/redis.service.ts)
- [server/src/services/storage.service.ts](file://server/src/services/storage.service.ts)
- [server/src/types/index.ts](file://server/src/types/index.ts)
</cite>

## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构总览](#架构总览)
5. [详细组件分析](#详细组件分析)
6. [依赖关系分析](#依赖关系分析)
7. [性能考量](#性能考量)
8. [故障排查指南](#故障排查指南)
9. [结论](#结论)
10. [附录](#附录)

## 简介
本文件面向AI有声书生成平台的后端架构，围绕Koa.js应用进行系统化梳理，重点覆盖以下方面：
- 应用入口与路由组织
- 中间件体系：认证、安全、限流、性能监控、错误处理
- 控制器层、服务层、数据访问层的职责分离与协作
- 配置管理、环境变量与第三方服务集成
- API版本控制、请求校验、响应格式化与安全防护
- 日志记录、异常处理与监控告警

## 项目结构
后端采用模块化与分层架构：
- 应用入口：Koa实例、路由注册、中间件装配
- 中间件层：认证、安全、限流、性能监控、错误处理
- 控制器层：按业务域划分（如auth、tts、player等）
- 服务层：业务逻辑封装（TTS、存储、队列、日志、Sentry等）
- 数据访问层：Prisma客户端与数据库连接
- 配置层：环境变量加载、模型配置、运行参数

```mermaid
graph TB
subgraph "应用入口"
APP["server/src/app.ts"]
end
subgraph "中间件层"
AUTH["auth.ts"]
SEC["security.ts"]
PERF["performance.ts"]
ERR["errorHandler.ts"]
RATE["rate-limiter.ts"]
end
subgraph "控制器层"
CTRL_AUTH["modules/auth/auth.controller.ts"]
CTRL_TTS["modules/tts/tts.controller.ts"]
end
subgraph "服务层"
SRV_LOGGER["services/logger.service.ts"]
SRV_SENTRY["services/sentry.service.ts"]
SRV_REDIS["services/redis.service.ts"]
SRV_STORAGE["services/storage.service.ts"]
SRV_TTS["modules/tts/tts.service.ts"]
end
subgraph "数据访问层"
PRISMA["models/index.ts"]
end
APP --> AUTH
APP --> SEC
APP --> PERF
APP --> ERR
APP --> RATE
APP --> CTRL_AUTH
APP --> CTRL_TTS
CTRL_AUTH --> SRV_TTS
CTRL_TTS --> SRV_TTS
SRV_TTS --> PRISMA
SRV_TTS --> SRV_STORAGE
SRV_TTS --> SRV_REDIS
SRV_LOGGER --> APP
SRV_SENTRY --> APP
```

**图表来源**
- [server/src/app.ts:57-130](file://server/src/app.ts#L57-L130)
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)
- [server/src/middleware/performance.ts:29-76](file://server/src/middleware/performance.ts#L29-L76)
- [server/src/middleware/errorHandler.ts:3-24](file://server/src/middleware/errorHandler.ts#L3-L24)
- [server/src/middleware/rate-limiter.ts:49-72](file://server/src/middleware/rate-limiter.ts#L49-L72)
- [server/src/modules/auth/auth.controller.ts:8-94](file://server/src/modules/auth/auth.controller.ts#L8-L94)
- [server/src/modules/tts/tts.service.ts:1-715](file://server/src/modules/tts/tts.service.ts#L1-L715)
- [server/src/services/logger.service.ts:75-102](file://server/src/services/logger.service.ts#L75-L102)
- [server/src/services/sentry.service.ts:92-110](file://server/src/services/sentry.service.ts#L92-L110)
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)

**章节来源**
- [server/src/app.ts:57-130](file://server/src/app.ts#L57-L130)

## 核心组件
- 应用入口与路由组织
  - 创建Koa实例与HTTP服务器，注册全局中间件与路由
  - 健康检查与性能指标路由
- 中间件体系
  - 认证中间件：基于JWT的Bearer Token校验
  - 安全中间件：XSS过滤、SQL注入检测、敏感数据脱敏、安全响应头
  - 限流中间件：基于内存/Redis的灵活限流器
  - 性能监控中间件：统计请求总数、平均耗时、慢请求、错误率
  - 错误处理中间件：统一错误响应与开发环境堆栈输出
- 控制器层
  - 按模块拆分（auth、tts、member、share、player等）
  - 控制器内进行参数校验与调用服务层
- 服务层
  - TTS服务：文本分段、多提供商合成、合并与上传、状态查询
  - 存储服务：OSS与本地存储无缝切换
  - Redis服务：键值缓存、Hash、计数器、过期控制
  - 日志与Sentry：Winston日志、HTTP请求日志、错误上报
- 数据访问层
  - Prisma客户端连接MySQL/MariaDB
- 配置管理
  - 环境变量加载与模型配置聚合
  - JWT密钥、DashScope/TTS参数、上传目录与大小限制

**章节来源**
- [server/src/app.ts:63-130](file://server/src/app.ts#L63-L130)
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)
- [server/src/middleware/rate-limiter.ts:49-72](file://server/src/middleware/rate-limiter.ts#L49-L72)
- [server/src/middleware/performance.ts:29-76](file://server/src/middleware/performance.ts#L29-L76)
- [server/src/middleware/errorHandler.ts:3-24](file://server/src/middleware/errorHandler.ts#L3-L24)
- [server/src/modules/auth/auth.controller.ts:8-94](file://server/src/modules/auth/auth.controller.ts#L8-L94)
- [server/src/modules/tts/tts.service.ts:1-715](file://server/src/modules/tts/tts.service.ts#L1-L715)
- [server/src/services/storage.service.ts:43-49](file://server/src/services/storage.service.ts#L43-L49)
- [server/src/services/redis.service.ts:52-82](file://server/src/services/redis.service.ts#L52-L82)
- [server/src/services/logger.service.ts:75-102](file://server/src/services/logger.service.ts#L75-L102)
- [server/src/services/sentry.service.ts:92-110](file://server/src/services/sentry.service.ts#L92-L110)
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)
- [server/src/config/index.ts:69-117](file://server/src/config/index.ts#L69-L117)

## 架构总览
下图展示从客户端到控制器、服务层、存储与数据库的整体交互流程。

```mermaid
sequenceDiagram
participant C as "客户端"
participant K as "Koa应用(app.ts)"
participant M1 as "认证中间件(auth.ts)"
participant M2 as "安全中间件(security.ts)"
participant M3 as "性能中间件(performance.ts)"
participant M4 as "错误处理(errorHandler.ts)"
participant R as "路由(controllers)"
participant S as "服务层(tts.service.ts)"
participant P as "Prisma(models/index.ts)"
participant ST as "存储(storage.service.ts)"
participant RD as "Redis(redis.service.ts)"
C->>K : HTTP请求
K->>M4 : 错误处理
K->>M3 : 性能监控
K->>M2 : 安全过滤
K->>M1 : JWT校验
K->>R : 路由匹配
R->>S : 业务调用
S->>P : 数据库操作
S->>ST : 上传/下载
S->>RD : 缓存读写
S-->>R : 业务结果
R-->>C : 统一响应
```

**图表来源**
- [server/src/app.ts:63-130](file://server/src/app.ts#L63-L130)
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)
- [server/src/middleware/performance.ts:29-76](file://server/src/middleware/performance.ts#L29-L76)
- [server/src/middleware/errorHandler.ts:3-24](file://server/src/middleware/errorHandler.ts#L3-L24)
- [server/src/modules/auth/auth.controller.ts:8-94](file://server/src/modules/auth/auth.controller.ts#L8-L94)
- [server/src/modules/tts/tts.service.ts:1-715](file://server/src/modules/tts/tts.service.ts#L1-L715)
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)
- [server/src/services/storage.service.ts:43-49](file://server/src/services/storage.service.ts#L43-L49)
- [server/src/services/redis.service.ts:52-82](file://server/src/services/redis.service.ts#L52-L82)

## 详细组件分析

### 应用入口与路由组织
- 创建Koa实例与HTTP服务器，注册全局中间件顺序对行为至关重要
- 健康检查与性能指标路由便于运维观测
- 路由按模块挂载，形成清晰的REST风格API命名空间

**章节来源**
- [server/src/app.ts:57-130](file://server/src/app.ts#L57-L130)

### 中间件体系

#### 认证中间件
- 支持可选认证与强制认证两种模式
- Bearer Token解析与JWT校验，开发环境可通过环境变量开关
- 将用户信息注入ctx.state供后续中间件与控制器使用

```mermaid
flowchart TD
Start(["进入认证中间件"]) --> CheckAuth["检查是否开启认证"]
CheckAuth --> |未开启| SetTestUser["设置测试用户信息"]
SetTestUser --> Next["继续下一个中间件"]
CheckAuth --> |已开启| ParseHeader["解析Authorization头"]
ParseHeader --> ValidateFormat{"格式是否为Bearer Token?"}
ValidateFormat --> |否| ThrowUnauthorized["抛出未授权错误"]
ValidateFormat --> |是| VerifyToken["验证JWT签名"]
VerifyToken --> TokenOK{"校验是否通过?"}
TokenOK --> |否| ThrowUnauthorized2["抛出未授权错误"]
TokenOK --> |是| AttachUser["将用户信息写入ctx.state"]
AttachUser --> Next
```

**图表来源**
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)

**章节来源**
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)

#### 安全中间件
- XSS过滤：递归清理请求体与查询参数中的危险字符与脚本标签
- SQL注入检测：正则匹配常见注入模式，发现即拒绝
- 敏感数据脱敏：对响应体中密码、令牌等字段进行脱敏
- 安全响应头：X-XSS-Protection、X-Content-Type-Options、X-Frame-Options、CSP

```mermaid
flowchart TD
Start(["进入安全中间件"]) --> SanitizeBody["递归清理请求体XSS"]
SanitizeBody --> SanitizeQuery["递归清理查询参数XSS"]
SanitizeQuery --> SetHeaders["设置安全响应头"]
SetHeaders --> Next["继续下一个中间件"]
```

**图表来源**
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)

**章节来源**
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)

#### 限流中间件
- 支持内存与Redis双栈限流器，自动回退
- 提供通用限流器工厂与多种场景预设（API、登录、短信、TTS、上传）

```mermaid
flowchart TD
Enter(["进入限流中间件"]) --> GetLimiter["获取或创建限流器"]
GetLimiter --> GenKey["生成限流键(默认IP/用户)"]
GenKey --> Consume["尝试consume(1)"]
Consume --> |成功| Next["继续下一个中间件"]
Consume --> |失败| Reject["返回429与Retry-After"]
```

**图表来源**
- [server/src/middleware/rate-limiter.ts:49-72](file://server/src/middleware/rate-limiter.ts#L49-L72)

**章节来源**
- [server/src/middleware/rate-limiter.ts:49-72](file://server/src/middleware/rate-limiter.ts#L49-L72)

#### 性能监控中间件
- 统计总请求数、平均响应时间、慢请求阈值、端点维度指标
- 通过响应头返回X-Response-Time
- 提供/health与/api/metrics端点

```mermaid
flowchart TD
Enter(["进入性能监控"]) --> StartTimer["记录开始时间"]
StartTimer --> Next["执行业务逻辑"]
Next --> Calc["计算耗时"]
Calc --> Update["更新全局与端点指标"]
Update --> Slow{"是否慢请求?"}
Slow --> |是| LogWarn["记录慢请求警告"]
Slow --> |否| SetHeader["设置X-Response-Time"]
SetHeader --> Done(["结束"])
```

**图表来源**
- [server/src/middleware/performance.ts:29-76](file://server/src/middleware/performance.ts#L29-L76)

**章节来源**
- [server/src/middleware/performance.ts:29-76](file://server/src/middleware/performance.ts#L29-L76)

#### 错误处理中间件
- 捕获异常并统一返回code/message/data结构
- 开发环境附加stack信息
- 提供AppError及其子类（Unauthorized、Forbidden、NotFound、BadRequest、QuotaExceeded）

**章节来源**
- [server/src/middleware/errorHandler.ts:3-24](file://server/src/middleware/errorHandler.ts#L3-L24)

### 控制器层与服务层职责分离
- 控制器负责参数接收、基础校验与调用服务层
- 服务层封装复杂业务逻辑（如TTS合成、存储上传、Redis缓存）
- 数据访问通过Prisma客户端在服务层内完成

```mermaid
classDiagram
class AuthController {
+sendCode()
+login()
+getUserInfo()
+updateUserInfo()
}
class TTSService {
+generateAudio()
+getAudioStatus()
+getAvailableProviders()
}
class PrismaClient {
+$connect()
}
class StorageService {
+uploadAudio()
+downloadFile()
}
class RedisService {
+get/set()
+hgetall()
}
AuthController --> TTSService : "调用"
TTSService --> PrismaClient : "数据访问"
TTSService --> StorageService : "文件上传"
TTSService --> RedisService : "缓存"
```

**图表来源**
- [server/src/modules/auth/auth.controller.ts:8-94](file://server/src/modules/auth/auth.controller.ts#L8-L94)
- [server/src/modules/tts/tts.service.ts:1-715](file://server/src/modules/tts/tts.service.ts#L1-L715)
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)
- [server/src/services/storage.service.ts:43-49](file://server/src/services/storage.service.ts#L43-L49)
- [server/src/services/redis.service.ts:52-82](file://server/src/services/redis.service.ts#L52-L82)

**章节来源**
- [server/src/modules/auth/auth.controller.ts:8-94](file://server/src/modules/auth/auth.controller.ts#L8-L94)
- [server/src/modules/tts/tts.service.ts:1-715](file://server/src/modules/tts/tts.service.ts#L1-L715)
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)
- [server/src/services/storage.service.ts:43-49](file://server/src/services/storage.service.ts#L43-L49)
- [server/src/services/redis.service.ts:52-82](file://server/src/services/redis.service.ts#L52-L82)

### 数据访问层
- PrismaClient负责连接数据库并提供ORM能力
- 在服务层内进行查询与更新，避免控制器直连数据库

**章节来源**
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)

### 配置管理与环境变量
- 使用dotenv加载环境变量，结合models.json聚合模型配置
- 支持JWT密钥、DashScope/TTS参数、上传目录与大小限制等
- 提供模型自动切换策略（基于错误类型判断）

**章节来源**
- [server/src/config/index.ts:69-117](file://server/src/config/index.ts#L69-L117)

### 第三方服务集成
- 存储：OSS与本地存储无缝切换，支持上传、下载、签名URL、批量删除
- 缓存：Redis键值、Hash、计数器、过期控制与批量删除
- 日志：Winston多传输器（控制台、错误文件、常规文件、HTTP请求）
- 监控：Sentry错误监控与性能采样，支持过滤与上下文设置

**章节来源**
- [server/src/services/storage.service.ts:43-49](file://server/src/services/storage.service.ts#L43-L49)
- [server/src/services/redis.service.ts:52-82](file://server/src/services/redis.service.ts#L52-L82)
- [server/src/services/logger.service.ts:75-102](file://server/src/services/logger.service.ts#L75-L102)
- [server/src/services/sentry.service.ts:92-110](file://server/src/services/sentry.service.ts#L92-L110)

### API版本控制、请求验证与响应格式化
- 版本控制：路由以/api前缀组织，不同模块独立命名空间
- 请求验证：控制器内进行基础参数校验（如手机号格式、验证码格式）
- 响应格式：统一ApiResponse结构（code/message/data），错误中间件保证一致性

**章节来源**
- [server/src/app.ts:100-128](file://server/src/app.ts#L100-L128)
- [server/src/modules/auth/auth.controller.ts:14-16](file://server/src/modules/auth/auth.controller.ts#L14-L16)
- [server/src/types/index.ts:85-89](file://server/src/types/index.ts#L85-L89)

### 安全防护措施
- XSS与SQL注入双重防护
- 敏感数据脱敏与安全响应头
- 可选认证与强制认证模式
- 限流策略降低滥用风险

**章节来源**
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)
- [server/src/middleware/rate-limiter.ts:49-72](file://server/src/middleware/rate-limiter.ts#L49-L72)
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)

## 依赖关系分析

```mermaid
graph LR
A["app.ts"] --> B["auth.ts"]
A --> C["security.ts"]
A --> D["performance.ts"]
A --> E["errorHandler.ts"]
A --> F["rate-limiter.ts"]
A --> G["auth.controller.ts"]
A --> H["tts.controller.ts"]
H --> I["tts.service.ts"]
I --> J["models/index.ts"]
I --> K["storage.service.ts"]
I --> L["redis.service.ts"]
M["logger.service.ts"] --> A
N["sentry.service.ts"] --> A
```

**图表来源**
- [server/src/app.ts:63-130](file://server/src/app.ts#L63-L130)
- [server/src/middleware/auth.ts:7-49](file://server/src/middleware/auth.ts#L7-L49)
- [server/src/middleware/security.ts:7-27](file://server/src/middleware/security.ts#L7-L27)
- [server/src/middleware/performance.ts:29-76](file://server/src/middleware/performance.ts#L29-L76)
- [server/src/middleware/errorHandler.ts:3-24](file://server/src/middleware/errorHandler.ts#L3-L24)
- [server/src/middleware/rate-limiter.ts:49-72](file://server/src/middleware/rate-limiter.ts#L49-L72)
- [server/src/modules/auth/auth.controller.ts:8-94](file://server/src/modules/auth/auth.controller.ts#L8-L94)
- [server/src/modules/tts/tts.service.ts:1-715](file://server/src/modules/tts/tts.service.ts#L1-L715)
- [server/src/models/index.ts:5-13](file://server/src/models/index.ts#L5-L13)
- [server/src/services/storage.service.ts:43-49](file://server/src/services/storage.service.ts#L43-L49)
- [server/src/services/redis.service.ts:52-82](file://server/src/services/redis.service.ts#L52-L82)
- [server/src/services/logger.service.ts:75-102](file://server/src/services/logger.service.ts#L75-L102)
- [server/src/services/sentry.service.ts:92-110](file://server/src/services/sentry.service.ts#L92-L110)

**章节来源**
- [server/src/app.ts:63-130](file://server/src/app.ts#L63-L130)

## 性能考量
- 性能监控中间件提供端点级指标与慢请求告警
- TTS服务采用分段与并发策略，支持多提供商与降级
- 存储与缓存分离，上传统一经由存储服务抽象
- 限流中间件按场景精细化配置，避免热点接口被压垮

[本节为通用指导，无需特定文件引用]

## 故障排查指南
- 错误处理中间件统一捕获异常并返回标准结构，开发环境显示堆栈
- Sentry中间件自动捕获异常并设置上下文标签与用户信息
- Winston日志记录HTTP请求与错误详情，便于定位问题
- Redis与存储服务提供连接测试方法，便于快速验证基础设施可用性

**章节来源**
- [server/src/middleware/errorHandler.ts:3-24](file://server/src/middleware/errorHandler.ts#L3-L24)
- [server/src/services/sentry.service.ts:92-110](file://server/src/services/sentry.service.ts#L92-L110)
- [server/src/services/logger.service.ts:75-102](file://server/src/services/logger.service.ts#L75-L102)
- [server/src/services/redis.service.ts:246-255](file://server/src/services/redis.service.ts#L246-L255)
- [server/src/services/storage.service.ts:252-272](file://server/src/services/storage.service.ts#L252-L272)

## 结论
该后端架构以Koa为核心，通过中间件体系实现横切关注点（认证、安全、限流、监控、错误处理），控制器与服务层职责清晰，配合Prisma与统一存储/缓存抽象，满足AI有声书生成平台的高并发与多提供商需求。建议持续完善API版本策略、引入输入校验Schema与统一鉴权装饰器，进一步提升可维护性与安全性。

[本节为总结性内容，无需特定文件引用]

## 附录

### 统一响应结构
- 字段：code、message、data
- 错误场景：统一由错误中间件填充

**章节来源**
- [server/src/types/index.ts:85-89](file://server/src/types/index.ts#L85-L89)

### 关键环境变量
- 端口、节点环境、JWT密钥与过期时间、DashScope/TTS参数、上传目录与大小限制、存储类型、Redis连接参数、Sentry DSN等

**章节来源**
- [server/src/config/index.ts:69-117](file://server/src/config/index.ts#L69-L117)