feat(library): 生产发布授权与同步/恢复编排,worker 接线
build / build (push) Successful in 1m19s

为什么:同步入口此前只会拒绝;授权、预备份、四类写入、验证与失败恢复都没有代码。
本轮把编排与授权实现出来,真实生产执行仍按授权闸口关闭。

- internal/libraryrelease:预备份 → 数据库/资源/索引/Wiki → 验证 → 失败恢复;
  授权过期/目标不符/快照不符/参数变化在动生产前拒绝;恢复失败单独上报。
- 迁移 000067 library_release_authorizations(目标+快照+参数摘要+有效期,可撤销)。
- POST/GET /api/v1/library/authorizations 与 /{id}/revoke,仅管理员签发,5–1440 分钟。
- worker library.sync 接编排:先闸口再授权,阶段落库,只有编排成功才标成功。
- 生产目标适配器未配置时显式失败(不返回零值状态),预备份存储同。
- overview 返回授权状态,页面"生产保护与恢复"显示签发人与有效期。
- 验收矩阵区分"已实现·隔离测试通过"与"真实执行未授权"。
This commit is contained in:
姚章浩
2026-10-28 15:11:27 +08:00
parent f91359f881
commit 7b8cc0384b
22 changed files with 1288 additions and 46 deletions
+18
View File
@@ -1,5 +1,23 @@
# Changelog
## 开发快照(生产发布授权 + 同步/恢复编排 + 存储管理真实化)
### Added
- `internal/libraryretention`:保留策略、依赖保护(生产生效/最近封存/预备份/在飞作业)与清理预览;
预算未设置即不放行的容量门禁;已并入启动同步的缺项列表。
- `GET /api/v1/library/storage`:真实归档用量 + 三类版本保护依据 + 策略 + 预览 + 容量,只读。
- 发布授权:`library_release_authorizations`(目标+快照+参数摘要+有效期,可撤销),
`POST/GET /api/v1/library/authorizations`、`POST /{id}/revoke`,仅管理员签发,有效期 5–1440 分钟。
- `internal/libraryrelease`:预备份 → 数据库/资源/索引/Wiki → 验证 → 失败恢复的编排,
授权过期/目标不符/快照不符/参数变化一律在动生产前拒绝;恢复失败作为独立结论上报。
- worker `library.sync` 接执行编排:先闸口、再授权,写入阶段落库;生产目标适配器未配置时明确失败。
- 页面"生产保护与恢复"显示发布授权状态与有效期;系统设置→存储管理显示容量门禁、受保护版本与清理预览。
### Changed
- 启动同步的缺项包含"没有与目标快照匹配的有效发布授权"与容量预算;作业只有在编排返回成功时才标成功。
## 开发快照(CI 修复 + 真实差异 + 孤儿作业回收)
### Added
+127
View File
@@ -1025,6 +1025,133 @@
}
}
},
"/api/v1/library/authorizations": {
"get": {
"tags": [
"Runtime"
],
"operationId": "listLibraryAuthorizations",
"summary": "列出该目标的生产发布授权(含签发人、有效期与撤销状态)",
"parameters": [
{
"name": "scope",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": [
"internal",
"external"
]
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
},
"post": {
"tags": [
"Runtime"
],
"operationId": "createLibraryAuthorization",
"summary": "管理员签发生产发布授权:绑定目标+快照+参数摘要+有效期(5–1440 分钟),换快照或换参数即失效",
"responses": {
"201": {
"description": "已记录授权"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"403": {
"description": "仅管理员可签发"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "授权存储不可用"
}
},
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"scope",
"snapshot_id",
"expires_in_minutes"
],
"properties": {
"scope": {
"type": "string",
"enum": [
"internal",
"external"
]
},
"snapshot_id": {
"type": "string"
},
"expires_in_minutes": {
"type": "integer",
"minimum": 5,
"maximum": 1440
}
}
}
}
}
}
}
},
"/api/v1/library/authorizations/{id}/revoke": {
"post": {
"tags": [
"Runtime"
],
"operationId": "revokeLibraryAuthorization",
"summary": "撤销一份生产发布授权(仅管理员);撤销后同一目标快照不能再启动同步",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"403": {
"description": "仅管理员可撤销"
},
"409": {
"description": "授权不存在或已撤销"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/library/syncs": {
"post": {
"tags": [
+78 -12
View File
@@ -19,8 +19,10 @@ import (
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/libraryagent"
"knowledge-governance/internal/libraryrelease"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
v071 "knowledge-governance/internal/releaseadapter/v071"
"knowledge-governance/internal/versionhistory"
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh"
@@ -28,6 +30,19 @@ import (
"knowledge-governance/internal/workflows/testweknora"
)
// libraryStageRecorder 把执行阶段写进持久作业,页面刷新/worker 重启后仍可复现。
type libraryStageRecorder struct {
store *postgresstore.Store
jobID string
scope string
}
func (r libraryStageRecorder) Stage(ctx context.Context, stage, state, detail string) {
if err := r.store.UpdateLibraryStage(ctx, r.jobID, stage, state, nil, nil, nil, nil, detail, time.Now().UTC()); err != nil {
log.Printf("library stage %s/%s update failed: %v", r.jobID, stage, err)
}
}
// libraryCaptureJobType is shared with the API which enqueues it.
const libraryCaptureJobType = "library.capture"
@@ -207,22 +222,73 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
return fmt.Errorf("invalid library sync payload")
}
now := time.Now().UTC()
reasons := make([]string, 0, 3)
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "prebackup", "", "", "", "", now)
recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope}
// 闸口本身关闭时不必进入执行编排:先给出可操作的缺项。
gateReasons := make([]string, 0, 3)
if !config.ProductionReleaseRequestsEnabled {
reasons = append(reasons, "生产写入闸口关闭")
gateReasons = append(gateReasons, "生产写入闸口关闭")
}
if !config.ProductionBackupRestoreVerified {
reasons = append(reasons, "没有已核验的生产恢复演练证据")
gateReasons = append(gateReasons, "没有已核验的生产恢复演练证据")
}
if len(gateReasons) > 0 {
message := "生产同步被闸口拒绝:" + strings.Join(gateReasons, ";")
recorder.Stage(ctx, "prebackup", "failed", message)
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "prebackup", message,
"未对生产执行任何写入,无需恢复", "", "", time.Now().UTC())
return errors.New(message)
}
digest, digestErr := governance.LibraryRequestDigest(payload.Scope, governance.LibraryJobSync,
map[string]any{"target_snapshot_id": payload.TargetSnapshotID})
if digestErr != nil {
message := "无法计算请求摘要"
recorder.Stage(ctx, "prebackup", "failed", message)
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "prebackup", message, "", "", "", time.Now().UTC())
return errors.New(message)
}
grant, found, grantErr := store.ActiveLibraryAuthorization(ctx, payload.Scope, payload.TargetSnapshotID, digest, now)
if grantErr != nil || !found {
// 授权缺失/过期/参数不符都会走到这里:不能写生产。
message := "没有与目标快照匹配的有效发布授权"
recorder.Stage(ctx, "prebackup", "failed", message)
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "prebackup", message,
"未对生产执行任何写入,无需恢复", "", "", time.Now().UTC())
return errors.New(message)
}
request := libraryrelease.Request{
Target: payload.Scope, SnapshotID: payload.TargetSnapshotID, ParamsDigest: digest, Now: now,
Grant: libraryrelease.Grant{Target: payload.Scope, SnapshotID: grant.SnapshotID,
ParamsDigest: grant.ParamsDigest, ExpiresAt: grant.ExpiresAt, AuthorizedBy: grant.AuthorizedBy},
}
// 生产目标与预备份存储都来自适配层:未配置时整条链路在第一步就以明确缺项失败,
// 不会出现"写了一半没有回滚目标"的状态。
target, _ := v071.NewProductionLibraryTarget(config.ProductionWeKnoraBaseURL, config.ProductionWeKnoraAPIKeyFile)
outcome := libraryrelease.Run(ctx, request, target, v071.ArchiveBackupStore{}, recorder)
finishedAt := time.Now().UTC()
switch outcome.State {
case "succeeded":
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobSucceeded, "verify", "", "",
"", payload.TargetSnapshotID, finishedAt)
log.Printf("library sync succeeded job=%s scope=%s snapshot=%s backup=%s",
payload.LibraryJobID, payload.Scope, payload.TargetSnapshotID, outcome.Backup.ID)
return nil
case "rolled_back":
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "rollback", outcome.Error,
outcome.Rollback, "", "", finishedAt)
return errors.New(outcome.Error)
case "rollback_failed":
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "rollback", outcome.Error,
outcome.Rollback, "", "", finishedAt)
return fmt.Errorf("%s(%s)", outcome.Error, outcome.Rollback)
default:
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "prebackup", outcome.Error,
"未对生产执行任何写入,无需恢复", "", "", finishedAt)
return errors.New(outcome.Error)
}
// 生产写入适配与预备份实现之前,执行链本身就是缺项:直接拒绝而不是空转。
reasons = append(reasons, "生产预备份与写入适配尚未实现")
message := "生产同步执行链未接通:" + strings.Join(reasons, ";")
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "prebackup", "", "", "", "", now)
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, "prebackup", "failed", nil, nil, nil, nil, message, now)
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "prebackup", message,
"未对生产执行任何写入,无需恢复", "", "", now)
log.Printf("library sync refused job=%s scope=%s: %s", payload.LibraryJobID, payload.Scope, message)
return errors.New(message)
}
// A crash can leave the source writer stopped: recover before taking work,
// and keep the failure visible instead of pretending the worker is ready.
+16 -10
View File
@@ -9,6 +9,12 @@
A06(内容、问答、引用图片效果、性能报告)已被用户取消,本矩阵不含该项,也不再作为封版门槛。
**状态口径(严格区分四件事)**:
- 已实现·已验证:代码 + 本机真实归档/真实 PostgreSQL 或既有 CI 的实跑证据。
- 已实现·隔离测试通过:代码 + 单元/集成测试(注入假生产目标),**没有**真实生产执行。
- 已实现·未验证:代码在位但缺真实环境证据。
- 未实现 / 真实执行未授权:前者是代码缺口,后者是**权限**缺口,两者不混用。
| ID | 验收要点 | 代码 / 承载位置 | 状态 | 证据或缺口 |
| --- | --- | --- | --- | --- |
| V01 | 只有对内/对外两个目标,身份来自配置映射 | `internal/httpapi/library_*.go`(scope 只接受 internal/external);`web/src/ReleaseTargets.tsx` | 已实现·已验证 | overview 对非法 scope 返回 400;真实归档里 internal/external 各自解析到唯一 KB(0c84a098… / 对外 KB) |
@@ -17,16 +23,16 @@ A06(内容、问答、引用图片效果、性能报告)已被用户取消
| V04 | 完整固定版本:文档集合+处理结果+资源+索引+完整 Wiki | `internal/librarysnapshot/*`(10 表 + 索引 + 资源 + Wiki 部件);`artifacts` 清单 | 已实现·已验证 | 真实快照 f992d64e…:4 文档/38 分块/122 索引/21 资源/31 Wiki 页/55,309,044 字节;部件摘要逐项校验 |
| V05 | 导出中源变更则拒绝或隔离 | `internal/libraryfreeze/*`(持久 journal、源锁、暂停/恢复);`ProjectController` | 已实现·未验证 | 冻结窗口内会重新比对兼容契约;跨"项目外写入者"的证明仍缺,需一次带并发写入的隔离演练 |
| V06 | 只同步知识数据,不含账号/会话/凭据 | 导出白名单(10 张知识表 + 知识域索引 + 资源 + Wiki) | 已实现·已验证 | 部件清单里没有 users/sessions/api_keys;真实归档部件名可逐项核对 |
| B01 | 每次生产写入前完整预备份,失败零写入 | `library_versions.kind=production_prebackup`;`POST /api/v1/library/syncs` 的 gate | 阻塞(需生产读取/写入授权) | 预备份必须读生产当前整库;当前没有生产读取凭据,接口按缺项 503 拒绝且**不建作业** |
| B01 | 每次生产写入前完整预备份,失败零写入 | `internal/libraryrelease`(prebackup 阶段)+ `library_versions.production_prebackup` + gate | 已实现·隔离测试通过·真实执行未授权 | 编排测试:预备份失败→零写入;读不到生产当前状态→零写入。真实预备份需生产读取凭据(未授权) |
| B02 | 资源在测试侧删除后仍可恢复 | 归档内容寻址 blob(`library_versions` + `librarysnapshot` 内容去重) | 已实现·未验证 | 归档不依赖测试临时对象;跨版本去重 55,309,693 字节;尚未做"测试侧删除后从归档恢复"的实测 |
| B03 | 每版保存完整 Wiki 与引用关联并校验 | `library_snapshot` 的 wiki 部件 + 摘要 | 已实现·已验证 | 真实快照含 31 页 Wiki 与逐页摘要,manifest 记录数量/字节 |
| S01 | 数据库/资源/索引/Wiki 真实落地并校验 | 同步执行链 | 阻塞(需生产写入授权) | 执行器在 `cmd/worker` 中 fail-closed:闸口未开即拒绝并写明缺项,不产生部分写入 |
| S02 | 生产不再解析/Embedding/生成 Wiki | 同上(只搬运归档产物) | 阻塞(同上) | 设计上只写归档产物;执行链尚未开通,不能声称已验证 |
| S01 | 数据库/资源/索引/Wiki 真实落地并校验 | `internal/libraryrelease.Run`(四类阶段 + verify)+ worker `library.sync` | 已实现·隔离测试通过·真实执行未授权 | 测试覆盖:四类按序写入、阶段失败→恢复、验证失败→恢复;生产目标适配器未配置时显式失败 |
| S02 | 生产不再解析/Embedding/生成 Wiki | 编排只对 `Stage` 提交归档快照 id,不做解析/嵌入/生成 | 已实现·未验证 | 代码层面没有解析/嵌入调用;真实生产写入未执行,不能声称已验证 |
| S03 | 一致生效与失败补偿边界 | — | 未实现 | 跨 PG/ES/资源的一致切点与可见性保护未实现 |
| S04 | 各阶段失败/超时/重启可追溯可恢复 | `library_jobs`/`library_job_stages` + `ReconcileLibraryJobs` | 已实现·已验证 | 阶段与错误持久化;worker 启动清理"队列已无对应作业"的孤儿并写明恢复责任,避免永久占锁 |
| S05 | 幂等与互斥(多 worker 安全) | `library_jobs_idempotency`、`library_jobs_active` 唯一索引 | 已实现·已验证 | 真实 PostgreSQL 上验证:同目标第二个在飞作业被拒;同键同 digest 重放复用;同键换 digest 冲突 |
| R01 | 版本恢复整套生产知识状态 | — | 阻塞(需生产恢复授权) | 恢复流程未实现;版本抽屉的恢复入口保持禁用并写明"没有恢复演练证据" |
| R02 | 恢复失败显式异常、不回退测试库 | — | 未实现 | 随 R01 一起阻塞 |
| R01 | 版本恢复整套生产知识状态 | `libraryrelease` 失败路径调用 `Target.Restore(backup)`;抽屉恢复入口仍禁用 | 已实现(失败自动恢复)·独立恢复未实现 | 恢复编排与幂等由测试覆盖;"按版本手动恢复"入口仍未接线,不能声称可用 |
| R02 | 恢复失败显式异常、不回退测试库 | `Outcome.State=rollback_failed` + 独立阶段记录 | 已实现·隔离测试通过 | 测试断言恢复失败与同步失败可区分,且不触碰测试库 |
| R03 | 存快/恢复快对比 | — | 未实现 | 未做测速;不写没有测量的数字 |
| P01 | 作业阶段与整体状态 | `library_jobs.state/stage`;页面阶段条 | 已实现·已验证 | 阶段勾选只认当前作业证据;无作业时显示"本次作业尚未开始" |
| P02 | 四类分项计数/字节/错误 | `library_job_stages`(NULL=未知总量) | 已实现·已验证 | 真实库验证阶段行为;无 total 时页面显示"未知总量",不画百分比 |
@@ -34,12 +40,12 @@ A06(内容、问答、引用图片效果、性能报告)已被用户取消
| U01 | 发布管理为主要入口(两库+单作业区) | `web/src/ReleaseTargets.tsx` | 已实现·已验证 | 按确认稿布局;父会话已在登录浏览器核验两库切换与抽屉 |
| U02 | 权限边界 | `canWrite`/`canCapture`,POST 需 engineer+ | 已实现·已验证 | 无权限时不给封存入口;未接线时说明通道状态 |
| U03 | 操作确认 | 封存按钮 + 作业号 + notice | 已实现·已验证 | 同一作业号重放返回已存作业并明确提示 |
| D01 | 保留策略(数量/天数) | — | 未实现 | 保留数量/天数未定,页面明确"未接线",不擅自编默认值 |
| D01 | 保留策略(数量/天数) | `internal/libraryretention`;`LIBRARY_RETENTION_VERSIONS/DAYS` | 已实现·已验证(单测+真实归档) | 未设置=0 时按"全部保留",不编默认值;设置了才生成候选 |
| D02 | 占用测量 | `internal/librarysnapshot/usage.go`;系统设置→存储管理 | 已实现·已验证 | 版本数/跨版本去重内容/blob 表观与分配/未引用/清单;真实两份清单 55,309,693 字节 |
| D03 | 依赖保护 | — | 未实现 | 没有引用保护实现,页面写明 |
| D04 | 清理预览 | — | 未实现 | 没有预览实现,页面写明 |
| D05 | 容量门禁 | — | 未实现 | 生产写入前容量检查随 B01/S01 一起阻塞 |
| D06 | 测试残留 | — | 未实现 | 未做扫描 |
| D03 | 依赖保护 | `libraryretention.Build` 的 Protected/ProtectedBy | 已实现·已验证 | 真实归档上 2 个版本都因"最近测试封存"受保护;受保护版本永不进入候选 |
| D04 | 清理预览 | `libraryretention.Build` 的 Candidates/ReclaimPreviewBytes;`GET /library/storage` | 已实现·已验证 | 真实归档:策略 keep=1 时仍 0 候选(两版均受保护);回收预览只计独占字节 |
| D05 | 容量门禁 | `libraryretention.CheckCapacity` + sync gate | 已实现·已验证(单测+真实数据) | 预算未设置→阻断并说明;超预算→阻断并给出预计字节 |
| D06 | 测试残留 | 归档未引用 blob 统计(UnreferencedBlobs/Bytes) | 已实现·已验证 | 真实归档未引用 blob 为 0;这只是口径,不等于扫描过所有测试残留 |
| D07 | 实际回收 | — | 阻塞(需清理授权) | 自动清理默认关闭,不提供删除动作 |
## 差异比对(本轮新增)
+5 -1
View File
@@ -22,7 +22,11 @@ build-web / tests-go / tests-web / contracts / version / security-secrets / secu
| 0.1.117 | e313ae12f29bd5579f779122cf6a26a87a98a87d | 真实差异比对(librarydiff)+ 孤儿作业回收 + 验收矩阵/台账 | 158 | **success** | 否 |
| 0.1.118 | 3ad48ff32cf301b70555e93409d8593b3b571be0 | 版本抽屉分列测试封存/生产生效/本次预备份 | 159 | **success** | 否 |
0.1.119 起为本台账自身的补记提交:它只改文档,CI 结论以对应 run 为准(交付报告列出 run id 与结论),
| 0.1.119 | 12bb839d8a2cc138d3e4034d4dae559a52c3d094 | 台账补记 | 160 | success | 否 |
| 0.1.120 | f91359f881077d1fad17fca021973c6beb54553f | 存储管理真实化:容量门禁、依赖保护、清理预览 | 161 | **success** | 否 |
| 0.1.121 | 本批提交(见交付报告) | 生产发布授权 + 同步/恢复编排 + worker 接线 + 页面授权状态 | 以 run 为准 | 见交付报告 | 否 |
旧记录 0.1.119 起为本台账自身补记:它只改文档,CI 结论以对应 run 为准(交付报告列出 run id 与结论),
不因"文档提交"免检。
## 说明
+17
View File
@@ -115,3 +115,20 @@ func SyncStages() []string {
func SealStages() []string {
return []string{"export"}
}
// LibraryReleaseAuthorization 是生产发布授权:绑定目标、快照、参数摘要与有效期。
type LibraryReleaseAuthorization struct {
ID string `json:"id"`
Scope string `json:"scope"`
SnapshotID string `json:"snapshot_id"`
ParamsDigest string `json:"params_digest"`
AuthorizedBy string `json:"authorized_by"`
ExpiresAt time.Time `json:"expires_at"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// ValidAt 只在未撤销且未过期时为真;参数摘要由调用方显式比对。
func (a LibraryReleaseAuthorization) ValidAt(now time.Time) bool {
return a.RevokedAt == nil && now.Before(a.ExpiresAt)
}
+134
View File
@@ -0,0 +1,134 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
)
// 生产发布授权:管理员把"目标 + 快照 + 参数摘要 + 有效期"钉死。
// 换快照、换目标或改参数都会得到不同摘要,旧授权自然失效;到期或被撤销也不能用。
type libraryAuthorizationRequest struct {
Scope string `json:"scope"`
SnapshotID string `json:"snapshot_id"`
ExpiresInMinutes int `json:"expires_in_minutes"`
}
type libraryAuthorizationStore interface {
CreateLibraryAuthorization(ctx context.Context, item governance.LibraryReleaseAuthorization) error
LibraryAuthorizations(ctx context.Context, scope string, limit int) ([]governance.LibraryReleaseAuthorization, error)
RevokeLibraryAuthorization(ctx context.Context, id string, now time.Time) error
}
func libraryAuthorizationStoreOf(config Config) (libraryAuthorizationStore, bool) {
store, ok := config.Store.(libraryAuthorizationStore)
return store, ok
}
// librarySyncParamsDigest 与 POST /library/syncs 使用的摘要必须完全一致,
// 否则授权永远匹配不上,或者更糟——能匹配上却对应别的参数。
func librarySyncParamsDigest(scope, snapshotID string) (string, error) {
return governance.LibraryRequestDigest(scope, governance.LibraryJobSync,
map[string]any{"target_snapshot_id": snapshotID})
}
func libraryAuthorizationCreate(w http.ResponseWriter, r *http.Request, config Config) {
if r.Method != http.MethodPost {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
identity, ok := sessionFrom(r.Context())
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
writeJSON(w, http.StatusForbidden, map[string]any{"error": "生产发布授权仅管理员可签发"})
return
}
store, ok := libraryAuthorizationStoreOf(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "授权存储不可用"})
return
}
var request libraryAuthorizationRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
if request.Scope != "internal" && request.Scope != "external" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"})
return
}
if strings.TrimSpace(request.SnapshotID) == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshot_id required"})
return
}
// 有效期必须显式给出且很短:不提供"永久授权"这种危险默认值。
if request.ExpiresInMinutes < 5 || request.ExpiresInMinutes > 24*60 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "expires_in_minutes must be between 5 and 1440"})
return
}
digest, err := librarySyncParamsDigest(request.Scope, request.SnapshotID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"})
return
}
now := time.Now().UTC()
item := governance.LibraryReleaseAuthorization{
ID: "libauth-" + request.Scope + "-" + now.Format("20060102T150405.000000"),
Scope: request.Scope,
SnapshotID: request.SnapshotID,
ParamsDigest: digest,
AuthorizedBy: identity.Username,
ExpiresAt: now.Add(time.Duration(request.ExpiresInMinutes) * time.Minute),
CreatedAt: now,
}
if err := store.CreateLibraryAuthorization(r.Context(), item); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record authorization"})
return
}
writeJSON(w, http.StatusCreated, map[string]any{"authorization": item})
}
func libraryAuthorizationList(w http.ResponseWriter, r *http.Request, config Config) {
scope, err := scopeFromQuery(r)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
store, ok := libraryAuthorizationStoreOf(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "授权存储不可用", "authorizations": []any{}})
return
}
items, err := store.LibraryAuthorizations(r.Context(), scope, 50)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read authorizations"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"available": true, "authorizations": items})
}
func libraryAuthorizationRevoke(w http.ResponseWriter, r *http.Request, config Config) {
identity, ok := sessionFrom(r.Context())
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
writeJSON(w, http.StatusForbidden, map[string]any{"error": "撤销生产发布授权仅管理员可执行"})
return
}
store, ok := libraryAuthorizationStoreOf(config)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "授权存储不可用"})
return
}
id := strings.TrimSpace(r.PathValue("id"))
if id == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "authorization id required"})
return
}
if err := store.RevokeLibraryAuthorization(r.Context(), id, time.Now().UTC()); err != nil {
writeJSON(w, http.StatusConflict, map[string]any{"error": "授权不存在或已撤销"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"revoked": id})
}
@@ -0,0 +1,84 @@
package httpapi
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
func authorizationRequest(body string, role string, username string) *http.Request {
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/authorizations", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json")
ctx := context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: username, Role: role})
return request.WithContext(ctx)
}
func TestLibraryAuthorizationRequiresAdmin(t *testing.T) {
store := &fakeLibraryStore{}
recorder := httptest.NewRecorder()
libraryAuthorizationCreate(recorder, authorizationRequest(`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":30}`, roleEngineer, "eng"), Config{Store: store})
if recorder.Code != http.StatusForbidden {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.grant != nil {
t.Fatal("non-admin must not create an authorization")
}
}
func TestLibraryAuthorizationBindsScopeSnapshotAndDigest(t *testing.T) {
store := &fakeLibraryStore{}
recorder := httptest.NewRecorder()
libraryAuthorizationCreate(recorder, authorizationRequest(`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":30}`, roleAdmin, "admin"), Config{Store: store})
if recorder.Code != http.StatusCreated {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
want, err := librarySyncParamsDigest("internal", "snap-1")
if err != nil {
t.Fatal(err)
}
if store.grant.ParamsDigest != want || store.grant.SnapshotID != "snap-1" || store.grant.Scope != "internal" {
t.Fatalf("grant not bound to request params: %+v", store.grant)
}
// 同一个授权不能用于另一个快照:摘要不同即查不到。
if _, found, _ := store.ActiveLibraryAuthorization(context.Background(), "internal", "snap-2", want, time.Now()); found {
t.Fatal("grant must not authorize another snapshot")
}
if _, found, _ := store.ActiveLibraryAuthorization(context.Background(), "internal", "snap-1", "other-digest", time.Now()); found {
t.Fatal("grant must not authorize different params")
}
}
func TestLibraryAuthorizationRejectsUnboundedValidity(t *testing.T) {
for _, body := range []string{
`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":0}`,
`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":100000}`,
} {
store := &fakeLibraryStore{}
recorder := httptest.NewRecorder()
libraryAuthorizationCreate(recorder, authorizationRequest(body, roleAdmin, "admin"), Config{Store: store})
if recorder.Code != http.StatusBadRequest {
t.Fatalf("body=%s status=%d", body, recorder.Code)
}
}
}
func TestLibraryAuthorizationExpiryIsEnforced(t *testing.T) {
now := time.Now()
item := governance.LibraryReleaseAuthorization{ID: "a", Scope: "internal", SnapshotID: "snap-1",
ParamsDigest: "d", ExpiresAt: now.Add(-time.Minute)}
if item.ValidAt(now) {
t.Fatal("expired authorization must be invalid")
}
revoked := item
revoked.ExpiresAt = now.Add(time.Hour)
revokedAt := now
revoked.RevokedAt = &revokedAt
if revoked.ValidAt(now) {
t.Fatal("revoked authorization must be invalid")
}
}
+96 -15
View File
@@ -10,6 +10,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarydiff"
"knowledge-governance/internal/librarysnapshot"
)
@@ -34,6 +35,9 @@ type libraryVersionView struct {
SupersededAt *time.Time `json:"superseded_at,omitempty"`
}
// librarySyncJobType 与 worker 的处理器类型一致;单独定义避免 API 依赖 worker 包。
const librarySyncJobType = "library.sync"
type libraryKnownView struct {
State string `json:"state"` // known | unknown
Version *libraryVersionView `json:"version,omitempty"`
@@ -123,24 +127,33 @@ func computeLibraryDiff(root, baseID, targetID string) (libraryDiffView, bool) {
return view, true
}
// libraryAuthorizationView 让页面能直说"有没有授权、有效期到什么时候"。
type libraryAuthorizationView struct {
State string `json:"state"` // active | none
AuthorizedBy string `json:"authorized_by,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Reason string `json:"reason,omitempty"`
}
type libraryGateView struct {
SyncAllowed bool `json:"sync_allowed"`
Reasons []string `json:"reasons"`
}
type libraryOverview struct {
Scope string `json:"scope"`
TestSealed *librarySnapshotView `json:"test_sealed,omitempty"`
TestSealedReason string `json:"test_sealed_reason,omitempty"`
Production libraryKnownView `json:"production"`
Prebackup libraryKnownView `json:"prebackup"`
Diff libraryDiffView `json:"diff"`
Job *governance.LibraryJob `json:"job,omitempty"`
Jobs []governance.LibraryJob `json:"jobs"`
Gate libraryGateView `json:"gate"`
CaptureAvailable bool `json:"capture_available"`
CaptureReason string `json:"capture_reason,omitempty"`
Now time.Time `json:"now"`
Scope string `json:"scope"`
TestSealed *librarySnapshotView `json:"test_sealed,omitempty"`
TestSealedReason string `json:"test_sealed_reason,omitempty"`
Production libraryKnownView `json:"production"`
Prebackup libraryKnownView `json:"prebackup"`
Diff libraryDiffView `json:"diff"`
Job *governance.LibraryJob `json:"job,omitempty"`
Jobs []governance.LibraryJob `json:"jobs"`
Gate libraryGateView `json:"gate"`
Authorization libraryAuthorizationView `json:"authorization"`
CaptureAvailable bool `json:"capture_available"`
CaptureReason string `json:"capture_reason,omitempty"`
Now time.Time `json:"now"`
}
type libraryJobStore interface {
@@ -160,6 +173,36 @@ func libraryStore(config Config) (libraryJobStore, bool) {
return store, ok
}
// activeGrantFor 只查"目标+快照+同一参数摘要"的未过期未撤销授权。
func activeGrantFor(ctx context.Context, config Config, scope, snapshotID string) (governance.LibraryReleaseAuthorization, bool) {
if snapshotID == "" {
return governance.LibraryReleaseAuthorization{}, false
}
store, ok := config.Store.(interface {
ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, paramsDigest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error)
})
if !ok {
return governance.LibraryReleaseAuthorization{}, false
}
digest, err := librarySyncParamsDigest(scope, snapshotID)
if err != nil {
return governance.LibraryReleaseAuthorization{}, false
}
grant, found, err := store.ActiveLibraryAuthorization(ctx, scope, snapshotID, digest, time.Now().UTC())
if err != nil || !found {
return governance.LibraryReleaseAuthorization{}, false
}
return grant, true
}
func authorizationViewOf(grant governance.LibraryReleaseAuthorization, found bool) libraryAuthorizationView {
if !found {
return libraryAuthorizationView{State: "none", Reason: "没有与目标快照匹配的有效发布授权"}
}
expires := grant.ExpiresAt
return libraryAuthorizationView{State: "active", AuthorizedBy: grant.AuthorizedBy, ExpiresAt: &expires}
}
func scopeFromQuery(r *http.Request) (string, error) {
scope := strings.TrimSpace(r.URL.Query().Get("scope"))
if scope == "" {
@@ -180,7 +223,16 @@ func libraryVersionViewOf(item governance.LibraryVersion) libraryVersionView {
// librarySyncGate 只依据真实存在的证据判断能不能写生产:闸口、生产端点、
// 生产权威版本、目标快照的预备份。任何一项缺失都给出具体原因,不默认放行。
func librarySyncGate(config Config, production libraryKnownView, prebackup libraryKnownView, target string) libraryGateView {
return librarySyncGateWithGrant(config, production, prebackup, target, false)
}
// librarySyncGateWithGrant 在原有证据之外再要求一份有效授权:
// 授权绑定了目标、快照、参数与有效期,缺它就不能写生产。
func librarySyncGateWithGrant(config Config, production libraryKnownView, prebackup libraryKnownView, target string, hasGrant bool) libraryGateView {
gate := libraryGateView{SyncAllowed: false, Reasons: []string{}}
if !hasGrant {
gate.Reasons = append(gate.Reasons, "没有与目标快照匹配的有效发布授权")
}
if !config.ProductionReleaseRequestsEnabled {
gate.Reasons = append(gate.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
}
@@ -299,7 +351,9 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
overview.Diff = view
}
overview.Gate = librarySyncGate(config, overview.Production, overview.Prebackup, target)
grant, hasGrant := activeGrantFor(r.Context(), config, scope, target)
overview.Authorization = authorizationViewOf(grant, hasGrant)
overview.Gate = librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, target, hasGrant)
writeJSON(w, http.StatusOK, overview)
}
@@ -384,7 +438,9 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
overview.Prebackup = libraryKnownView{State: "known", Version: &view}
}
}
gate := librarySyncGate(config, overview.Production, overview.Prebackup, request.Target)
grantFound, hasGrant := activeGrantFor(r.Context(), config, request.Scope, request.Target)
_ = grantFound
gate := librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, request.Target, hasGrant)
if !gate.SyncAllowed {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
"code": "library_sync_blocked", "reasons": gate.Reasons,
@@ -423,5 +479,30 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": reused})
if reused {
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
return
}
// 业务作业先落库,再投递队列:投递失败就把作业标失败,不留下"看起来在跑"的空作业。
payload, err := json.Marshal(map[string]string{
"library_job_id": job.ID, "scope": request.Scope, "target_snapshot_id": request.Target,
})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build sync payload"})
return
}
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: job.ID + "-queue", Type: librarySyncJobType, Payload: payload, AvailableAt: now,
MaxAttempts: 1, IdempotencyKey: "library.sync.queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"})
return
}
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach sync job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
}
+76 -1
View File
@@ -18,6 +18,7 @@ import (
// 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。
type fakeLibraryStore struct {
fakeJobStore
grant *governance.LibraryReleaseAuthorization
versions []governance.LibraryVersion
jobs []governance.LibraryJob
createN int
@@ -69,6 +70,32 @@ func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state
return nil
}
func (f *fakeLibraryStore) CreateLibraryAuthorization(_ context.Context, item governance.LibraryReleaseAuthorization) error {
f.grant = &item
return nil
}
func (f *fakeLibraryStore) ActiveLibraryAuthorization(_ context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error) {
if f.grant == nil || f.grant.Scope != scope || f.grant.SnapshotID != snapshotID || f.grant.ParamsDigest != digest {
return governance.LibraryReleaseAuthorization{}, false, nil
}
if !f.grant.ValidAt(now) {
return governance.LibraryReleaseAuthorization{}, false, nil
}
return *f.grant, true, nil
}
func (f *fakeLibraryStore) LibraryAuthorizations(context.Context, string, int) ([]governance.LibraryReleaseAuthorization, error) {
if f.grant == nil {
return nil, nil
}
return []governance.LibraryReleaseAuthorization{*f.grant}, nil
}
func (f *fakeLibraryStore) RevokeLibraryAuthorization(context.Context, string, time.Time) error {
return nil
}
func (f *fakeLibraryStore) AttachLibraryQueueJob(_ context.Context, _, _ string, _ time.Time) error {
return nil
}
@@ -130,7 +157,7 @@ func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
gate := librarySyncGate(testCase.config, testCase.production, testCase.prebackup, testCase.target)
gate := librarySyncGateWithGrant(testCase.config, testCase.production, testCase.prebackup, testCase.target, true)
if gate.SyncAllowed != testCase.allowed {
t.Fatalf("sync_allowed = %v, want %v (%v)", gate.SyncAllowed, testCase.allowed, gate.Reasons)
}
@@ -194,6 +221,54 @@ func TestLibrarySyncEnqueueRequiresPrebackupForTarget(t *testing.T) {
}
}
// 证据齐全 + 有效授权时才会真正建作业并入队;缺授权一律拒绝且不建作业。
func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) {
target := "snap-1"
digest, err := librarySyncParamsDigest("internal", target)
if err != nil {
t.Fatal(err)
}
store := &fakeLibraryStore{versions: []governance.LibraryVersion{
{ID: "ver-prod", Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
SnapshotID: "prod-snap", VersionLabel: "prod-2026.10", CreatedAt: time.Now().UTC()},
{ID: "ver-backup", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup,
SnapshotID: target, CreatedAt: time.Now().UTC()},
}}
store.enqueueEchoRequestedID = true
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid", LibraryCapacityBudgetBytes: 1 << 40}
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
// 先没有授权
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("without grant status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.createN != 0 {
t.Fatal("must not create a job without a grant")
}
// 补上绑定同一目标与快照的授权
now := time.Now().UTC()
store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target,
ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now}
recorder = httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusAccepted {
t.Fatalf("with grant status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.createN != 1 {
t.Fatalf("created=%d, want 1", store.createN)
}
if store.enqueued.Type != "library.sync" {
t.Fatalf("enqueued type=%q, want library.sync", store.enqueued.Type)
}
if !strings.Contains(string(store.enqueued.Payload), store.lastJob.ID) {
t.Fatalf("queue payload must carry the library job id: %s", store.enqueued.Payload)
}
}
// 三类版本必须分开读:production_effective 才是生产当前,测试封存不能顶替。
func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) {
now := time.Now().UTC()
+10
View File
@@ -424,6 +424,16 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/library/jobs/{id}", func(w http.ResponseWriter, r *http.Request) {
libraryJobDetailHandler(w, r, config)
})
// 生产发布授权:管理员签发,绑定目标+快照+参数摘要+有效期;可撤销。
mux.HandleFunc("POST /api/v1/library/authorizations", func(w http.ResponseWriter, r *http.Request) {
libraryAuthorizationCreate(w, r, config)
})
mux.HandleFunc("GET /api/v1/library/authorizations", func(w http.ResponseWriter, r *http.Request) {
libraryAuthorizationList(w, r, config)
})
mux.HandleFunc("POST /api/v1/library/authorizations/{id}/revoke", func(w http.ResponseWriter, r *http.Request) {
libraryAuthorizationRevoke(w, r, config)
})
// 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
librarySyncEnqueue(w, r, config)
+205
View File
@@ -0,0 +1,205 @@
// Package libraryrelease 是生产同步的执行编排:预备份 → 四类写入 → 验证 → 失败恢复。
//
// 它只编排顺序与责任,不自己连生产:目标读写由 Target 注入,备份由 BackupStore 注入,
// 授权由 Grant 描述。任何一步失败都不得标记成功;失败后必须尝试恢复原生产版本,
// 恢复失败要作为独立的、更严重的结论上报。
package libraryrelease
import (
"context"
"errors"
"fmt"
"time"
)
// Stage 是四类需要真实落地的数据;顺序即写入顺序。
type Stage string
const (
StageDatabase Stage = "database"
StageResources Stage = "resources"
StageIndex Stage = "index"
StageWiki Stage = "wiki"
)
func Stages() []Stage { return []Stage{StageDatabase, StageResources, StageIndex, StageWiki} }
// Grant 是一次生产发布的授权:绑定确切目标与快照,带有效期与参数摘要。
// 参数一旦变化(例如换了目标快照)就必须重新授权,不能复用旧 grant。
type Grant struct {
Target string `json:"target"`
SnapshotID string `json:"snapshot_id"`
ExpiresAt time.Time `json:"expires_at"`
ParamsDigest string `json:"params_digest"`
AuthorizedBy string `json:"authorized_by"`
}
// Request 是一次待执行的生产同步。
type Request struct {
Target string
SnapshotID string
// ParamsDigest 覆盖会影响生产结果的全部参数(目标、快照、排除范围等)。
ParamsDigest string
Grant Grant
Now time.Time
}
// CurrentState 是生产当前整库的指纹,用于预备份与最终验证。
type CurrentState struct {
Revision string `json:"revision"`
Counts map[string]int64 `json:"counts"`
Digests map[string]string `json:"digests"`
CapturedAt time.Time `json:"captured_at"`
}
// Expectation 是同步完成后生产应当具备的状态(来自测试封存)。
type Expectation struct {
SnapshotID string
Counts map[string]int64
Digests map[string]string
}
// BackupRef 指向一份可独立恢复的完整预备份。
type BackupRef struct {
ID string `json:"id"`
Bytes int64 `json:"bytes"`
CreatedAt time.Time `json:"created_at"`
}
type Target interface {
// Current 读取生产当前整库指纹;读不到就不能开始写入。
Current(ctx context.Context) (CurrentState, error)
// Apply 把一类数据写入生产;实现必须幂等或可回滚。
Apply(ctx context.Context, stage Stage, snapshotID string) error
// Verify 校验生产是否与期望一致。
Verify(ctx context.Context, expect Expectation) error
// Restore 把生产恢复到给定预备份。
Restore(ctx context.Context, backup BackupRef) error
}
type BackupStore interface {
// Prepare 创建独立完整预备份,并在返回前自检可恢复性。
Prepare(ctx context.Context, snapshotID string, current CurrentState) (BackupRef, error)
}
// Recorder 把阶段状态写进持久作业,供页面恢复展示。
type Recorder interface {
Stage(ctx context.Context, stage string, state string, detail string)
}
type recorderFunc func(ctx context.Context, stage, state, detail string)
func (f recorderFunc) Stage(ctx context.Context, stage, state, detail string) {
f(ctx, stage, state, detail)
}
// NoopRecorder 用于测试或不需要落库的调用。
type NoopRecorder struct{}
func (NoopRecorder) Stage(context.Context, string, string, string) {}
type Outcome struct {
State string `json:"state"` // succeeded | failed | rolled_back | rollback_failed
Backup BackupRef `json:"backup"`
FailedAt Stage `json:"failed_at,omitempty"`
Error string `json:"error,omitempty"`
Rollback string `json:"rollback,omitempty"`
Finished time.Time `json:"finished"`
}
var (
ErrGrantExpired = errors.New("发布授权已过期")
ErrGrantTarget = errors.New("发布授权与目标不匹配")
ErrGrantSnapshot = errors.New("发布授权与快照不匹配")
ErrGrantParams = errors.New("发布参数与授权不一致")
ErrBackupUnavailable = errors.New("无法创建可独立恢复的生产预备份")
)
// ValidateGrant 在动生产之前把授权核对清楚:目标、快照、参数摘要、有效期,
// 任一项不符都直接拒绝,不做"先写一半再说"。
func ValidateGrant(request Request) error {
if request.Grant.Target != request.Target {
return fmt.Errorf("%w:授权 %q,请求 %q", ErrGrantTarget, request.Grant.Target, request.Target)
}
if request.Grant.SnapshotID != request.SnapshotID {
return fmt.Errorf("%w:授权 %q,请求 %q", ErrGrantSnapshot, request.Grant.SnapshotID, request.SnapshotID)
}
if request.Grant.ParamsDigest != request.ParamsDigest {
return ErrGrantParams
}
now := request.Now
if now.IsZero() {
now = time.Now()
}
if request.Grant.ExpiresAt.IsZero() || !now.Before(request.Grant.ExpiresAt) {
return ErrGrantExpired
}
return nil
}
// Run 执行完整链路。任何阶段失败都会尝试恢复;只有全部成功才返回 succeeded。
func Run(ctx context.Context, request Request, target Target, backups BackupStore, recorder Recorder) Outcome {
outcome := Outcome{State: "failed", Finished: time.Now().UTC()}
if recorder == nil {
recorder = NoopRecorder{}
}
if err := ValidateGrant(request); err != nil {
outcome.Error = err.Error()
recorder.Stage(ctx, "prebackup", "failed", err.Error())
return outcome
}
recorder.Stage(ctx, "prebackup", "running", "读取生产当前状态并创建预备份")
current, err := target.Current(ctx)
if err != nil {
// 读不到生产当前状态就不能写:否则回滚目标都没有。
outcome.Error = "读取生产当前状态失败:" + err.Error()
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
return outcome
}
backup, err := backups.Prepare(ctx, request.SnapshotID, current)
if err != nil {
outcome.Error = fmt.Sprintf("%v:%v", ErrBackupUnavailable, err)
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
return outcome
}
outcome.Backup = backup
recorder.Stage(ctx, "prebackup", "succeeded", "预备份 "+backup.ID)
for _, stage := range Stages() {
recorder.Stage(ctx, string(stage), "running", "")
if err = target.Apply(ctx, stage, request.SnapshotID); err != nil {
return failAndRestore(ctx, outcome, target, recorder, stage, err)
}
recorder.Stage(ctx, string(stage), "succeeded", "")
}
recorder.Stage(ctx, "verify", "running", "")
expect := Expectation{SnapshotID: request.SnapshotID, Counts: current.Counts, Digests: current.Digests}
if err = target.Verify(ctx, expect); err != nil {
return failAndRestore(ctx, outcome, target, recorder, "verify", err)
}
recorder.Stage(ctx, "verify", "succeeded", "")
outcome.State = "succeeded"
outcome.Finished = time.Now().UTC()
return outcome
}
func failAndRestore(ctx context.Context, outcome Outcome, target Target, recorder Recorder, stage Stage, cause error) Outcome {
outcome.FailedAt = stage
outcome.Error = cause.Error()
outcome.Finished = time.Now().UTC()
recorder.Stage(ctx, string(stage), "failed", cause.Error())
recorder.Stage(ctx, "rollback", "running", "恢复到预备份 "+outcome.Backup.ID)
if restoreErr := target.Restore(ctx, outcome.Backup); restoreErr != nil {
// 恢复失败比同步失败更严重:明确标出,不能当作普通失败吞掉。
outcome.State = "rollback_failed"
outcome.Rollback = "恢复失败:" + restoreErr.Error()
recorder.Stage(ctx, "rollback", "failed", outcome.Rollback)
return outcome
}
outcome.State = "rolled_back"
outcome.Rollback = "已恢复到预备份 " + outcome.Backup.ID
recorder.Stage(ctx, "rollback", "succeeded", outcome.Rollback)
return outcome
}
+210
View File
@@ -0,0 +1,210 @@
package libraryrelease
import (
"context"
"errors"
"strings"
"testing"
"time"
)
type fakeTarget struct {
currentErr error
applyErr map[Stage]error
verifyErr error
restoreErr error
applied []Stage
restored int
currentN int
}
func (f *fakeTarget) Current(context.Context) (CurrentState, error) {
f.currentN++
if f.currentErr != nil {
return CurrentState{}, f.currentErr
}
return CurrentState{Revision: "prod-r1", Counts: map[string]int64{"documents": 4},
Digests: map[string]string{"knowledges": "abc"}, CapturedAt: time.Now().UTC()}, nil
}
func (f *fakeTarget) Apply(_ context.Context, stage Stage, _ string) error {
if err, ok := f.applyErr[stage]; ok && err != nil {
return err
}
f.applied = append(f.applied, stage)
return nil
}
func (f *fakeTarget) Verify(context.Context, Expectation) error { return f.verifyErr }
func (f *fakeTarget) Restore(context.Context, BackupRef) error {
f.restored++
return f.restoreErr
}
type fakeBackups struct {
err error
ref BackupRef
seen int
}
func (f *fakeBackups) Prepare(context.Context, string, CurrentState) (BackupRef, error) {
f.seen++
if f.err != nil {
return BackupRef{}, f.err
}
ref := f.ref
if ref.ID == "" {
ref = BackupRef{ID: "backup-1", Bytes: 1024, CreatedAt: time.Now().UTC()}
}
return ref, nil
}
type stageLog struct{ entries []string }
func (s *stageLog) Stage(_ context.Context, stage, state, _ string) {
s.entries = append(s.entries, stage+":"+state)
}
func (s *stageLog) has(entry string) bool {
for _, item := range s.entries {
if item == entry {
return true
}
}
return false
}
func request(now time.Time) Request {
return Request{Target: "internal-prod", SnapshotID: "snap-1", ParamsDigest: "digest-1", Now: now,
Grant: Grant{Target: "internal-prod", SnapshotID: "snap-1", ParamsDigest: "digest-1",
ExpiresAt: now.Add(30 * time.Minute), AuthorizedBy: "admin"}}
}
func TestRunHappyPathWritesAllStagesThenVerifies(t *testing.T) {
target := &fakeTarget{}
backups := &fakeBackups{}
recorder := &stageLog{}
now := time.Now()
outcome := Run(context.Background(), request(now), target, backups, recorder)
if outcome.State != "succeeded" {
t.Fatalf("state = %s (%s)", outcome.State, outcome.Error)
}
if len(target.applied) != 4 || target.restored != 0 {
t.Fatalf("applied=%v restored=%d", target.applied, target.restored)
}
if !recorder.has("verify:succeeded") || recorder.has("rollback:running") {
t.Fatalf("stage log = %v", recorder.entries)
}
}
func TestRunRefusesExpiredOrMismatchedGrantBeforeTouchingTarget(t *testing.T) {
cases := []struct {
name string
mutate func(*Request)
want error
}{
{"expired", func(r *Request) { r.Now = r.Grant.ExpiresAt.Add(time.Minute) }, ErrGrantExpired},
{"other target", func(r *Request) { r.Target = "external-prod" }, ErrGrantTarget},
{"other snapshot", func(r *Request) { r.SnapshotID = "snap-2" }, ErrGrantSnapshot},
{"params changed", func(r *Request) { r.ParamsDigest = "digest-2" }, ErrGrantParams},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
req := request(time.Now())
testCase.mutate(&req)
target := &fakeTarget{}
backups := &fakeBackups{}
outcome := Run(context.Background(), req, target, backups, nil)
if outcome.State != "failed" {
t.Fatalf("state = %s, want failed", outcome.State)
}
if !errors.Is(errors.New(outcome.Error), testCase.want) && !strings.Contains(outcome.Error, testCase.want.Error()) {
t.Fatalf("error = %q, want %v", outcome.Error, testCase.want)
}
if target.currentN != 0 || len(target.applied) != 0 || backups.seen != 0 {
t.Fatalf("refused request must not touch production: current=%d applied=%d backups=%d",
target.currentN, len(target.applied), backups.seen)
}
})
}
}
func TestRunStopsWhenProductionStateUnreadable(t *testing.T) {
target := &fakeTarget{currentErr: errors.New("生产不可达")}
backups := &fakeBackups{}
outcome := Run(context.Background(), request(time.Now()), target, backups, nil)
if outcome.State != "failed" || !strings.Contains(outcome.Error, "读取生产当前状态失败") {
t.Fatalf("outcome = %+v", outcome)
}
if backups.seen != 0 || len(target.applied) != 0 {
t.Fatal("must not write when production state is unknown")
}
}
func TestRunStopsBeforeWritingWhenBackupFails(t *testing.T) {
target := &fakeTarget{}
backups := &fakeBackups{err: errors.New("磁盘不足")}
recorder := &stageLog{}
outcome := Run(context.Background(), request(time.Now()), target, backups, recorder)
if outcome.State != "failed" {
t.Fatalf("state = %s", outcome.State)
}
if len(target.applied) != 0 {
t.Fatalf("must not write production without a verified backup: %v", target.applied)
}
if !strings.Contains(outcome.Error, ErrBackupUnavailable.Error()) {
t.Fatalf("error must name the backup failure: %q", outcome.Error)
}
if !recorder.has("prebackup:failed") {
t.Fatalf("stage log = %v", recorder.entries)
}
}
func TestRunRollsBackWhenStageFails(t *testing.T) {
target := &fakeTarget{applyErr: map[Stage]error{StageIndex: errors.New("索引写入失败")}}
recorder := &stageLog{}
outcome := Run(context.Background(), request(time.Now()), target, &fakeBackups{}, recorder)
if outcome.State != "rolled_back" {
t.Fatalf("state = %s (%s)", outcome.State, outcome.Error)
}
if outcome.FailedAt != StageIndex {
t.Fatalf("failed_at = %s", outcome.FailedAt)
}
if target.restored != 1 {
t.Fatalf("restore calls = %d, want 1", target.restored)
}
// wiki 在 index 之后,不应执行
for _, stage := range target.applied {
if stage == StageWiki {
t.Fatal("later stages must not run after a failure")
}
}
if !recorder.has("rollback:succeeded") {
t.Fatalf("stage log = %v", recorder.entries)
}
}
func TestRunRollsBackWhenVerificationFails(t *testing.T) {
target := &fakeTarget{verifyErr: errors.New("生产分块数不一致")}
outcome := Run(context.Background(), request(time.Now()), target, &fakeBackups{}, nil)
if outcome.State != "rolled_back" || target.restored != 1 {
t.Fatalf("outcome = %+v restored=%d", outcome, target.restored)
}
}
func TestRunReportsRollbackFailureDistinctly(t *testing.T) {
target := &fakeTarget{applyErr: map[Stage]error{StageDatabase: errors.New("写库失败")},
restoreErr: errors.New("恢复也失败")}
recorder := &stageLog{}
outcome := Run(context.Background(), request(time.Now()), target, &fakeBackups{}, recorder)
if outcome.State != "rollback_failed" {
t.Fatalf("state = %s, want rollback_failed", outcome.State)
}
if !strings.Contains(outcome.Rollback, "恢复失败") {
t.Fatalf("rollback message = %q", outcome.Rollback)
}
if !recorder.has("rollback:failed") {
t.Fatalf("stage log = %v", recorder.entries)
}
}
@@ -300,3 +300,72 @@ FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`
}
return result, rows.Err()
}
// CreateLibraryAuthorization 记录一次生产发布授权;同一 (scope,snapshot,digest) 只保留最新有效。
func (s *Store) CreateLibraryAuthorization(ctx context.Context, item governance.LibraryReleaseAuthorization) error {
if item.ID == "" || item.Scope == "" || item.SnapshotID == "" || item.ParamsDigest == "" || item.ExpiresAt.IsZero() {
return errors.New("invalid library release authorization")
}
_, err := s.db.Exec(ctx, `
INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC())
if err != nil {
return fmt.Errorf("create library release authorization: %w", err)
}
return nil
}
// ActiveLibraryAuthorization 只返回"未撤销、未过期、且参数摘要完全一致"的授权。
// 参数一变就查不到,自然拒绝,而不是靠调用方记得复核。
func (s *Store) ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, paramsDigest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error) {
var item governance.LibraryReleaseAuthorization
err := s.db.QueryRow(ctx, `
SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at
FROM library_release_authorizations
WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND revoked_at IS NULL AND expires_at > $4
ORDER BY expires_at DESC, created_at DESC
LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope, &item.SnapshotID,
&item.ParamsDigest, &item.AuthorizedBy, &item.ExpiresAt, &item.RevokedAt, &item.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryReleaseAuthorization{}, false, nil
}
if err != nil {
return governance.LibraryReleaseAuthorization{}, false, fmt.Errorf("load library authorization: %w", err)
}
return item, true, nil
}
func (s *Store) RevokeLibraryAuthorization(ctx context.Context, id string, now time.Time) error {
tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND revoked_at IS NULL`, id, now.UTC())
if err != nil {
return fmt.Errorf("revoke library authorization: %w", err)
}
if tag.RowsAffected() != 1 {
return errors.New("library authorization not found or already revoked")
}
return nil
}
func (s *Store) LibraryAuthorizations(ctx context.Context, scope string, limit int) ([]governance.LibraryReleaseAuthorization, error) {
if limit < 1 || limit > 100 {
return nil, errors.New("library authorization limit out of range")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at
FROM library_release_authorizations WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
if err != nil {
return nil, fmt.Errorf("list library authorizations: %w", err)
}
defer rows.Close()
result := make([]governance.LibraryReleaseAuthorization, 0, limit)
for rows.Next() {
var item governance.LibraryReleaseAuthorization
if err := rows.Scan(&item.ID, &item.Scope, &item.SnapshotID, &item.ParamsDigest, &item.AuthorizedBy,
&item.ExpiresAt, &item.RevokedAt, &item.CreatedAt); err != nil {
return nil, fmt.Errorf("scan library authorization: %w", err)
}
result = append(result, item)
}
return result, rows.Err()
}
@@ -0,0 +1 @@
DROP TABLE IF EXISTS library_release_authorizations;
@@ -0,0 +1,14 @@
-- 生产发布授权:绑定确切目标 + 快照 + 参数摘要 + 有效期,可撤销。
-- 参数一变(换快照/换目标)摘要就不同,旧授权不能再放行。
CREATE TABLE library_release_authorizations (
id VARCHAR(64) PRIMARY KEY,
scope VARCHAR(16) NOT NULL CHECK (scope IN ('internal','external')),
snapshot_id VARCHAR(64) NOT NULL,
params_digest VARCHAR(64) NOT NULL,
authorized_by VARCHAR(128) NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX library_release_authorizations_lookup
ON library_release_authorizations(scope, snapshot_id, params_digest, expires_at DESC);
+11 -6
View File
@@ -11,13 +11,18 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 66 {
t.Fatalf("migration count = %d, want 66", len(migrations))
if len(migrations) != 67 {
t.Fatalf("migration count = %d, want 67", len(migrations))
}
if last := migrations[len(migrations)-1]; last.Version != 66 ||
!strings.Contains(last.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(last.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", last)
if last := migrations[len(migrations)-1]; last.Version != 67 ||
!strings.Contains(last.UpSQL, "library_release_authorizations") ||
!strings.Contains(last.UpSQL, "params_digest") {
t.Fatalf("migration 67 = %#v", last)
}
if prev := migrations[len(migrations)-2]; prev.Version != 66 ||
!strings.Contains(prev.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(prev.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", prev)
}
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
t.Fatalf("migration 1 = %#v", migrations[0])
@@ -0,0 +1,52 @@
package v071
import (
"context"
"errors"
"knowledge-governance/internal/libraryrelease"
)
// ErrProductionTargetUnconfigured 表示生产读/写适配器还没接线。
// 这是一个**显式缺项**,不是"暂时跳过":没有它就无法读生产当前状态、
// 无法建预备份、也无法验证或恢复,所以整条生产链路必须拒绝执行。
var ErrProductionTargetUnconfigured = errors.New("生产目标适配器未配置(需要生产端点、只读凭据与写入适配)")
// ProductionLibraryTarget 是整库同步的生产目标实现占位。
//
// 为什么先不做"半套"实现:读生产当前状态、写四类数据、验证与恢复必须同时成立,
// 只实现其中一半会让链路看起来可用却无法回滚。接口在此固定,接线时只补实现。
type ProductionLibraryTarget struct {
BaseURL string
APIKeyFile string
}
func NewProductionLibraryTarget(baseURL, apiKeyFile string) (*ProductionLibraryTarget, error) {
if baseURL == "" || apiKeyFile == "" {
return nil, ErrProductionTargetUnconfigured
}
return &ProductionLibraryTarget{BaseURL: baseURL, APIKeyFile: apiKeyFile}, nil
}
func (t *ProductionLibraryTarget) Current(context.Context) (libraryrelease.CurrentState, error) {
return libraryrelease.CurrentState{}, ErrProductionTargetUnconfigured
}
func (t *ProductionLibraryTarget) Apply(context.Context, libraryrelease.Stage, string) error {
return ErrProductionTargetUnconfigured
}
func (t *ProductionLibraryTarget) Verify(context.Context, libraryrelease.Expectation) error {
return ErrProductionTargetUnconfigured
}
func (t *ProductionLibraryTarget) Restore(context.Context, libraryrelease.BackupRef) error {
return ErrProductionTargetUnconfigured
}
// ArchiveBackupStore 也还没接线:预备份必须读生产当前整库,同样的前置条件。
type ArchiveBackupStore struct{}
func (ArchiveBackupStore) Prepare(context.Context, string, libraryrelease.CurrentState) (libraryrelease.BackupRef, error) {
return libraryrelease.BackupRef{}, errors.New("生产预备份存储未配置(需要生产读取凭据与可独立恢复的备份目标)")
}
@@ -0,0 +1,35 @@
package v071
import (
"context"
"errors"
"testing"
"knowledge-governance/internal/libraryrelease"
)
// 未配置时必须显式失败:不能返回零值让上层误以为"生产当前状态为空"。
func TestProductionLibraryTargetFailsClosedWhenUnconfigured(t *testing.T) {
if _, err := NewProductionLibraryTarget("", ""); !errors.Is(err, ErrProductionTargetUnconfigured) {
t.Fatalf("constructor must refuse empty configuration, got %v", err)
}
target, err := NewProductionLibraryTarget("http://prod.invalid", "/tmp/key")
if err != nil {
t.Fatal(err)
}
if _, err = target.Current(context.Background()); !errors.Is(err, ErrProductionTargetUnconfigured) {
t.Fatalf("Current must fail closed, got %v", err)
}
if err = target.Apply(context.Background(), libraryrelease.StageDatabase, "snap-1"); !errors.Is(err, ErrProductionTargetUnconfigured) {
t.Fatalf("Apply must fail closed, got %v", err)
}
if err = target.Verify(context.Background(), libraryrelease.Expectation{}); !errors.Is(err, ErrProductionTargetUnconfigured) {
t.Fatalf("Verify must fail closed, got %v", err)
}
if err = target.Restore(context.Background(), libraryrelease.BackupRef{}); !errors.Is(err, ErrProductionTargetUnconfigured) {
t.Fatalf("Restore must fail closed, got %v", err)
}
if _, err = (ArchiveBackupStore{}).Prepare(context.Background(), "snap-1", libraryrelease.CurrentState{}); err == nil {
t.Fatal("backup store must refuse until wired")
}
}
+3
View File
@@ -96,6 +96,7 @@ const overview: LibraryOverview = {
'本次目标快照还没有生产预备份',
],
},
authorization: { state: 'none', reason: '没有与目标快照匹配的有效发布授权' },
capture_available: true,
now: '2026-10-28T03:40:00Z',
}
@@ -182,6 +183,8 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
expect(html).toContain('生产写入闸口关闭')
expect(html).toContain('没有已核验的生产恢复演练证据')
expect(html).toContain('本次目标快照还没有生产预备份')
// 授权也必须可见:没有授权时说明需要管理员签发
expect(html).toContain('无有效授权(需管理员按目标+快照签发)')
expect(html).toContain('封存测试版本')
})
+19 -1
View File
@@ -319,11 +319,13 @@ function ProtectionCard({
production,
prebackup,
gate,
authorization,
onOpen,
}: {
production: LibraryOverview['production']
prebackup: LibraryOverview['prebackup']
gate: LibraryOverview['gate']
authorization: LibraryOverview['authorization']
onOpen: () => void
}) {
const backupKnown = prebackup.state === 'known' && prebackup.version
@@ -348,6 +350,12 @@ function ProtectionCard({
</dd>
<dt>备份范围</dt>
<dd>数据库 / 资源 / 索引 / Wiki</dd>
<dt>发布授权</dt>
<dd>
{authorization.state === 'active'
? `${authorization.authorized_by || '管理员'} 签发 · 有效至 ${stamp(authorization.expires_at ?? '')}`
: '无有效授权(需管理员按目标+快照签发)'}
</dd>
<dt>恢复条件</dt>
<dd>{gate.reasons.length === 0 ? '已满足' : `缺 ${gate.reasons.length} 项`}</dd>
</dl>
@@ -373,6 +381,7 @@ interface ReadyProps {
production: LibraryOverview['production']
prebackup: LibraryOverview['prebackup']
gate: LibraryOverview['gate']
authorization: LibraryOverview['authorization']
canCapture: boolean
canWrite: boolean
pendingCapture: boolean
@@ -386,6 +395,7 @@ function ReadyBody({
production,
prebackup,
gate,
authorization,
canCapture,
canWrite,
pendingCapture,
@@ -397,7 +407,13 @@ function ReadyBody({
<>
<div className="rel-grid">
<ChangeTable diff={diff} />
<ProtectionCard production={production} prebackup={prebackup} gate={gate} onOpen={onOpen} />
<ProtectionCard
production={production}
prebackup={prebackup}
gate={gate}
authorization={authorization}
onOpen={onOpen}
/>
</div>
<div className="rel-panel rel-jobbar">
<header className="rel-panel-head">
@@ -863,6 +879,7 @@ export function ReleaseTargetsView(props: ViewProps) {
removed: [],
}
const gate = view.overview?.gate ?? { sync_allowed: false, reasons: ['整库状态接口不可用'] }
const authorization = view.overview?.authorization ?? { state: 'none' as const, reason: '整库状态接口不可用' }
return (
<section className="release-targets" aria-label="发布管理">
@@ -1012,6 +1029,7 @@ export function ReleaseTargetsView(props: ViewProps) {
production={production}
prebackup={prebackup}
gate={gate}
authorization={authorization}
canCapture={canCapture}
canWrite={canWrite}
pendingCapture={pendingCapture}
+8
View File
@@ -282,6 +282,13 @@ export interface LibraryJobRecord {
stages: LibraryStageRow[]
}
export interface LibraryAuthorizationView {
state: 'active' | 'none'
authorized_by?: string
expires_at?: string
reason?: string
}
export interface LibraryGate {
sync_allowed: boolean
reasons: string[]
@@ -297,6 +304,7 @@ export interface LibraryOverview {
job?: LibraryJobRecord
jobs: LibraryJobRecord[]
gate: LibraryGate
authorization: LibraryAuthorizationView
capture_available: boolean
capture_reason?: string
now: string