feat(gateway): 多租户增量2 —— gorm 租户插件按上下文自动隔离查询(SaaS P1)

统一强制、别靠人肉:受租户模型标记 isTenantScoped() 后,store/tenant_scope.go
的 gorm 回调按请求 ctx 自动给查询加 WHERE tenant_id、创建自动填 tenant_id。
- KB / Agent 加 TenantID 字段 + isTenantScoped() 标记
- middleware.TenantContext 把 tenant 注入 request context 供 store 插件读取
- ctx 无租户(系统/回填/未登录)不过滤,保留跨租户操作能力
- 启动 BackfillRowTenants 回填存量行 tenant_id=owner 默认租户(幂等)

live 验证:创建自动写 tenant_id ✓;同 owner 不同 tenant 的行被查询过滤 ✓。
Doc/DocLink(异步入库)、Task/Eval(无 owner)留待增量2b。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-06 17:58:58 +08:00
parent f7d12cbf66
commit 30d667954b
6 changed files with 116 additions and 9 deletions
+4 -1
View File
@@ -45,12 +45,15 @@ func main() {
db := store.OpenPostgres(pgDSN) // MainDB: Users / Billing / DSL(连不上则降级)
defer db.Close()
// 多租户回填:给存量用户补建默认租户(幂等;每次启动跑一次)。
// 多租户回填:给存量用户补建默认租户 + 给受租户表存量行回填 tenant_id(幂等;每次启动跑一次)。
if n, err := db.BackfillDefaultTenants(context.Background()); err != nil {
log.Printf("[startup] 默认租户回填失败: %v", err)
} else if n > 0 {
log.Printf("[startup] 为 %d 个存量用户补建了默认租户", n)
}
if err := db.BackfillRowTenants(context.Background()); err != nil {
log.Printf("[startup] 存量行 tenant_id 回填失败: %v", err)
}
cache := store.OpenRedis(redisAddr) // CacheDB: Session / Rate Limit(连不上则降级)
defer cache.Close()
bus := nats.MustConnect(natsURL) // 接入 NATS 零拷贝骨干网 + 声明任务流