「让客户端敢操作」的关键能力:写前/写后打一份快照 → 任意 GET 带 X-Snapshot-Id
头即可命中 backups_<id> schema 的同名表(业务 SQL 不带 schema 前缀照样切)。
设计要点:
- 备份 = 独立 schema backups_<id>(真表,不是单存 JSONB)—— 查询性能与活库一致
- snapshotRouter 中间件:BeginTx + SET LOCAL search_path → 把 a.pool 临时换
为事务视图 txPool → handler 结束 commit + 还原 a.pool。业务代码一行不改。
- a.pool 字段类型从 *pgxpool.Pool 升级为 dbRunner interface(中间件可换 txPool)。
- 11 个 helper 函数签名同步改为 dbExec(与现有 dbExec 共存,无破坏性)。
- 写方法(POST/PUT/PATCH/DELETE)带快照头 → 403 拒绝(mistake-safety)。
接口:
- POST /api/v1/backups 创建
- GET /api/v1/backups 列表
- GET /api/v1/backups/:id 元信息(含 schema_name)
- GET /api/v1/backups/:id/switch 切库提示
- DELETE /api/v1/backups/:id 级联删 schema
- 支持 X-Snapshot-Id (直接 run id) + X-Snapshot-Ts (秒级时间戳) 两种切换入口
MCP 工具 (5 个):backup_create / backup_list / backup_inspect / backup_switch / backup_delete
测试 (22 个全绿,~5.5s 集成):
- SnapshotRouter:改前建快照 → 改后读快照只见改前
- SnapshotSearchPathPersist:不污染下一个请求
- SnapshotByTimestamp:ts 头也能切库
- SnapshotDeleteCleansSchema:delete 真 DROP schema
- BackupLifecycle / BackupDiffAfterMutation:完整 create→list→inspect→switch→delete
文档:docs/BACKUP.md 写清用法、机制、客户端工作流;CHANGELOG.md [1.3.0]。
185 lines
7.0 KiB
Go
185 lines
7.0 KiB
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/jackc/pgx/v5"
|
||
"github.com/jackc/pgx/v5/pgconn"
|
||
)
|
||
|
||
// ============================================================================
|
||
// snapshotRouter:请求级「按 schema 镜像切库」
|
||
//
|
||
// 设计目标:业务代码 a.pool.Query / a.pool.QueryRow / a.pool.Exec 一行不改即可
|
||
// 命中快照库。
|
||
//
|
||
// 实现机制:
|
||
// 1) snapshotMiddleware 读取 X-Snapshot-Id / X-Snapshot-Ts 头,校验快照存在。
|
||
// 2) 校验通过后中间件 BeginTx → SET LOCAL search_path TO <snap_schema>,> public →
|
||
// 关键一步:把 a.pool 字段(指针)**临时替换**为事务视图,handler 结束后还原。
|
||
// 3) 业务代码里所有 a.pool.Query / .QueryRow / .Exec 都自动走事务视图,无前缀
|
||
// 的 SQL 自然命中快照库。
|
||
// 4) 写路径检测:method ∈ {POST, PUT, PATCH, DELETE} + 有快照头 → 403。
|
||
//
|
||
// 不替换 SQL 的物理限制:pgxpool.Pool 与 pgx.Tx 都是 struct,没有共同接口;
|
||
// 业务代码用 `a.pool.Query` 字面引用,要让「池」的行为变成「事务」,只能
|
||
// 把字段替换成自定义结构。该结构实现同样的 Pool / Tx 行为子集:
|
||
// - Query / QueryRow / Exec
|
||
// - Begin(如果业务自己起子事务 — 走外层事务的子 SAVEPOINT)
|
||
// 其它(Close、Stat、Acquire 等))转发到真正的池。
|
||
//
|
||
// 关于一致性:snapshotRouter 包外层事务 → handler 结束 commit。多语句的「读+读」
|
||
// 一致性由事务保证;写操作被 403 拦截在中间件,不会污染事务。
|
||
// ============================================================================
|
||
|
||
// txPool 让 a.pool 字段在中间件期间看起来仍是 *pgxpool.Pool,但实际行为走事务。
|
||
// 直接继承 *pgxpool.Pool 不行(PG Pool 的方法集与 pgx.Tx 不同),所以用一个独立
|
||
// 类型 + 走事务转发。a.pool 是 *pgxpool.Pool 类型,所以中间件把它换成 *txPool。
|
||
// 但**类型替换需要重新声明 a.pool 为 interface**,这就要改 main.go 一处声明。
|
||
// ---
|
||
// 为避免改 app 结构体定义,我们把「池」字段类型从 *pgxpool.Pool 升级为
|
||
// dbRunner interface,txPool 与原 pool 都实现该接口。
|
||
// ============================================================================
|
||
|
||
// dbRunner 是 a.pool 字段的接口类型(替代原 *pgxpool.Pool 直引)。
|
||
// 业务代码继续调 a.pool.Query / a.pool.QueryRow / a.pool.Exec(与方法同名),只要
|
||
// a.pool 字段类型从 *pgxpool.Pool 改为 dbRunner 即可——Go 方法集是结构字段访问
|
||
// 自动走接口分派,**对业务代码完全透明**。
|
||
//
|
||
// dbRunner 是 dbExec 的超集(多了 Begin/BeginTx/Close,给 snapshot_router 切库用)。
|
||
// 业务 helper 函数若只需 Exec/Query/QueryRow,可声明接收 dbExec;a.pool 自动满足。
|
||
type dbRunner interface {
|
||
dbExec
|
||
Begin(ctx context.Context) (pgx.Tx, error)
|
||
BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
|
||
Close()
|
||
}
|
||
|
||
// txPool 把 pgxpool.Pool 包成「事务视图」。所有查询都走同一个外层事务。
|
||
// 设计点:
|
||
// - 业务调 a.pool.Begin 仍能开内层事务(savepoint)。
|
||
// - Close 是 no-op((不能关事务,由中间件统一 commit/rollback)。
|
||
// - Exec / Query / QueryRow 转发到 tx(事务里执行的 SET LOCAL 已生效)。
|
||
type txPool struct {
|
||
tx pgx.Tx
|
||
}
|
||
|
||
func (t *txPool) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
|
||
return t.tx.Query(ctx, sql, args...)
|
||
}
|
||
|
||
func (t *txPool) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
|
||
return t.tx.QueryRow(ctx, sql, args...)
|
||
}
|
||
|
||
func (t *txPool) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {
|
||
return t.tx.Exec(ctx, sql, args...)
|
||
}
|
||
|
||
func (t *txPool) Begin(ctx context.Context) (pgx.Tx, error) {
|
||
return t.tx.Begin(ctx)
|
||
}
|
||
|
||
func (t *txPool) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) {
|
||
// pgx.Tx 不直接暴露 BeginTx;调 Begin(嵌套事务,pgx 自动 savepoint)
|
||
_ = txOptions
|
||
return t.tx.Begin(ctx)
|
||
}
|
||
|
||
func (t *txPool) Close() {
|
||
// no-op;事务在中间件统一提交/回滚
|
||
}
|
||
|
||
// snapshotMiddleware 解析 X-Snapshot-Id / X-Snapshot-Ts,必要时替换 a.db。
|
||
//
|
||
// 步骤:
|
||
// 1) 取头部头(X-Snapshot-Id / X-Snapshot-Ts)
|
||
// 2) 都空 → 放行(默认走活库)
|
||
// 3) 非只读 method → 403(快照模式只读)
|
||
// 4) 解析 schema → 失败 503
|
||
// 5) BeginTx + SET LOCAL search_path → 备份 a.db 原值 → a.db = txPool{tx}
|
||
// 6) c.Next() → 中间件后处理 commit + 还原 a.db
|
||
func (a *app) snapshotMiddleware() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
idStr := c.GetHeader("X-Snapshot-Id")
|
||
tsStr := c.GetHeader("X-Snapshot-Ts")
|
||
if idStr == "" && tsStr == "" {
|
||
c.Next()
|
||
return
|
||
}
|
||
// 写路径直接 403,不开事务、不替换 a.db
|
||
if !isReadMethod(c.Request.Method) {
|
||
c.AbortWithStatusJSON(403, gin.H{
|
||
"error": "快照模式仅支持 GET / HEAD(写操作必须用活库)",
|
||
"method": c.Request.Method,
|
||
"snapshot": idStr + tsStr,
|
||
"hint": "去掉 X-Snapshot-Id / X-Snapshot-Ts 头即可写活库",
|
||
})
|
||
return
|
||
}
|
||
schemaName, snapID, err := a.resolveSnapshotSchema(c, idStr, tsStr)
|
||
if err != nil {
|
||
c.AbortWithStatusJSON(404, gin.H{
|
||
"error": err.Error(),
|
||
"hint": "GET /api/v1/backups 看现有快照 id 列表",
|
||
})
|
||
return
|
||
}
|
||
if schemaName == "" {
|
||
c.Next()
|
||
return
|
||
}
|
||
// 起事务 + 切 schema + 替换 a.db
|
||
tx, err := a.pool.Begin(c)
|
||
if err != nil {
|
||
c.AbortWithStatusJSON(500, gin.H{"error": "起快照事务失败: " + err.Error()})
|
||
return
|
||
}
|
||
if _, err := tx.Exec(c, fmt.Sprintf("SET LOCAL search_path TO %s, public", quoteIdent(schemaName))); err != nil {
|
||
_ = tx.Rollback(c)
|
||
c.AbortWithStatusJSON(500, gin.H{"error": "SET LOCAL search_path 失败: " + err.Error()})
|
||
return
|
||
}
|
||
// 替换字段:业务代码 a.pool 仍写 a.pool,但 Go 接口分派走 txPool
|
||
origDB := a.pool
|
||
a.pool = &txPool{tx: tx}
|
||
c.Set("__snapshot_id", snapID)
|
||
c.Header("X-Snapshot-Active", schemaName)
|
||
|
||
// handler 跑完后 commit + 还原
|
||
defer func() {
|
||
if r := recover(); r != nil {
|
||
_ = tx.Rollback(c)
|
||
a.pool = origDB
|
||
panic(r)
|
||
}
|
||
// 中间件顺序:defer 在 c.Next() 之后才执行 → 先 commit 还是 rollback?
|
||
// 用 c.Errors 决定 + status
|
||
if c.IsAborted() {
|
||
_ = tx.Rollback(c)
|
||
} else {
|
||
if err := tx.Commit(c); err != nil {
|
||
// commit 失败时也回滚
|
||
_ = tx.Rollback(c)
|
||
if !c.IsAborted() {
|
||
c.AbortWithStatusJSON(500, gin.H{"error": "commit 快照事务失败: " + err.Error()})
|
||
}
|
||
}
|
||
}
|
||
a.pool = origDB
|
||
}()
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// isReadMethod 判断 HTTP method 是否只读。
|
||
func isReadMethod(m string) bool {
|
||
return m == "GET" || m == "HEAD"
|
||
}
|
||
|
||
// 防止编译告警 - errRow 未使用(实际不抛错误,但保留为工具类型)
|
||
var _ = errors.New
|
||
var _ = pgx.ErrNoRows |