Files
ssw-ontology/docs/BACKUP.md
T

91 lines
3.7 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.
# 数据备份(v1.3.0,按 schema 镜像 + 请求级切库)
让 AI 客户端敢操作的关键能力:**写前打个保险 → 改坏了能从快照读原样**。
## 一句话工作流
1. **改前**:`POST /api/v1/backups` 打一份快照 → 拿到 `id=42`
2. **改活库**:`POST /api/v1/objects {pk: ...}` 写入
4. **改后想确认范围**:再读 `GET /api/v1/backups` / `GET /api/v1/backups/42` 看元信息
4. **想看「改前长什么样」**?带 `X-Snapshot-Id: 42` 头查同一接口 → 命中快照库(不是活库)
## 核心机制
每个备份 = 一个**独立 schema** `backups_<id>`,包含 23张业务表的同结构副本 + 一致的 `INSERT...SELECT` 数据。
读请求带 `X-Snapshot-Id` 时:
- snapshotRouter 中间件 `BeginTx` + `SET LOCAL search_path TO backups_42, public`
- 把 `a.pool` 字段临时换为 `*txPool`(事务视图)
- **业务代码 `a.pool.Query / .QueryRow / .Exec` 一行不改**,自动走事务视图
- handler 结束 → commit + 还原 `a.pool`
**写方法(POST/PUT/PATCH/DELETE)带快照头 → 403 拒绝**(mistake-safety)。
> **注**:v1.5.0 之前创建的备份快照 schema 无 `iri` 列,对旧快照做 schema 类读取(`/ontology/object-types` 等)会报错,需重新备份;实例数据不受影响。
## 接口清单
| 接口 | 方法 | 用途 |
|---|---|---|
| `POST /api/v1/backups` | 创建快照 | body `{name?, notes?}` |
| `GET /api/v1/backups` | 列表 | `?limit=50&offset=0` |
| `GET /api/v1/backups/:id` | 元信息 | 含 `schema_name=backups_<id>` |
| `GET /api/v1/backups/:id/switch` | 切库提示 | 返回「下次请求带什么头」 |
| `DELETE /api/v1/backups/:id` | 级联删 schema | 清理用 |
全部需要 manager 主体(`X-Principal: manager` 或登录 session)。
## 切库方法(任意 HTTP 请求通用)
```
X-Snapshot-Id: 42 # 直接 run id
X-Snapshot-Ts: 1700000000 # 秒级时间戳 → EXTRACT(EPOCH FROM created_at) <= ts 的最近 run
```
任一即可(同时带时以 ID 优先)。响应头会回 `X-Snapshot-Active: backups_42` 确认当前生效的 schema。
GET / HEAD / OPTIONS 才能切,写方法带快照头直接 403。
## MCP 工具
工具集(5 个):
```
backup_create({name?, notes?}) # 创建快照
backup_list({limit?, offset?}) # 列出快照
backup_inspect({id) # 元信息 + schema_name
backup_switch({id) # 切库提示(让 MCP 客户端知道下次该带什么头)
backup_delete({id) # 级联删
```
## 客户端典型用法
```javascript
// 1. 备份
const backup = await mcp.call("backup_create", { name: "before-batch-import" });
const snapId = backup.id;
// 3. 导入一批数据(万一出问题可以快速看原样)
await mcp.call("batch_create_objects", { items: [...] });
// 4. 检查导入是否有问题 — 用快照头对比
const oldView = await mcp.call("query_related", {
type: "Device",
filters: { ... },
/* MCP 客户端 SDK 不直接支持加 HTTP 头,
让 WorkBuddy 把 X-Snapshot-Id 注入下一批只读调用即可 */
});
```
## 不做什么
- **不提供 restore 到线上**:写入回滚极易连锁错位,让客户拿到 dump 自行恢复是更稳的路径。
- **不自动备份**:每次 create/update/delete 不自动触发,让客户端掌握节奏,避免 object_changes 表爆炸。
- **不限制快照数量**:当前默认永久保留,由 `DELETE /backups/:id` 主动清理。
## 测试覆盖
- `go test -short` 跑 11 个纯函数单测
- `go test -tags=integration` 跑 11 个集成测试(含快照路由 4 个 + 备份生命周期 2 个 + 之前治理 5 个)
完整 runbook 见 `docs/TESTING.md`。