关于 infrastructure-documenter
面向工程与运维团队的基础设施文档编写技能,提供架构说明、运行手册、API 文档和决策记录等模板与实践,并涵盖文档即代码。
主要功能
- 01架构文档与图表
- 02事件运行手册
- 03API 与环境文档
- 04架构决策记录
- 05文档即代码实践
适用场景
- 01记录系统组件与数据流
- 02编写故障排查和恢复步骤
- 03建立 API 与环境参考文档
- 04规划文档目录和自动生成流程
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jmsktm/ claude-settings --skill infrastructure-documenter安装后在 Claude Code 中输入/infrastructure-documenter确认已加载。
详细介绍
基础设施文档编写技能
概述
此技能可帮助你创建清晰、易维护的基础设施文档,涵盖架构图、运行手册、系统文档、运维流程以及文档即代码实践。
文档理念
原则
- 持续更新的文档:确保文档与实际情况同步
- 关注受众:为不同读者编写不同文档
- 可执行:每份文档都应帮助读者完成某项工作
- 版本控制:使用代码变更追踪文档变更
文档类型
| 类型 | 受众 | 用途 |
|---|---|---|
| 架构 | 工程师 | 了解系统设计 |
| 运行手册 | 运维/SRE | 处理事故 |
| API 文档 | 开发者 | 与系统集成 |
| 入职指南 | 新员工 | 快速熟悉工作 |
| 决策记录 | 未来的你 | 了解决策原因 |
架构文档
系统架构概览
# System Architecture
## Overview
[Project Name] is a [type] application that [purpose].
## High-Level Architecture
┌─────────────────────────────────────────────────────────────┐ │ Users │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Vercel Edge │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ Next.js App │ │ Edge Functions │ │ │ └─────────────────┘ └─────────────────┘ │ └─────────────────────────────────────────────────────────────┘ │ ┌───────────────┼───────────────┐ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Supabase │ │ Redis │ │ Stripe │ │ - PostgreSQL │ │ - Session │ │ - Payments │ │ - Auth │ │ - Cache │ │ - Webhooks │ │ - Realtime │ │ │ │ │ │ - Storage │ │ │ │ │ └─────────────────┘ └─────────────────┘ └─────────────────┘
## Components
### Frontend (Next.js App)
- **Location**: Vercel Edge Network
- **Framework**: Next.js 14 (App Router)
- **Styling**: Tailwind CSS + shadcn/ui
- **State**: Zustand + React Query
### Backend Services
| Service | Provider | Purpose |
|---------|----------|---------|
| Database | Supabase | PostgreSQL with RLS |
| Auth | Supabase Auth | User authentication |
| Storage | Supabase Storage | File uploads |
| Cache | Upstash Redis | Session & API cache |
| Payments | Stripe | Subscriptions |
| Email | Resend | Transactional emails |
### Data Flow
1. User request → Vercel Edge
2. SSR/API Route processes request
3. Database queries via Supabase client
4. Response cached at edge (when applicable)
5. Response returned to user
## Security
### Authentication Flow
1. User signs in via Supabase Auth
2. JWT token issued and stored in cookie
3. Server validates token on each request
4. RLS policies enforce data access
### Data Protection
- All data encrypted at rest (AES-256)
- TLS 1.3 for data in transit
- Secrets stored in Vercel environment
- PII fields encrypted in database
Mermaid 图表
## Request Flow
```mermaid
sequenceDiagram
participant U as User
participant V as Vercel
participant N as Next.js
participant S as Supabase
participant R as Redis
U->>V: HTTPS Request
V->>N: Route to App
alt Cached Response
N->>R: Check Cache
R-->>N: Cache Hit
N-->>U: Return Cached
else Cache Miss
N->>S: Query Database
S-->>N: Data
N->>R: Store in Cache
N-->>U: Return Response
end
数据库架构
erDiagram
users ||--o{ projects : owns
users {
uuid id PK
text email
text name
timestamp created_at
}
projects ||--o{ tasks : contains
projects {
uuid id PK
uuid user_id FK
text name
text status
}
tasks {
uuid id PK
uuid project_id FK
text title
boolean completed
}
## Runbooks
### Runbook Template
```markdown
# Runbook: [Service Name] - [Issue Type]
## Overview
Brief description of the issue and when this runbook applies.
## Severity
- **P1 (Critical)**: Complete outage
- **P2 (High)**: Degraded service
- **P3 (Medium)**: Minor impact
- **P4 (Low)**: No user impact
## Detection
How this issue is typically detected:
- [ ] Alert from [monitoring system]
- [ ] User report
- [ ] Automated check failure
## Impact Assessment
- **Users affected**: All / Segment / None
- **Data at risk**: Yes / No
- **Revenue impact**: High / Medium / Low / None
## Prerequisites
- [ ] Access to [system/dashboard]
- [ ] Credentials for [service]
- [ ] Contact info for [team/person]
## Resolution Steps
### Step 1: Verify the Issue
```bash
# Check service status
curl -I https://api.example.com/health
# Check logs
vercel logs --follow
步骤 2:确定根本原因
常见原因:
- 数据库连接池耗尽
- 达到内存上限
- 外部服务宕机
- 部署不当
步骤 3:应用修复
如果是数据库问题:
# Check connection count
SELECT count(*) FROM pg_stat_activity;
# Kill idle connections
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle' AND query_start < now() - interval '1 hour';
如果是部署不当:
# Rollback to previous deployment
vercel rollback
步骤 4:验证修复
# Check service health
curl https://api.example.com/health
# Monitor error rates for 15 minutes
升级处理
如果 30 分钟内无法解决:
- 呼叫值班工程师:[contact]
- 在 #incidents 中通知相关方
- 更新状态页
事故后续
- 创建事故报告
- 安排事后复盘(仅限 P1/P2)
- 如有需要,更新此运行手册
相关链接
### Database Runbooks
```markdown
# Runbook: Database Performance Issues
## Symptoms
- Slow API responses (>1s)
- Timeout errors in logs
- High database CPU in dashboard
## Quick Checks
### 1. Check Active Connections
```sql
SELECT
state,
count(*),
max(now() - query_start) as max_duration
FROM pg_stat_activity
GROUP BY state;
2. 查找长时间运行的查询
SELECT
pid,
now() - query_start AS duration,
query
FROM pg_stat_activity
WHERE state = 'active'
AND now() - query_start > interval '30 seconds'
ORDER BY duration DESC;
3. 检查表大小
SELECT
schemaname,
tablename,
pg_size_pretty(pg_total_relation_size(schemaname || '.' || tablename)) as size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname || '.' || tablename) DESC
LIMIT 10;
4. 检查缺失的索引
SELECT
relname,
seq_scan,
idx_scan,
seq_scan - idx_scan AS difference
FROM pg_stat_user_tables
WHERE seq_scan > idx_scan
ORDER BY difference DESC;
解决方案
终止问题查询
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE pid = [PID_FROM_ABOVE];
添加缺失的索引
CREATE INDEX CONCURRENTLY idx_table_column
ON table_name (column_name);
## Decision Records (ADRs)
### ADR Template
```markdown
# ADR-001: Choose Supabase for Database
## Status
Accepted
## Context
We need a database solution for [Project Name] that supports:
- PostgreSQL compatibility
- Real-time subscriptions
- Built-in authentication
- Easy local development
- Generous free tier
## Decision
We will use Supabase as our primary database and auth provider.
## Alternatives Considered
### PlanetScale
**Pros:**
- Excellent scaling
- Branching for schema changes
- MySQL compatible
**Cons:**
- No built-in auth
- No real-time subscriptions
- Additional services needed
### Firebase
**Pros:**
- Real-time built-in
- Mature platform
- Good mobile SDKs
**Cons:**
- NoSQL (not ideal for our use case)
- Vendor lock-in concerns
- Complex security rules
## Consequences
### Positive
- Single provider for DB + Auth + Storage
- Great developer experience
- Row Level Security for data protection
- Local development with supabase CLI
### Negative
- PostgreSQL-specific features tie us to provider
- Supabase still maturing (some rough edges)
- Limited to their managed offering
### Risks
- Supabase scaling limitations at high traffic
- Migration cost if we need to move
## References
- [Supabase Documentation](https://supabase.com/docs)
- [Comparison: Supabase vs Firebase](https://...)
API 文档
端点文档
# API Reference
## Base URL
生产环境:https://api.example.com/v1 预发布环境:https://staging-api.example.com/v1
## Authentication
All API requests require authentication via Bearer token.
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://api.example.com/v1/users
端点
用户
获取当前用户
GET /users/me
响应:
{
"id": "usr_123",
"email": "[email protected]",
"name": "John Doe",
"created_at": "2024-01-01T00:00:00Z"
}
更新用户
PATCH /users/me
请求正文:
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
| name | string | 否 | 显示名称 |
| avatar_url | string | 否 | 个人资料图片 URL |
示例:
curl -X PATCH \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "Jane Doe"}' \
https://api.example.com/v1/users/me
错误响应
| 状态 | 代码 | 描述 |
|---|---|---|
| 400 | BAD_REQUEST | 请求正文无效 |
| 401 | UNAUTHORIZED | 缺少令牌或令牌无效 |
| 403 | FORBIDDEN | 权限不足 |
| 404 | NOT_FOUND | 未找到资源 |
| 429 | RATE_LIMITED | 请求过多 |
| 500 | INTERNAL_ERROR | 服务错误 |
错误响应格式:
{
"error": {
"code": "NOT_FOUND",
"message": "User not found"
}
}
## Environment Documentation
### Environment Matrix
```markdown
# Environments
## Overview
| Environment | URL | Purpose | Deploy |
|-------------|-----|---------|--------|
| Production | https://myapp.com | Live users | Manual (main) |
| Staging | https://staging.myapp.com | Pre-release testing | Auto (main) |
| Preview | https://pr-*.vercel.app | PR review | Auto (PR) |
| Development | http://localhost:3000 | Local dev | Manual |
## Configuration
### Production
```env
NODE_ENV=production
DATABASE_URL=[Supabase Production]
NEXT_PUBLIC_APP_URL=https://myapp.com
预发布环境
NODE_ENV=production
DATABASE_URL=[Supabase Staging Branch]
NEXT_PUBLIC_APP_URL=https://staging.myapp.com
开发环境
NODE_ENV=development
DATABASE_URL=[Local Supabase]
NEXT_PUBLIC_APP_URL=http://localhost:3000
访问权限
生产环境
- Vercel:仅限管理员
- 数据库:开发人员只读,管理员可写
- 日志:所有工程师
预发布环境
- Vercel:所有工程师
- 数据库:所有工程师
- 日志:所有工程师
密钥轮换
| 密钥 | 轮换周期 | 上次轮换时间 |
|---|---|---|
| 数据库密码 | 90 天 | 2024-01-15 |
| API 密钥 | 90 天 | 2024-01-15 |
| JWT 密钥 | 从不 | 初始设置 |
## Documentation-as-Code
### Documentation Structure
docs/ ├── README.md # 文档索引 ├── architecture/ │ ├── overview.md # 系统架构 │ ├── data-flow.md # 数据流图 │ └── decisions/ # ADR │ ├── 001-database.md │ └── 002-hosting.md ├── runbooks/ │ ├── README.md # 运维手册索引 │ ├── database.md # 数据库问题 │ ├── deployment.md # 部署问题 │ └── outage.md # 服务中断 ├── api/ │ └── reference.md # API 文档 └── onboarding/ ├── setup.md # 本地设置 └── contributing.md # 如何贡献
### Auto-Generated Documentation
```yaml
# .github/workflows/docs.yml
name: Generate Docs
on:
push:
branches: [main]
paths:
- 'src/**'
- 'docs/**'
jobs:
generate-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Generate API docs from OpenAPI
run: |
npx @redocly/cli build-docs openapi.yaml \
--output docs/api/index.html
- name: Generate TypeDoc
run: npx typedoc --out docs/api/typescript
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs
文档检查清单
架构文档
- 系统概览图
- 组件说明
- 数据流文档
- 安全架构
- 技术决策(ADR)
运维文档
- 常见问题的运维手册
- 部署流程
- 监控与告警
- 事件响应计划
- 值班流程
开发者文档
- 本地设置指南
- API 参考
- 贡献指南
- 代码规范
- 测试指南
维护
- 文档审查计划
- 指定负责人
- 定义变更流程
- 版本管理策略
何时使用此技能
在以下情况下调用此技能:
- 创建架构文档
- 编写运维手册
- 记录决策理由(ADR)
- 设置文档结构
- 创建入职材料
- 构建自动化文档
- 规划事件响应流程