401 lines
8.8 KiB
Markdown
401 lines
8.8 KiB
Markdown
# 项目后续实现计划
|
||
|
||
## 🎯 总体目标
|
||
|
||
基于当前项目状态(已完成阶段1-7),我们需要完成剩余的高级功能,将项目从学习演示提升到生产就绪状态。
|
||
|
||
## 📋 详细实现计划
|
||
|
||
### 任务1: 验证SQLite数据库存储功能 ✅ 计划完成
|
||
**状态**: 已创建验证计划 [`database_verification_plan.md`](database_verification_plan.md)
|
||
**下一步**: 切换到Code模式执行验证
|
||
|
||
### 任务2: 添加数据库迁移系统 🔄
|
||
|
||
#### 目标
|
||
实现数据库版本管理和自动迁移系统,支持数据库结构的版本化更新。
|
||
|
||
#### 实现方案
|
||
1. **迁移文件结构**:
|
||
```
|
||
migrations/
|
||
├── 001_initial_users_table.sql
|
||
├── 002_add_user_roles.sql
|
||
└── 003_add_user_profile.sql
|
||
```
|
||
|
||
2. **迁移管理器**:
|
||
```rust
|
||
// src/storage/migrations.rs
|
||
pub struct MigrationManager {
|
||
pool: SqlitePool,
|
||
}
|
||
|
||
impl MigrationManager {
|
||
pub async fn run_migrations(&self) -> Result<(), ApiError> {
|
||
// 创建migrations表
|
||
// 检查已执行的迁移
|
||
// 执行未执行的迁移
|
||
}
|
||
}
|
||
```
|
||
|
||
3. **集成到启动流程**:
|
||
在 `src/main.rs` 中自动运行迁移
|
||
|
||
#### 需要的文件
|
||
- `src/storage/migrations.rs` - 迁移管理器
|
||
- `migrations/001_initial_users_table.sql` - 初始表结构
|
||
- `migrations/002_add_indexes.sql` - 添加索引
|
||
|
||
### 任务3: 实现数据库连接池配置 🔄
|
||
|
||
#### 目标
|
||
优化数据库连接管理,支持连接池配置和监控。
|
||
|
||
#### 实现方案
|
||
1. **配置扩展**:
|
||
```rust
|
||
// src/config/mod.rs
|
||
pub struct DatabaseConfig {
|
||
pub url: String,
|
||
pub max_connections: u32,
|
||
pub min_connections: u32,
|
||
pub connect_timeout: Duration,
|
||
pub idle_timeout: Duration,
|
||
}
|
||
```
|
||
|
||
2. **连接池管理**:
|
||
```rust
|
||
// src/storage/pool.rs
|
||
pub struct DatabasePool {
|
||
pool: SqlitePool,
|
||
config: DatabaseConfig,
|
||
}
|
||
|
||
impl DatabasePool {
|
||
pub async fn new(config: DatabaseConfig) -> Result<Self, ApiError> {
|
||
let pool = SqlitePoolOptions::new()
|
||
.max_connections(config.max_connections)
|
||
.min_connections(config.min_connections)
|
||
.connect_timeout(config.connect_timeout)
|
||
.idle_timeout(config.idle_timeout)
|
||
.connect(&config.url)
|
||
.await?;
|
||
|
||
Ok(Self { pool, config })
|
||
}
|
||
}
|
||
```
|
||
|
||
3. **健康检查**:
|
||
添加数据库连接健康检查端点
|
||
|
||
### 任务4: 添加API分页功能 🔄
|
||
|
||
#### 目标
|
||
为用户列表API添加分页支持,提升大数据量下的性能。
|
||
|
||
#### 实现方案
|
||
1. **分页参数**:
|
||
```rust
|
||
// src/models/pagination.rs
|
||
#[derive(Debug, Deserialize)]
|
||
pub struct PaginationParams {
|
||
pub page: Option<u32>,
|
||
pub limit: Option<u32>,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
pub struct PaginatedResponse<T> {
|
||
pub data: Vec<T>,
|
||
pub pagination: PaginationInfo,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
pub struct PaginationInfo {
|
||
pub current_page: u32,
|
||
pub per_page: u32,
|
||
pub total_pages: u32,
|
||
pub total_items: u64,
|
||
}
|
||
```
|
||
|
||
2. **存储层支持**:
|
||
```rust
|
||
// 在 UserStore trait 中添加
|
||
async fn list_users_paginated(
|
||
&self,
|
||
page: u32,
|
||
limit: u32
|
||
) -> Result<PaginatedResponse<User>, ApiError>;
|
||
```
|
||
|
||
3. **API端点更新**:
|
||
更新 `GET /api/users` 支持查询参数 `?page=1&limit=10`
|
||
|
||
### 任务5: 实现用户搜索和过滤功能 🔄
|
||
|
||
#### 目标
|
||
添加用户搜索和过滤功能,支持按用户名、邮箱等字段搜索。
|
||
|
||
#### 实现方案
|
||
1. **搜索参数**:
|
||
```rust
|
||
// src/models/search.rs
|
||
#[derive(Debug, Deserialize)]
|
||
pub struct UserSearchParams {
|
||
pub q: Option<String>, // 通用搜索
|
||
pub username: Option<String>, // 用户名搜索
|
||
pub email: Option<String>, // 邮箱搜索
|
||
pub created_after: Option<DateTime<Utc>>,
|
||
pub created_before: Option<DateTime<Utc>>,
|
||
}
|
||
```
|
||
|
||
2. **存储层实现**:
|
||
```rust
|
||
async fn search_users(
|
||
&self,
|
||
params: UserSearchParams,
|
||
pagination: PaginationParams,
|
||
) -> Result<PaginatedResponse<User>, ApiError>;
|
||
```
|
||
|
||
3. **SQL查询构建**:
|
||
动态构建WHERE子句支持多条件搜索
|
||
|
||
### 任务6: 添加用户角色管理系统 🔄
|
||
|
||
#### 目标
|
||
实现基于角色的访问控制(RBAC),支持用户角色和权限管理。
|
||
|
||
#### 实现方案
|
||
1. **数据模型扩展**:
|
||
```rust
|
||
// src/models/role.rs
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
pub enum UserRole {
|
||
Admin,
|
||
User,
|
||
Moderator,
|
||
}
|
||
|
||
// 扩展User模型
|
||
pub struct User {
|
||
// ... 现有字段
|
||
pub role: UserRole,
|
||
pub is_active: bool,
|
||
}
|
||
```
|
||
|
||
2. **权限中间件**:
|
||
```rust
|
||
// src/middleware/rbac.rs
|
||
pub fn require_role(required_role: UserRole) -> impl Fn(...) -> ... {
|
||
// 检查用户角色权限
|
||
}
|
||
```
|
||
|
||
3. **管理API**:
|
||
- `PUT /api/users/{id}/role` - 更新用户角色
|
||
- `GET /api/admin/users` - 管理员用户列表
|
||
|
||
### 任务7: 完善日志记录和监控 🔄
|
||
|
||
#### 目标
|
||
实现结构化日志记录、请求追踪和性能监控。
|
||
|
||
#### 实现方案
|
||
1. **结构化日志**:
|
||
```rust
|
||
// src/middleware/logging.rs
|
||
pub async fn request_logging_middleware(
|
||
req: Request,
|
||
next: Next,
|
||
) -> Response {
|
||
let start = Instant::now();
|
||
let method = req.method().clone();
|
||
let uri = req.uri().clone();
|
||
|
||
let response = next.run(req).await;
|
||
|
||
let duration = start.elapsed();
|
||
|
||
tracing::info!(
|
||
method = %method,
|
||
uri = %uri,
|
||
status = response.status().as_u16(),
|
||
duration_ms = duration.as_millis(),
|
||
"HTTP request completed"
|
||
);
|
||
|
||
response
|
||
}
|
||
```
|
||
|
||
2. **性能指标**:
|
||
- 请求响应时间
|
||
- 数据库查询时间
|
||
- 内存使用情况
|
||
- 活跃连接数
|
||
|
||
3. **健康检查增强**:
|
||
```rust
|
||
// src/handlers/health.rs
|
||
pub async fn detailed_health_check() -> Json<HealthStatus> {
|
||
Json(HealthStatus {
|
||
status: "healthy",
|
||
timestamp: Utc::now(),
|
||
database: check_database_health().await,
|
||
memory: get_memory_usage(),
|
||
uptime: get_uptime(),
|
||
})
|
||
}
|
||
```
|
||
|
||
### 任务8: 添加API限流和安全中间件 🔄
|
||
|
||
#### 目标
|
||
实现API限流、CORS配置和安全头设置。
|
||
|
||
#### 实现方案
|
||
1. **限流中间件**:
|
||
```rust
|
||
// src/middleware/rate_limit.rs
|
||
pub struct RateLimiter {
|
||
// 使用内存或Redis存储限流信息
|
||
}
|
||
|
||
pub async fn rate_limit_middleware(
|
||
req: Request,
|
||
next: Next,
|
||
) -> Result<Response, StatusCode> {
|
||
// 检查请求频率
|
||
// 返回429 Too Many Requests或继续处理
|
||
}
|
||
```
|
||
|
||
2. **安全中间件**:
|
||
```rust
|
||
// src/middleware/security.rs
|
||
pub async fn security_headers_middleware(
|
||
req: Request,
|
||
next: Next,
|
||
) -> Response {
|
||
let mut response = next.run(req).await;
|
||
|
||
// 添加安全头
|
||
response.headers_mut().insert("X-Content-Type-Options", "nosniff".parse().unwrap());
|
||
response.headers_mut().insert("X-Frame-Options", "DENY".parse().unwrap());
|
||
|
||
response
|
||
}
|
||
```
|
||
|
||
3. **CORS配置**:
|
||
使用tower-http的CORS中间件
|
||
|
||
### 任务9: 创建Docker容器化配置 🔄
|
||
|
||
#### 目标
|
||
创建Docker配置,支持容器化部署。
|
||
|
||
#### 实现方案
|
||
1. **Dockerfile**:
|
||
```dockerfile
|
||
FROM rust:1.75 as builder
|
||
WORKDIR /app
|
||
COPY . .
|
||
RUN cargo build --release
|
||
|
||
FROM debian:bookworm-slim
|
||
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
|
||
COPY --from=builder /app/target/release/rust-user-api /usr/local/bin/rust-user-api
|
||
EXPOSE 3000
|
||
CMD ["rust-user-api"]
|
||
```
|
||
|
||
2. **docker-compose.yml**:
|
||
```yaml
|
||
version: '3.8'
|
||
services:
|
||
api:
|
||
build: .
|
||
ports:
|
||
- "3000:3000"
|
||
environment:
|
||
- DATABASE_URL=sqlite:///data/users.db
|
||
volumes:
|
||
- ./data:/data
|
||
```
|
||
|
||
3. **多阶段构建优化**:
|
||
- 使用Alpine Linux减小镜像大小
|
||
- 静态链接减少依赖
|
||
|
||
### 任务10: 编写部署文档和生产环境配置 🔄
|
||
|
||
#### 目标
|
||
创建完整的部署文档和生产环境配置指南。
|
||
|
||
#### 实现方案
|
||
1. **部署文档**:
|
||
```markdown
|
||
# 部署指南
|
||
|
||
## 环境要求
|
||
- Docker 20.10+
|
||
- 或 Rust 1.75+
|
||
|
||
## 配置说明
|
||
- 环境变量配置
|
||
- 数据库设置
|
||
- 安全配置
|
||
|
||
## 部署步骤
|
||
1. 克隆代码
|
||
2. 配置环境变量
|
||
3. 构建和启动
|
||
4. 健康检查
|
||
```
|
||
|
||
2. **生产环境配置**:
|
||
- 环境变量模板
|
||
- 日志配置
|
||
- 监控配置
|
||
- 备份策略
|
||
|
||
## 🚀 实施顺序建议
|
||
|
||
1. **第一阶段** (立即执行):
|
||
- 验证SQLite数据库存储功能
|
||
- 添加数据库迁移系统
|
||
- 实现数据库连接池配置
|
||
|
||
2. **第二阶段** (核心功能):
|
||
- 添加API分页功能
|
||
- 实现用户搜索和过滤功能
|
||
- 完善日志记录和监控
|
||
|
||
3. **第三阶段** (高级功能):
|
||
- 添加用户角色管理系统
|
||
- 添加API限流和安全中间件
|
||
|
||
4. **第四阶段** (部署准备):
|
||
- 创建Docker容器化配置
|
||
- 编写部署文档和生产环境配置
|
||
|
||
## 📊 预期时间估算
|
||
|
||
- **验证和迁移**: 1-2天
|
||
- **分页和搜索**: 2-3天
|
||
- **角色和安全**: 3-4天
|
||
- **容器化和部署**: 1-2天
|
||
|
||
**总计**: 约7-11天的开发时间
|
||
|
||
---
|
||
|
||
**下一步行动**: 切换到Code模式开始实施第一个任务 - 验证SQLite数据库存储功能。 |