docs: add AGENTS.md development guidelines
- Define code style rules, forbidden patterns, and error handling - Document security, database, API design, and testing standards - Include Git workflow and architecture decision records
This commit is contained in:
@@ -0,0 +1,654 @@
|
||||
# AGENTS.md — 开发规范 / Development Guidelines
|
||||
|
||||
> 本文件为所有 AI 编码助手(Claude Code、pi、Cursor 等)提供统一的开发指导。
|
||||
> This file provides unified development guidelines for all AI coding assistants.
|
||||
|
||||
**最后更新 / Last Updated**: 2026-06-10
|
||||
|
||||
---
|
||||
|
||||
## 目录 / Table of Contents
|
||||
|
||||
1. [语言 / Language](#1-语言--language)
|
||||
2. [代码风格 / Code Style](#2-代码风格--code-style)
|
||||
3. [禁止模式 / Forbidden Patterns](#3-禁止模式--forbidden-patterns)
|
||||
4. [错误处理 / Error Handling](#4-错误处理--error-handling)
|
||||
5. [安全规范 / Security](#5-安全规范--security)
|
||||
6. [数据库规范 / Database](#6-数据库规范--database)
|
||||
7. [API 设计规范 / API Design](#7-api-设计规范--api-design)
|
||||
8. [日志与可观测性 / Logging & Observability](#8-日志与可观测性--logging--observability)
|
||||
9. [性能规范 / Performance](#9-性能规范--performance)
|
||||
10. [测试规范 / Testing](#10-测试规范--testing)
|
||||
11. [Git 规范 / Git Workflow](#11-git-规范--git-workflow)
|
||||
12. [工作流程 / Workflow](#12-工作流程--workflow)
|
||||
13. [架构决策记录 / ADR](#13-架构决策记录--adr)
|
||||
14. [审查清单 / Review Checklist](#14-审查清单--review-checklist)
|
||||
|
||||
---
|
||||
|
||||
## 1. 语言 / Language
|
||||
|
||||
**Always respond in Chinese (中文).** Use the user's language for all conversations and explanations. Code, commands, and technical terms can remain in English.
|
||||
|
||||
始终使用中文回复。代码、命令和技术术语可以保留英文。
|
||||
|
||||
---
|
||||
|
||||
## 2. 代码风格 / Code Style
|
||||
|
||||
### 2.1 基本原则 / Basic Principles
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|-----------|-----------------------------------------------------------------------------------------|
|
||||
| 遵循现有风格 | Follow existing project conventions |
|
||||
| 有意义命名 | Use meaningful variable names; avoid single-letter names except loop counters |
|
||||
| 函数长度 | Keep functions under **50 lines**; split complex logic into smaller functions |
|
||||
| 嵌套深度 | Maximum nesting depth: **3 levels**; use early returns to flatten logic |
|
||||
| 圈复杂度 | Function cyclomatic complexity should not exceed **10** |
|
||||
| 注释 | Add comments for complex logic only; prefer self-documenting code |
|
||||
| 文档注释 | Public items must have `///` doc comments; private items only when logic is non-obvious |
|
||||
|
||||
### 2.2 Rust 最佳实践 / Rust Best Practices
|
||||
|
||||
```rust
|
||||
// ✅ 正确 / Correct
|
||||
fn get_user(id: i64) -> AppResult<User> {
|
||||
let user = db.find_user(id).await?; // 使用 ? 传播错误
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
// ❌ 错误 / Incorrect
|
||||
fn get_user(id: i64) -> User {
|
||||
db.find_user(id).await.unwrap() // 禁止 unwrap()
|
||||
}
|
||||
```
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|-----------|---------------------------------------------------------------------------------------------|
|
||||
| 错误传播 | Use `?` operator for error propagation; never use `unwrap()` or `expect()` in non-test code |
|
||||
| `unsafe` | Avoid `unsafe` blocks; if necessary, add a `// SAFETY:` comment explaining why |
|
||||
| `clone()` | Minimize `clone()` usage; prefer references or `Rc`/`Arc` for shared ownership |
|
||||
| 魔法数字 | No magic numbers; define named constants with `const` |
|
||||
| 硬编码字符串 | No hardcoded strings for config/status; use enums or constants |
|
||||
| 死代码 | Remove dead code; don't leave commented-out code blocks |
|
||||
| 未完成代码 | Don't commit `unimplemented!()`, `todo!()`, or `FIXME` without a tracking issue |
|
||||
|
||||
### 2.3 导入规范 / Import Guidelines
|
||||
|
||||
```rust
|
||||
// 标准库 → 第三方 crate → 本地模块
|
||||
// stdlib → third-party crates → local modules
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::FromRow;
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::common::Status;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 禁止模式 / Forbidden Patterns
|
||||
|
||||
以下代码模式在项目中严格禁止:
|
||||
|
||||
The following code patterns are strictly forbidden in this project:
|
||||
|
||||
| 禁止项 / Forbidden | 说明 / Reason |
|
||||
|-------------------------------|------------------------------------------------|
|
||||
| `// ── xxxx ──────────` | 禁止使用此类分隔线注释;使用 `// Section: xxx` 格式替代 |
|
||||
| `unwrap()` / `expect()` (非测试) | 在非测试代码中禁止使用;使用 `?` 或 `unwrap_or` 等安全替代 |
|
||||
| `panic!()` / `unreachable!()` | 除极少数不可能到达的分支外禁止使用;使用 `AppError` 替代 |
|
||||
| 未处理的 `todo!()` | 不得提交包含 `todo!()` 的代码,除非有对应的 issue 追踪 |
|
||||
| 注释掉的代码 | 不得提交被注释的代码块;使用 Git 历史追溯 |
|
||||
| 过深嵌套 (≥4层) | 使用 early return、`match`、`map`/`and_then` 扁平化逻辑 |
|
||||
| 过长函数 (>50行) | 拆分为更小的、职责单一的函数 |
|
||||
| 魔法数字 | 使用 `const` 定义命名常量 |
|
||||
| 硬编码字符串 | 使用枚举或常量定义配置值/状态值 |
|
||||
| 死代码 | 删除未使用的代码、导入和变量 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 错误处理 / Error Handling
|
||||
|
||||
### 4.1 错误类型体系 / Error Type System
|
||||
|
||||
```rust
|
||||
// 统一使用 AppError 和 AppResult
|
||||
// Use AppError and AppResult consistently
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
pub async fn create_user(req: CreateUserReq) -> AppResult<User> {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
- **AppError**: 统一错误枚举,包含领域错误和外部库包装
|
||||
- **AppResult<T>**: `Result<T, AppError>` 的类型别名
|
||||
|
||||
### 4.2 错误处理原则 / Error Handling Principles
|
||||
|
||||
| 原则 / Principle | 说明 / Description |
|
||||
|----------------|---------------------------------------------------------------------------------|
|
||||
| 显式处理 | Handle all errors explicitly; no silent failures |
|
||||
| 用户友好 | Internal errors are logged and masked; user-facing messages should be helpful |
|
||||
| 错误上下文 | Use `.context()` or `.map_err()` to add meaningful context to errors |
|
||||
| 错误分类 | Domain errors (UserNotFound) vs Infrastructure errors (DatabaseError) |
|
||||
| Postgres 映射 | Map Postgres error codes (23505 unique, 23503 FK, 23514 check) to HTTP statuses |
|
||||
|
||||
### 4.3 错误日志格式 / Error Logging Format
|
||||
|
||||
```rust
|
||||
// 记录错误时包含完整上下文
|
||||
// Log errors with full context
|
||||
tracing::error!(
|
||||
error = %err,
|
||||
user_id = %user_id,
|
||||
operation = "create_user",
|
||||
"Failed to create user"
|
||||
);
|
||||
```
|
||||
|
||||
### 4.4 错误恢复策略 / Error Recovery
|
||||
|
||||
| 场景 / Scenario | 策略 / Strategy |
|
||||
|---------------|---------------|
|
||||
| 数据库连接失败 | 重试 + 降级到只读模式 |
|
||||
| 外部服务超时 | 断路器 + 降级响应 |
|
||||
| 缓存 miss | 回退到数据库查询 |
|
||||
| 队列积压 | 背压控制 + 告警 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 安全规范 / Security
|
||||
|
||||
### 5.1 基础安全 / Basic Security
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|-----------|---------------------------------------------------------------|
|
||||
| 密钥管理 | Never hardcode secrets or API keys; use environment variables |
|
||||
| 输入验证 | Always validate and sanitize user input |
|
||||
| SQL 注入 | Use parameterized queries (sqlx handles this automatically) |
|
||||
| XSS 防护 | Escape output; use Content-Security-Policy headers |
|
||||
| CSRF 防护 | Use CSRF tokens for state-changing operations |
|
||||
| 密码安全 | Argon2 hashing with session-scoped RSA-2048 OAEP-SHA256 |
|
||||
| 2FA | TOTP with HMAC-SHA1, base32 secrets, backup codes |
|
||||
|
||||
### 5.2 OWASP Top 10 防护 / OWASP Top 10 Protection
|
||||
|
||||
| 风险 / Risk | 防护措施 / Mitigation |
|
||||
|-----------|------------------------------------------------------|
|
||||
| 注入 | Parameterized queries, input validation |
|
||||
| 失效认证 | Strong password policy, 2FA, session management |
|
||||
| 敏感数据暴露 | Encryption at rest and in transit, data masking |
|
||||
| XML 外部实体 | Disable XML external entity processing |
|
||||
| 失效访问控制 | Role-based access control, resource ownership checks |
|
||||
| 安全配置错误 | Secure defaults, environment-based config |
|
||||
| XSS | Output encoding, CSP headers |
|
||||
| 不安全反序列化 | Validate serialized data, use safe formats |
|
||||
| 使用含漏洞组件 | Regular dependency updates, `cargo audit` |
|
||||
| 日志和监控不足 | Comprehensive logging, alerting |
|
||||
|
||||
### 5.3 企业级安全 / Enterprise Security
|
||||
|
||||
| 要求 / Requirement | 说明 / Description |
|
||||
|------------------|----------------------------------------------------------------------|
|
||||
| 安全审计日志 | Log all sensitive operations with actor, action, resource, timestamp |
|
||||
| 访问控制 | Implement RBAC/ABAC; check permissions at service layer |
|
||||
| 数据脱敏 | Mask PII in logs; encrypt sensitive fields in database |
|
||||
| 依赖安全 | Run `cargo audit` in CI; review new dependencies |
|
||||
| 安全头 | Set HSTS, X-Frame-Options, X-Content-Type-Options, etc. |
|
||||
| 速率限制 | Implement rate limiting for auth endpoints and API calls |
|
||||
|
||||
---
|
||||
|
||||
## 6. 数据库规范 / Database
|
||||
|
||||
### 6.1 基础规范 / Basic Rules
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|-----------|----------------------------------------------------------------------|
|
||||
| 参数化查询 | Always use parameterized queries (sqlx does this by default) |
|
||||
| 事务管理 | Use `ServiceContext::run_in_transaction()` for multi-step operations |
|
||||
| 读写分离 | Use `AppDatabase` read/write pool methods appropriately |
|
||||
| 迁移规范 | All schema changes must go through migration files in `migrate/` |
|
||||
|
||||
### 6.2 性能优化 / Performance Optimization
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|-----------|----------------------------------------------------------------------|
|
||||
| N+1 防护 | Use `JOIN` or batch queries instead of N+1 patterns |
|
||||
| 批量操作 | Use `INSERT ... ON CONFLICT`, `UPDATE ... FROM`, bulk operations |
|
||||
| 索引规范 | Add indexes for frequently queried columns; document index rationale |
|
||||
| 查询分析 | Use `EXPLAIN ANALYZE` to verify query plans for complex queries |
|
||||
| 连接池 | Configure pool sizes based on workload; monitor connection usage |
|
||||
| 慢查询 | Log queries >100ms; investigate and optimize |
|
||||
|
||||
### 6.3 数据一致性 / Data Consistency
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|-----------|-----------------------------------------------------------|
|
||||
| 事务边界 | Keep transactions short; avoid long-running transactions |
|
||||
| 幂等性 | Design operations to be idempotent where possible |
|
||||
| 乐观锁 | Use version columns for concurrent update protection |
|
||||
| 外键约束 | Use database-level foreign keys for referential integrity |
|
||||
|
||||
---
|
||||
|
||||
## 7. API 设计规范 / API Design
|
||||
|
||||
### 7.1 RESTful 规范 / RESTful Conventions
|
||||
|
||||
| 规则 / Rule | 示例 / Example |
|
||||
|-----------|-----------------------------------------------------------------------------------------|
|
||||
| 资源命名 | `/api/v1/workspaces/{id}/repos` (复数名词) |
|
||||
| HTTP 方法 | GET (读取), POST (创建), PUT/PATCH (更新), DELETE (删除) |
|
||||
| 状态码 | 200 (成功), 201 (创建), 204 (无内容), 400 (客户端错误), 401 (未认证), 403 (禁止), 404 (未找到), 500 (服务器错误) |
|
||||
| 版本管理 | URL path versioning: `/api/v1/...` |
|
||||
|
||||
### 7.2 响应格式 / Response Format
|
||||
|
||||
```rust
|
||||
// 统一响应类型
|
||||
// Unified response types
|
||||
ApiResponse<T> // 单个数据 / Single payload
|
||||
ApiListResponse<T> // 分页列表 / Paginated list { data, total, page, per_page }
|
||||
ApiEmptyResponse // 空响应 / Empty response
|
||||
ApiErrorResponse // 错误响应 / Error response { code, message, details }
|
||||
```
|
||||
|
||||
### 7.3 OpenAPI 文档 / OpenAPI Documentation
|
||||
|
||||
```rust
|
||||
// 每个端点必须添加 OpenAPI 注解
|
||||
// Every endpoint must have OpenAPI annotations
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/v1/auth/login",
|
||||
request_body = LoginReq,
|
||||
responses(
|
||||
(status = 200, description = "Login successful", body = ApiResponse<LoginResp>),
|
||||
(status = 401, description = "Invalid credentials", body = ApiErrorResponse)
|
||||
),
|
||||
tag = "auth"
|
||||
)]
|
||||
pub async fn login(...) -> HttpResponse { ... }
|
||||
```
|
||||
|
||||
### 7.4 API 治理 / API Governance
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|---|---|
|
||||
| 请求验证 | Validate all request bodies and query parameters |
|
||||
| 速率限制 | Apply rate limiting to auth and resource-intensive endpoints |
|
||||
| 幂等性 | POST operations with same idempotency key should produce same result |
|
||||
| 缓存策略 | Use ETag/Last-Modified for cacheable resources |
|
||||
| 错误码体系 | Consistent error codes across all endpoints |
|
||||
| 分页 | Default page size 20, max 100; use cursor-based pagination for large datasets |
|
||||
|
||||
---
|
||||
|
||||
## 8. 日志与可观测性 / Logging & Observability
|
||||
|
||||
### 8.1 日志规范 / Logging Standards
|
||||
|
||||
```rust
|
||||
// 使用 tracing crate 进行结构化日志
|
||||
// Use tracing crate for structured logging
|
||||
use tracing::{info, warn, error, debug, instrument};
|
||||
|
||||
#[instrument(skip(db), fields(user_id = %req.user_id))]
|
||||
pub async fn create_user(req: CreateUserReq) -> AppResult<User> {
|
||||
info!("Creating new user");
|
||||
// ...
|
||||
error!(error = %err, "Failed to create user");
|
||||
}
|
||||
```
|
||||
|
||||
| 级别 / Level | 用途 / Usage |
|
||||
|---|---|
|
||||
| `error` | 错误需要立即关注 / Errors requiring immediate attention |
|
||||
| `warn` | 异常但可恢复的情况 / Abnormal but recoverable situations |
|
||||
| `info` | 关键业务操作记录 / Key business operation records |
|
||||
| `debug` | 开发调试信息 / Development debugging info |
|
||||
| `trace` | 详细执行路径 / Detailed execution paths |
|
||||
|
||||
### 8.2 敏感信息脱敏 / Data Masking
|
||||
|
||||
| 数据类型 / Data Type | 脱敏规则 / Masking Rule |
|
||||
|---|---|
|
||||
| 密码 | 完全隐藏 / Never log |
|
||||
| Token/密钥 | 只显示前 4 位 / Show first 4 chars only |
|
||||
| 邮箱 | `u***@example.com` |
|
||||
| IP 地址 | 保留网段 / Keep subnet |
|
||||
| 个人信息 | 根据最小必要原则 / Minimum necessary principle |
|
||||
|
||||
### 8.3 性能指标 / Metrics
|
||||
|
||||
| 指标 / Metric | 说明 / Description |
|
||||
|---|---|
|
||||
| 请求延迟 | HTTP request latency (P50, P95, P99) |
|
||||
| 错误率 | Error rate by endpoint and status code |
|
||||
| 吞吐量 | Requests per second |
|
||||
| 数据库连接 | Active/idle connections in pool |
|
||||
| 缓存命中率 | Cache hit/miss ratio |
|
||||
| 队列积压 | Queue depth and processing rate |
|
||||
| 内存使用 | Heap usage, allocation rate |
|
||||
| 活跃会话 | Active WebSocket sessions |
|
||||
|
||||
### 8.4 健康检查 / Health Checks
|
||||
|
||||
```rust
|
||||
// 端点: GET /health
|
||||
// Endpoint: GET /health
|
||||
{
|
||||
"status": "healthy", // healthy | degraded | unhealthy
|
||||
"version": "1.0.0",
|
||||
"uptime": 3600,
|
||||
"checks": {
|
||||
"database": { "status": "up", "latency_ms": 5 },
|
||||
"redis": { "status": "up", "latency_ms": 2 },
|
||||
"nats": { "status": "up", "latency_ms": 1 },
|
||||
"etcd": { "status": "up", "latency_ms": 3 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8.5 告警规则 / Alerting Rules
|
||||
|
||||
| 条件 / Condition | 级别 / Level |
|
||||
|---|---|
|
||||
| 错误率 > 5% | Critical |
|
||||
| P99 延迟 > 500ms | Warning |
|
||||
| 数据库连接池 > 80% | Warning |
|
||||
| 队列积压 > 1000 | Critical |
|
||||
| 内存使用 > 85% | Warning |
|
||||
| 健康检查失败 | Critical |
|
||||
|
||||
### 8.6 请求链路追踪 / Request Tracing
|
||||
|
||||
```rust
|
||||
// 每个请求分配唯一 trace_id
|
||||
// Each request gets a unique trace_id
|
||||
tracing::info!(
|
||||
trace_id = %request_id,
|
||||
user_id = %session.user_id,
|
||||
method = %req.method(),
|
||||
path = %req.path(),
|
||||
"Request started"
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 性能规范 / Performance
|
||||
|
||||
### 9.1 SLA 目标 / SLA Targets
|
||||
|
||||
| 指标 / Metric | 目标 / Target |
|
||||
|---|---|
|
||||
| 可用性 | 99.9% (每月宕机 <43 分钟) |
|
||||
| P50 延迟 | <50ms |
|
||||
| P95 延迟 | <200ms |
|
||||
| P99 延迟 | <500ms |
|
||||
| 错误率 | <0.1% |
|
||||
| 数据库查询 | <100ms (常规查询) |
|
||||
| 缓存命中率 | >90% |
|
||||
|
||||
### 9.2 性能原则 / Performance Principles
|
||||
|
||||
| 原则 / Principle | 说明 / Description |
|
||||
|---|---|
|
||||
| 基准测试 | Establish performance baselines before optimization |
|
||||
| 测量优先 | Profile before optimizing; don't guess |
|
||||
| 渐进优化 | Optimize iteratively; measure impact of each change |
|
||||
| 容量规划 | Plan for 3x current load |
|
||||
|
||||
### 9.3 优化策略 / Optimization Strategies
|
||||
|
||||
| 场景 / Scenario | 策略 / Strategy |
|
||||
|---|---|
|
||||
| 热点查询 | Add caching (L1 + L2) |
|
||||
| 大量读取 | Use read replicas |
|
||||
| 批量操作 | Batch database operations |
|
||||
| 高并发 | Use connection pooling, async I/O |
|
||||
| 大数据量 | Use cursor-based pagination |
|
||||
|
||||
---
|
||||
|
||||
## 10. 测试规范 / Testing
|
||||
|
||||
### 10.1 基础要求 / Basic Requirements
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|---|---|
|
||||
| 新功能 | All new features must have unit tests |
|
||||
| Bug 修复 | Bug fixes must include regression tests |
|
||||
| 关键路径 | Critical business logic must have integration tests |
|
||||
| 测试隔离 | Tests must be independent and not depend on execution order |
|
||||
|
||||
### 10.2 测试命令 / Test Commands
|
||||
|
||||
```bash
|
||||
cargo test # 运行所有测试 / Run all tests
|
||||
cargo test -- <test_name> # 按名称运行 / Run by name
|
||||
cargo test lru::tests # 运行特定模块 / Run module tests
|
||||
cargo test -- --nocapture # 显示输出 / Show output
|
||||
```
|
||||
|
||||
### 10.3 测试命名 / Test Naming
|
||||
|
||||
```rust
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_create_user_with_valid_input() { ... }
|
||||
|
||||
#[test]
|
||||
fn test_create_user_with_duplicate_email_returns_error() { ... }
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_async_operation_handles_timeout() { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Git 规范 / Git Workflow
|
||||
|
||||
### 11.1 提交信息格式 / Commit Message Format
|
||||
|
||||
使用 Angular 风格,全部英文:
|
||||
|
||||
Use Angular style, all English:
|
||||
|
||||
```
|
||||
<type>(<scope>): <subject>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer]
|
||||
```
|
||||
|
||||
| Type | 说明 / Description |
|
||||
|---|---|
|
||||
| `feat` | 新功能 / New feature |
|
||||
| `fix` | Bug 修复 / Bug fix |
|
||||
| `refactor` | 重构 / Code refactoring |
|
||||
| `docs` | 文档 / Documentation |
|
||||
| `test` | 测试 / Tests |
|
||||
| `chore` | 构建/工具 / Build/tooling |
|
||||
| `perf` | 性能优化 / Performance improvement |
|
||||
| `style` | 代码格式 / Code formatting |
|
||||
| `ci` | CI/CD 相关 / CI/CD changes |
|
||||
|
||||
**示例 / Examples:**
|
||||
```
|
||||
feat(auth): add 2FA login support
|
||||
fix(api): resolve race condition in user creation
|
||||
refactor(service): extract common validation logic
|
||||
docs(readme): update API documentation
|
||||
test(cache): add unit tests for LRU eviction
|
||||
chore(deps): update sqlx to 0.8
|
||||
```
|
||||
|
||||
### 11.2 提交原则 / Commit Principles
|
||||
|
||||
| 原则 / Principle | 说明 / Description |
|
||||
|---|---|
|
||||
| 原子提交 | Each commit should address one concern |
|
||||
| 完整性 | Each commit should leave the codebase in a working state |
|
||||
| 禁止强制推送 | Never force push to main branch |
|
||||
| 提交前检查 | Run `cargo check` and `cargo test` before committing |
|
||||
|
||||
### 11.3 分支策略 / Branch Strategy
|
||||
|
||||
| 分支 / Branch | 用途 / Purpose |
|
||||
|---|---|
|
||||
| `main` | 生产就绪代码 / Production-ready code |
|
||||
| `feat/*` | 功能开发 / Feature development |
|
||||
| `fix/*` | Bug 修复 / Bug fixes |
|
||||
| `release/*` | 发布准备 / Release preparation |
|
||||
|
||||
---
|
||||
|
||||
## 12. 工作流程 / Workflow
|
||||
|
||||
### 12.1 开发流程 / Development Process
|
||||
|
||||
1. **理解先于编写** — Read before write; understand context first
|
||||
2. **最小变更** — Minimal changes; don't refactor unrelated code
|
||||
3. **验证变更** — Verify after changes; run tests or check output
|
||||
4. **文档同步** — Update documentation when changing public APIs
|
||||
|
||||
### 12.2 AI 助手工作规范 / AI Assistant Guidelines
|
||||
|
||||
| 规则 / Rule | 说明 / Description |
|
||||
|---|---|
|
||||
| 先读后写 | Always read existing code before making changes |
|
||||
| 最小侵入 | Make minimal changes; don't refactor unrelated code |
|
||||
| 验证结果 | Run `cargo check` or `cargo test` after changes |
|
||||
| 解释变更 | Explain what you changed and why |
|
||||
| 询问不确定 | Ask when unsure about requirements |
|
||||
|
||||
### 12.3 常用命令 / Common Commands
|
||||
|
||||
```bash
|
||||
cargo build # 构建 / Build
|
||||
cargo check # 快速检查 / Quick check
|
||||
cargo test # 运行测试 / Run tests
|
||||
cargo clippy # Lint 检查 / Lint checks
|
||||
cargo fmt # 格式化 / Format code
|
||||
cargo doc --no-deps # 生成文档 / Build docs
|
||||
cargo machete # 检查未使用依赖 / Check unused deps
|
||||
cargo run --bin gen_openapi # 生成 OpenAPI / Generate OpenAPI
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 13. 架构决策记录 / ADR
|
||||
|
||||
架构决策记录存放在 `docs/adr/` 目录下,使用 Markdown 格式。
|
||||
|
||||
Architecture Decision Records are stored in `docs/adr/` directory in Markdown format.
|
||||
|
||||
### 索引 / Index
|
||||
|
||||
| ADR | 标题 / Title | 状态 / Status |
|
||||
|---|---|---|
|
||||
| [ADR-001](docs/adr/001-choice-of-web-framework.md) | 选择 Actix-web 作为 Web 框架 | Accepted |
|
||||
| [ADR-002](docs/adr/002-two-tier-caching.md) | 两级缓存架构 (L1 LRU + L2 Redis) | Accepted |
|
||||
| [ADR-003](docs/adr/003-nats-for-messaging.md) | 使用 NATS JetStream 作为消息队列 | Accepted |
|
||||
| [ADR-004](docs/adr/004-etcd-for-discovery.md) | 使用 etcd 进行服务发现 | Accepted |
|
||||
| [ADR-005](docs/adr/005-error-handling-strategy.md) | 统一错误处理策略 | Accepted |
|
||||
|
||||
### ADR 模板 / ADR Template
|
||||
|
||||
```markdown
|
||||
# ADR-NNN: 标题 / Title
|
||||
|
||||
## 状态 / Status
|
||||
Accepted | Superseded | Deprecated
|
||||
|
||||
## 背景 / Context
|
||||
描述问题背景 / Describe the context
|
||||
|
||||
## 决策 / Decision
|
||||
描述做出的决策 / Describe the decision
|
||||
|
||||
## 后果 / Consequences
|
||||
描述正面和负面影响 / Describe positive and negative impacts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. 审查清单 / Review Checklist
|
||||
|
||||
### 代码审查 / Code Review
|
||||
|
||||
- [ ] 代码风格符合项目规范 / Code style follows project conventions
|
||||
- [ ] 没有使用禁止模式 / No forbidden patterns used
|
||||
- [ ] 错误处理完整 / Error handling is complete
|
||||
- [ ] 安全考虑已处理 / Security considerations addressed
|
||||
- [ ] 性能影响已评估 / Performance impact assessed
|
||||
- [ ] 测试已添加 / Tests are added
|
||||
- [ ] 文档已更新 / Documentation is updated
|
||||
|
||||
### PR 审查 / PR Review
|
||||
|
||||
- [ ] 提交信息符合 Angular 风格 / Commit messages follow Angular style
|
||||
- [ ] 每个提交只关注一个问题 / Each commit addresses one concern
|
||||
- [ ] 变更范围合理 / Change scope is reasonable
|
||||
- [ ] 没有遗留的 TODO/FIXME / No leftover TODO/FIXME
|
||||
- [ ] CI 检查通过 / CI checks pass
|
||||
|
||||
### 发布前审查 / Pre-release Review
|
||||
|
||||
- [ ] 所有测试通过 / All tests pass
|
||||
- [ ] 性能测试完成 / Performance tests completed
|
||||
- [ ] 安全扫描通过 / Security scan passed
|
||||
- [ ] 文档完整 / Documentation is complete
|
||||
- [ ] 变更日志已更新 / Changelog is updated
|
||||
|
||||
---
|
||||
|
||||
## 附录 / Appendix
|
||||
|
||||
### 项目架构速查 / Quick Architecture Reference
|
||||
|
||||
```
|
||||
appks — 协作开发平台后端 / Collaborative Development Platform Backend
|
||||
|
||||
config/ → 环境配置 / Environment configuration
|
||||
models/ → 数据模型 / Data models (sqlx FromRow)
|
||||
service/ → 业务逻辑 / Business logic (AppService)
|
||||
api/ → HTTP 端点 / HTTP endpoints
|
||||
immediate/ → 实时 IM / Real-time IM (WebSocket)
|
||||
cache/ → 两级缓存 / Two-tier cache (L1 + L2)
|
||||
storage/ → 对象存储 / Object storage (S3)
|
||||
queue/ → 消息队列 / Message queue (NATS)
|
||||
etcd/ → 服务发现 / Service discovery
|
||||
session/ → 会话管理 / Session management
|
||||
pb/ → gRPC 客户端 / gRPC client stubs
|
||||
proto/ → Protobuf 定义 / Protobuf definitions
|
||||
migrate/ → 数据库迁移 / Database migrations
|
||||
error.rs → 统一错误类型 / Unified error types
|
||||
```
|
||||
|
||||
### 基础设施速查 / Infrastructure Quick Reference
|
||||
|
||||
| 服务 / Service | 用途 / Purpose | 协议 / Protocol |
|
||||
|--------------|-----------------------------------------|---------------|
|
||||
| Postgres | 主数据库 / Primary database | sqlx |
|
||||
| Redis | 缓存/会话/限流 / Cache/sessions/rate limiting | redis + r2d2 |
|
||||
| etcd | 服务发现 / Service discovery | etcd-client |
|
||||
| NATS | 消息队列 / Message queue | async-nats |
|
||||
| S3/MinIO | 对象存储 / Object storage | object_store |
|
||||
| Qdrant | 向量数据库 / Vector DB | config only |
|
||||
|
||||
---
|
||||
|
||||
*This document is maintained by the development team. For questions or suggestions, please open an issue.*
|
||||
Reference in New Issue
Block a user