Files
asset_helper/AGENTS.md

255 lines
8.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AGENTS.md
本文件为 AI Agent 提供项目背景、结构说明和开发规范。
## 项目概述
这是一个基于 **Rust** 的微服务后端项目,采用 **Axum + Tokio** 技术栈,使用 **Nginx** 作为 API 网关,**PostgreSQL** 作为数据库,**Redis** 作为缓存。服务以 Docker 容器形式部署,每个核心功能拆分为独立的微服务二进制文件。
## 技术栈
| 层级 | 技术 |
|------|------|
| 语言 | Rust 2024 Edition |
| Web 框架 | axum 0.8, tokio 1.x, tower 0.5 |
| 数据库 | PostgreSQL 18.3 (sqlx 0.8) |
| 缓存 | Redis 8.6.2 (redis 0.29) |
| 网关 | Nginx 1.25 (Alpine) |
| 部署 | Docker, Docker Compose |
| 其他 | bcrypt, jsonwebtoken, uuid v7, chrono, tracing, validator |
## 项目结构
```
backend/
├── services/ # 微服务目录
│ └── user-service/ # 用户服务(当前唯一实现的服务域)
│ ├── user-login-account/ # 账号登录服务 (port 8001)
│ ├── user-register-account/ # 账号注册服务 (port 8002)
│ ├── user-login-email/ # 邮箱登录服务 (port 8003)
│ ├── user-register-email/ # 邮箱注册服务 (port 8004)
│ ├── migrations/ # 数据库初始化 SQL
│ ├── docker-compose.yml # 用户服务本地编排
│ └── Dockerfile # 通用/遗留构建文件
├── gateway/ # API 网关
│ ├── Dockerfile
│ └── nginx/
│ ├── nginx.conf
│ ├── conf.d/default.conf
│ └── conf.d/services/ # 各服务路由配置
├── shared/ # 共享代码库(当前为空,待扩展)
├── deploy/
│ └── local/redis.conf # 本地 Redis 配置
├── scripts/
│ ├── gateway.sh # 网关管理脚本(测试/重载/日志/证书)
│ └── init-multiple-databases.sh # Postgres 多库初始化
└── README.md
```
## 微服务架构说明
### 服务拆分原则
每个用户功能(登录/注册)按**认证方式**拆分为独立服务:
- `user-login-account`: 账号密码登录,签发 JWT
- `user-login-email`: 邮箱密码登录,签发 JWT
- `user-register-account`: 账号注册,写入 `user_main` / `user_login_account` / `user_login_password`
- `user-register-email`: 邮箱注册,写入 `user_main` / `user_login_email` / `user_login_password`
每个服务都是独立的 Rust Crate拥有独立的 `Cargo.toml``src/main.rs``Dockerfile`
### 数据库模型
核心表结构(见 `services/user-service/migrations/001_init.sql`
- `user_main(id UUID PK, deleted BOOLEAN, create_date, modify_date)`
- `user_login_account(id UUID PK, user_id FK, account VARCHAR)`
- `user_login_email(id UUID PK, user_id FK, email VARCHAR)`
- `user_login_password(id UUID PK, user_id FK, password VARCHAR)`
采用**软删除**设计(`deleted` 字段),账号/邮箱通过部分索引保证唯一性:
```sql
CREATE UNIQUE INDEX ... ON user_login_account(account) WHERE deleted = FALSE;
```
## 开发规范
### 1. API 公共约定
项目中存在两类接口风格,新增服务时请遵循对应场景的约定:
#### 注册/业务类接口(使用统一包装)
**请求包装格式:**
```json
{
"device": 1,
"language": 1,
"data": {
// 业务字段
}
}
```
- `device`: 设备类型标识(`i32`
- `1` = iOS
- `2` = Android
- `3` = Web
- `4` = iPad
- `5` = macOS
- `6` = Windows
- `7` = Linux
- `language`: 语言标识(`i32`
- `1` = 简体中文
- `2` = 繁体中文
- `3` = 英文
- `data`: 实际业务请求体
**响应包装格式:**
```json
{
"success": true,
"message": "User registered successfully",
"data": {
// 业务返回数据,失败时为 null
}
}
```
- `success`: 布尔值,表示业务是否成功
- `message`: 可读的状态描述或错误信息
- `data`: 业务数据,`Option<T>`,失败时返回 `null`
#### 登录/认证类接口(扁平响应)
**请求格式:** 直接携带凭证字段(如 `username`/`email` + `password`)。
**响应格式:**
```json
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIs...",
"message": "Login successful"
}
```
- `success`: 布尔值
- `token`: JWT Token认证失败或错误时为 `null`
- `message`: 状态描述
#### 健康检查
所有服务必须暴露 `GET /health`,成功时返回 HTTP 200
```text
OK
```
#### 错误响应HTTP 非 200
网关层返回统一 JSON 错误:
```json
{
"error": "Not Found",
"message": "The requested resource was not found",
"code": 404
}
```
### 2. 代码风格
- 使用 **Rust 2024 Edition**
- 注释使用**中文**。
- 服务状态通过 `Arc<AppState>` 注入到 Axum Handler 中。
- 注册类服务统一使用包装请求/响应格式:
```rust
struct ApiRequest<T> { device: i32, language: i32, data: T }
struct ApiResponse<T> { success: bool, message: String, data: Option<T> }
```
### 3. 时间字段约定
所有表中的 `create_date` 和 `modify_date` **必须由业务层生成并传入**数据库Schema中**不设置** `DEFAULT CURRENT_TIMESTAMP`,也不使用触发器自动更新。
- 建表时:
```sql
create_date TIMESTAMP WITH TIME ZONE NOT NULL,
modify_date TIMESTAMP WITH TIME ZONE NOT NULL
```
- Rust 代码中使用 `chrono::Utc::now()` 生成时间戳,统一在事务开始前创建 `let now = Utc::now();`,确保同一笔业务中各表时间一致。
- `modify_date` 更新时同样需要在业务代码中显式传入 `Utc::now()`。
### 4. 环境变量
所有服务通过环境变量读取配置:
- `DATABASE_URL` — PostgreSQL 连接串(必需)
- `REDIS_URL` — Redis 连接串
- `SERVICE_PORT` — 服务监听端口(默认 8080
- `JWT_SECRET` — JWT 签名密钥
- `RUST_LOG` — 日志级别
### 5. Docker 构建
- 各微服务 Dockerfile 的构建上下文为**项目根目录**`docker-compose.yml` 中使用 `context: ../..`)。
- 构建采用多阶段builder + runtime基于 `rust:1.94.1-alpine3.23` 编译,最终运行在 `alpine:3.23`。
- 共享代码更新时,需确保 `shared/` 目录在 Dockerfile 中被正确复制。
### 6. 网关与路由
- Nginx 监听 80/443开发环境使用自签名证书。
- 路由前缀约定:
- `/api/v1/users` → 用户服务通用接口
- `/api/v1/auth` → 认证接口(更严格限流)
- 新增服务时,需在 `gateway/nginx/conf.d/services/` 下创建对应 `.conf` 文件,并在 `nginx.conf` 中添加上游 `upstream`。
## 常用命令
### 启动用户服务(本地开发)
```bash
cd services/user-service
docker-compose up --build
```
### 网关管理
```bash
# 测试配置
./scripts/gateway.sh test
# 生成开发证书
./scripts/gateway.sh certs
# 查看状态
./scripts/gateway.sh status
# 热重载(容器运行中)
./scripts/gateway.sh reload
```
### 本地编译单个服务
```bash
cd services/user-service/user-login-account
cargo run
```
## 扩展指南
### 新增微服务
1. 在 `services/<service-domain>/` 下创建新目录,如 `services/order-service/order-create/`。
2. 编写独立的 `Cargo.toml`、`src/main.rs`、`Dockerfile`。
3. 在 `gateway/nginx/conf.d/services/` 添加路由配置。
4. 在 `gateway/nginx/nginx.conf` 添加 `upstream`。
5. 如需新数据库表,在对应服务域的 `migrations/` 目录添加 SQL 文件。
### 共享代码提取
当前 `shared/` 目录为空。当多个服务需要共用模型、中间件或工具函数时:
1. 在 `shared/` 下创建子模块(如 `shared/models`、`shared/middleware`)。
2. 将共享 crate 以 path dependency 引入各微服务:
```toml
[dependencies]
shared = { path = "../../shared" }
```
3. 更新各 Dockerfile确保 `COPY shared /app/shared` 在依赖缓存步骤之前执行。
## 注意事项
- `services/user-service/Dockerfile` 是一个通用构建文件,但当前各微服务使用自己的 Dockerfile。修改时请确认影响范围。
- 当前 `shared/` 为空Agent 在修改代码时若发现重复逻辑,可提议提取到 `shared/`。
- 网关配置文件中的 `api.example.com` 为占位域名,本地开发需配置 hosts 或使用 `localhost`。