Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cbce82e3f1 | |||
| 8210af7847 | |||
| e5040d88d8 | |||
| 839b4ca2cf | |||
| b662520439 | |||
| 9258aa8273 | |||
| 9dddda8491 | |||
| fe7edea1a3 | |||
| 28fb449d17 | |||
| f4b3f4c4c8 | |||
| f45b6fc8c9 | |||
| 082f77fc18 | |||
| dc28f0b65c | |||
| 1b2db5045a | |||
| a655f4cca8 | |||
| 5c34ef1429 | |||
| a55c8844a8 | |||
| f9e8e5e013 | |||
| 6e0382c3ba |
+3
-2
@@ -27,8 +27,9 @@ QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
|
||||
WEKNORA_RUNTIME_KEY_FILE=
|
||||
# 导入对账(T6)总开关:只接线对账服务、只用知识库绑定里的租户 Key。
|
||||
# 与 TEST_WEKNORA_ENABLED(旧取件/上传链路)解耦;默认关闭,生产按授权再开。
|
||||
RECONCILIATION_ENABLED=false
|
||||
RECONCILIATION_SCHEDULE_ENABLED=true
|
||||
RECONCILIATION_DAILY_AT=02:00
|
||||
RECONCILIATION_TIMEZONE=Asia/Shanghai
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.426(导入对账:运行时读复用知识库绑定 Key)
|
||||
|
||||
### Changed
|
||||
|
||||
- **运行时读不再单独维护平台只读 Key**:「导入对账」的 WeKnora 队列与「WeKnora 处理详情」改为每次请求解析「系统设置 → 知识库绑定」测试环境的地址与 Key,与对账扫描共用同一个 resolver;换 Key 保存后下一次请求即生效,无需重启。删除 `WEKNORA_RUNTIME_KEY_FILE` 配置、0400 文件读取与启动 WARN,`weknora.ReadRuntimeKeyFile` 一并移除。
|
||||
- **三种失败可区分**:绑定未配置/不可用 → 503 `runtime_read_unavailable`;上游 401/403 → 502 `runtime_read_forbidden`(缺 `system_runtime_read`);超时/DNS/连接失败 → 502 `runtime_read_unreachable`。`/api/v1/monitor/overview` 在队列不可用时给出 `weknora_queue_error`,页面显示三句不同指引,且保留「在 WeKnora 中打开」链接。
|
||||
- 同步 `docs/IMPORT_RECONCILIATION_REQUIREMENTS.md` §5/Q7、`docs/WEKNORA_091_PHASE_PLAN.md` 与 `docs/OPERATIONS_RUNBOOK.md`;`api/openapi.yaml` 的 progress 契约增加 502。
|
||||
|
||||
## 开发快照 0.1.425(WeKnora 0.9.1:schema 137 + 漏表门禁 + 编辑历史搬运)
|
||||
|
||||
### Added
|
||||
|
||||
+11
-1
@@ -50,7 +50,7 @@
|
||||
"/api/v1/reconciliation/findings/{id}/writeback": {"post":{"tags":["Reconciliation"],"operationId":"writebackReconciliationFinding","summary":"仅限 R5:以 WeKnora 状态回写台账 processing_state,写审计;completed 不可降级","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"reconciliation_writeback_stale 或迁移不允许"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/requeue": {"post":{"tags":["Reconciliation"],"operationId":"requeueReconciliationFinding","summary":"仅限 R1/R4:R1 清空 document_id 后重排上传;R4 先删旧知识再重传,删除失败则台账不变","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"finding 状态或台账身份已变化"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/remove": {"post":{"tags":["Reconciliation"],"operationId":"removeReconciliationFinding","summary":"仅限 R2:按远端 document_id 从测试库删除;404 视为已删除;重复点击幂等","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"该文档已被现行台账收养"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;未配置平台只读 Key 时返回 503 runtime_read_unavailable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
|
||||
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;绑定未配置/不可用返回 503 runtime_read_unavailable,上游 401/403 返回 502 runtime_read_forbidden,不可达返回 502 runtime_read_unreachable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"$ref":"#/components/responses/BadGateway"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
|
||||
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
|
||||
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。未覆盖的是否正确固定为待确认,拒绝是或否;已覆盖点踩固定为否。quality.correctness_rule=coverage-correctness-v1标记覆盖/正确性固定投影,原字段和复核证据保留","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
|
||||
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
|
||||
@@ -6161,6 +6161,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"BadGateway": {
|
||||
"description": "上游 WeKnora 拒绝或不可达:runtime_read_forbidden(Key 缺 system_runtime_read)或 runtime_read_unreachable(超时/DNS/连接失败)。",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ServiceUnavailable": {
|
||||
"description": "依赖的第三方或本地工具当前不可用(例如 dws 未登录/权限不足)。",
|
||||
"content": {
|
||||
|
||||
+12
-21
@@ -209,45 +209,36 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
result := readinessProber.Check(probeCtx)
|
||||
return result.Target, result.Err
|
||||
}
|
||||
// The runtime read (queues / document progress) and the reconciliation remote
|
||||
// must resolve the SAME knowledge-base binding: an admin who saves a new test
|
||||
// key in the console gets it applied on the next request, without a restart.
|
||||
resolveTestConnection := func(resolveCtx context.Context) (string, string, error) {
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
}
|
||||
knowledgeBaseLister := &weKnoraLister{
|
||||
resolve: func(resolveCtx context.Context) (string, string, error) {
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return connection.BaseURL, connection.APIKey, err
|
||||
},
|
||||
resolve: resolveTestConnection,
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
runtimeKey := ""
|
||||
if config.WeKnoraRuntimeKeyFile != "" {
|
||||
key, keyErr := weknora.ReadRuntimeKeyFile(config.WeKnoraRuntimeKeyFile)
|
||||
if keyErr != nil {
|
||||
log.Printf("WARN: WeKnora runtime read key is unavailable; runtime endpoints degrade to 503")
|
||||
} else {
|
||||
runtimeKey = key
|
||||
}
|
||||
}
|
||||
runtimeProvider := reconciliation.NewRuntimeProvider(reconciliation.RuntimeConfig{
|
||||
BaseURL: testEndpointResolver,
|
||||
APIKey: runtimeKey,
|
||||
Resolve: resolveTestConnection,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
})
|
||||
reconciliationRemote := &weknoraaccess.Client{
|
||||
Resolver: readiness.Resolver{
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
ResolveConnection: resolveTestConnection,
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
},
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
var reconciliationService httpapi.ReconciliationService
|
||||
if config.TestWeKnoraEnabled {
|
||||
if config.ReconciliationEnabled {
|
||||
service, serviceErr := reconciliation.New(reconciliation.Config{
|
||||
Store: actionStore,
|
||||
Remote: reconciliationRemote,
|
||||
|
||||
+16
-12
@@ -262,7 +262,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
|
||||
}
|
||||
var reconciliationService *reconciliation.Service
|
||||
if config.TestWeKnoraEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
if config.ReconciliationEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
reconciliationRemote := &weknoraaccess.Client{
|
||||
Resolver: readiness.Resolver{
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
@@ -619,6 +619,21 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
|
||||
}
|
||||
handlers["source.scan.pp"] = handler.Handle
|
||||
}
|
||||
// 导入对账的作业处理器只依赖对账服务本身(租户 Key 走知识库绑定),
|
||||
// 与旧测试库取件/上传链路(TEST_WEKNORA_ENABLED)无关,必须在下面那个
|
||||
// 早退之前注册;否则 RECONCILIATION_ENABLED=true 时候选只接线了 API,
|
||||
// worker 从不认领 reconciliation.run,批次永远停在 running。
|
||||
if reconciliationService != nil {
|
||||
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
|
||||
var payload struct {
|
||||
RunID string `json:"run_id"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
|
||||
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
|
||||
}
|
||||
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
|
||||
}
|
||||
}
|
||||
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
return handlers, nil
|
||||
}
|
||||
@@ -695,17 +710,6 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
|
||||
handlers["test.poll"] = poll.Handle
|
||||
handlers["test.validate"] = validate.Handle
|
||||
handlers["test.remove"] = remove.Handle
|
||||
if reconciliationService != nil {
|
||||
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
|
||||
var payload struct {
|
||||
RunID string `json:"run_id"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
|
||||
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
|
||||
}
|
||||
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
|
||||
}
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -68,9 +68,7 @@ services:
|
||||
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级;
|
||||
# Key 本身只挂载 secret 文件,绝不写进 compose。
|
||||
WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}"
|
||||
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
|
||||
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
|
||||
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
|
||||
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
|
||||
@@ -147,6 +145,7 @@ services:
|
||||
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
|
||||
TEST_WEKNORA_KB_ID: "${TEST_WEKNORA_KB_ID:-}"
|
||||
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
|
||||
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
|
||||
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
|
||||
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
|
||||
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
|
||||
|
||||
@@ -109,7 +109,7 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
|
||||
| --- | --- | --- |
|
||||
| 全量列出库内条目 | `GET /knowledge-bases/{id}/knowledge`(分页;可按 `parse_status`、`source`、时间、目录筛选) | 现有租户 API Key |
|
||||
| 单条确认 | `GET /knowledge/{id}` | 现有租户 API Key |
|
||||
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | **平台级 API Key,能力 `system_runtime_read`**(上游 `routes_auth_tenant.go:356`) |
|
||||
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | 知识库绑定(测试环境)里的 Key,需能力 `system_runtime_read`(上游 `routes_auth_tenant.go:356`) |
|
||||
| 队列深度 | `GET /system/admin/runtime/queues` | 同上 |
|
||||
|
||||
条目中对账要用的字段:`id`、`knowledge_base_id`、`channel`、`metadata`、`file_hash`、`parse_status`、`stall_state`、`enable_status`、`updated_at`。
|
||||
@@ -118,15 +118,16 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
|
||||
|
||||
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
|
||||
|
||||
**平台级 Key 的配置契约(Q7 已裁定)**
|
||||
**运行时读 Key 的配置契约(Q7,2026-12-02 改判)**
|
||||
|
||||
- 键名 `WEKNORA_RUNTIME_KEY_FILE`,值为**绝对路径**,secret 文件挂载进容器;不写进 compose 环境变量、不进 Git。
|
||||
- 启动时读取一次,权限 0400;换 Key 需重启平台(与现有 `*_API_KEY_FILE` 一致,不做热加载)。
|
||||
- “变量为空”与“变量有值但文件缺失/不可读”要区分:前者静默降级;后者启动不失败,写一条 WARN 日志,运行时按未配置处理。
|
||||
- 两种情况都让 `runtime/queues`、`runtime/documents/{id}` 返回 503 `runtime_read_unavailable`,`/monitor/overview` 的 `weknora_queues` 为 `null`;对账本身只需租户 Key,照常运行。
|
||||
- 不再单独维护平台级只读 Key:「导入对账」的 `runtime/queues` 与 `runtime/documents/{id}`(以及页面上的「WeKnora 处理详情」)直接使用「系统设置 → 知识库绑定」测试环境保存的地址与 Key,与对账扫描共用同一个 resolver。
|
||||
- 每次请求解析绑定;管理员换 Key 保存后,下一次请求即生效,不需要重启 API。不再读取任何 Key 文件。
|
||||
- 绑定未配置或无法解密 → 503 `runtime_read_unavailable`,页面指向绑定页;上游 401/403 → 502 `runtime_read_forbidden`,页面提示去 WeKnora 授权 `system_runtime_read`;超时/DNS 失败 → 502 `runtime_read_unreachable`,页面提示连不上 WeKnora。
|
||||
- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身(对账只用租户 Key 列库与读单条)。
|
||||
|
||||
## 6. 运行方式
|
||||
|
||||
- **开关**:`RECONCILIATION_ENABLED`(默认 `false`)只决定对账服务是否接线——关着时 9 个接口统一 503 `reconciliation_not_configured`;它与 `TEST_WEKNORA_ENABLED`(旧的取件/上传链路)解耦,因为对账只用知识库绑定里的租户 Key。候选/测试环境显式开启,生产按授权再开。
|
||||
- **对账批次**:每次对账生成一个批次(run),记录开始/结束时间、两侧计数、各类差异计数和明细。结果持久化,可以和上一成功批次比较。触发方式:定时(默认每天 02:00,可配)+ 页面手动触发。
|
||||
- **唯一观测时刻**:批次以 `run.started_at` 作为唯一的“现在”。R5 宽限期、R7 阈值和所有相对时间判断都用它,不用 `time.Now()`。同一批次因此可重放、可解释,验收里的“连续两次一致”才有定义。
|
||||
- **全量扫描必须完整**:整页翻完才算完成,中途失败整批标为 `failed`,不产出部分结论。不能用“最近 N 条”代替全量(陷阱 17)。扫描使用 `page_size=1000`(§5)。这里的“完整”指本批把所有页翻完,不承诺对并发写入做快照:扫描期间有增删时可能漏掉个别条目,漏掉的在下一批补上,批次记 `window_overlapped` 供解释;不为此引入游标或重扫(Q10)。
|
||||
@@ -239,7 +240,7 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
|
||||
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||
| Q7 | 运行时读 Key 的配置键名 | **已裁定(2026-12-02 改判)**:不再单独配置;复用知识库绑定(测试环境)的地址与 Key |
|
||||
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加“距上次发布 N 天” |
|
||||
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受并发增删造成的个别漏项在下一批补上,不引入游标 |
|
||||
|
||||
@@ -82,6 +82,8 @@ http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,
|
||||
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
|
||||
「同 ID 语义」,提示里会写明。
|
||||
|
||||
**导入对账的运行时读。** 队列栏与「WeKnora 处理详情」复用本页保存的测试环境地址与 Key(该 Key 需在 WeKnora 授予 `system_runtime_read`),不再挂载单独的只读 Key 文件。换 Key 保存后下一次刷新即生效,无需重启 API。三种失败提示分别指向:绑定未配置/不可用 → 本页;缺权限 → WeKnora 授权;连不上 → 检查地址与网络。
|
||||
|
||||
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
|
||||
|
||||
```bash
|
||||
|
||||
@@ -120,7 +120,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
- [ ] `schema_migrations` 应为 `137, false`
|
||||
- [ ] 抽查原有知识库的检索、问答是否正常
|
||||
- [ ] 测试环境额外检查:平台走一轮「取件 → 上传 → 解析 → 完成」
|
||||
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 创建平台级 API Key,只授予 `system_runtime_read` 能力,以 secret 文件形式交给平台(不写进 Git 或 compose),然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。生产不需要这个 Key
|
||||
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 给「系统设置 → 知识库绑定」里保存的那把 Key 授予 `system_runtime_read` 能力,然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。不再创建/挂载独立的平台只读 Key;生产不需要该能力
|
||||
- [ ] 生产额外检查:平台发布通道只读预检(`release-diag`)通过
|
||||
|
||||
**回退**:不能直接换回旧镜像。向下迁移会删除凭据表、截短审计字段。正确做法是停止写入后,用升级前的备份恢复数据库、存储和配置,再切回 v0.9.0 镜像。
|
||||
@@ -145,7 +145,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
- 新建 `reconciliation_runs` / `reconciliation_findings` 两张表:`runs` 永久保留;`findings` 按 `run_id` 整批清理,保留最近 30 批且不超过 90 天(Q5)。同一测试库的 `running` 批次用部分唯一索引约束(`WHERE state='running'`)。
|
||||
- 对账扫描使用 `page_size=1000`:要把 `internal/platform/weknora/client.go` 的 `validPage` 上限从 100 放开(或给对账单独一条扫描路径),不能沿用上传恢复的 100。扫描全程串行(在途 1 个请求),R1/R2 确认可用 `reconciliation_confirm_concurrency`(默认 1、上限 8),不复用 `ingestion_concurrency`。
|
||||
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `window_overlapped=true`,该批 R1/R2 的 `confirmation_state='pending'`(Q6)。
|
||||
- 平台级只读 Key 走 `WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,启动读取一次,不做热加载);未配置或文件不可读时 `runtime/*` 返回 503 `runtime_read_unavailable`,对账不受影响(Q7)。
|
||||
- 运行时读(队列与处理详情)复用知识库绑定(测试环境)的地址与 Key,每次请求解析、保存后即时生效,不单独维护 Key 文件;绑定不可用返回 503 `runtime_read_unavailable`,上游 401/403 返回 502 `runtime_read_forbidden`,不可达返回 502 `runtime_read_unreachable`,对账不受影响(Q7,2026-12-02 改判)。
|
||||
- 状态映射只写在服务端一处,接口返回 `normalized_state`;R5 回写按迁移矩阵校验,`completed` 不可降级。
|
||||
- 处置动作:新增 finding 级 `requeue`(R1/R4)与 `remove`(R2);R6 复用现有 `POST /test-publications/{id}/removal`(`removal-retry` 只重试已失败移除)。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
|
||||
- 扫描保留 offset 翻页,不引入游标;并发增删造成的个别漏项在下一批补上(Q10)。
|
||||
@@ -164,7 +164,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||
| Q7 | 运行时读 Key 的配置键名 | **已裁定(2026-12-02 改判)**:不再单独配置;复用知识库绑定(测试环境)的地址与 Key |
|
||||
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加"距上次发布 N 天" |
|
||||
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受个别漏项下一批补上,不引入游标 |
|
||||
|
||||
@@ -59,10 +59,10 @@ type Config struct {
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
// WeKnoraRuntimeKeyFile 是测试实例平台级只读 Key(0400,绝对路径)。空值=
|
||||
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
|
||||
WeKnoraRuntimeKeyFile string
|
||||
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
|
||||
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
|
||||
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
|
||||
ReconciliationEnabled bool
|
||||
ReconciliationScheduleEnabled bool
|
||||
ReconciliationDailyAt string
|
||||
ReconciliationTimezone string
|
||||
@@ -239,7 +239,6 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
WeKnoraRuntimeKeyFile: strings.TrimSpace(getenv("WEKNORA_RUNTIME_KEY_FILE")),
|
||||
ReconciliationDailyAt: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_DAILY_AT")), "02:00"),
|
||||
ReconciliationTimezone: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_TIMEZONE")), "Asia/Shanghai"),
|
||||
ReconciliationScheduleEnabled: true,
|
||||
@@ -403,8 +402,11 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
|
||||
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
|
||||
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("RECONCILIATION_ENABLED: %w", err)
|
||||
}
|
||||
}
|
||||
if raw := getenv("RECONCILIATION_SCHEDULE_ENABLED"); raw != "" {
|
||||
config.ReconciliationScheduleEnabled, err = strconv.ParseBool(raw)
|
||||
|
||||
@@ -6,6 +6,28 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoadParsesReconciliationEnabledWithoutLegacyTestWeKnora(t *testing.T) {
|
||||
values := map[string]string{"DATA" + "BASE_URL": "postgres://example"}
|
||||
config, err := Load(func(key string) string { return values[key] })
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error = %v", err)
|
||||
}
|
||||
if config.ReconciliationEnabled {
|
||||
t.Fatal("reconciliation must stay un-wired unless RECONCILIATION_ENABLED is set")
|
||||
}
|
||||
values["RECONCILIATION_ENABLED"] = "true"
|
||||
config, err = Load(func(key string) string { return values[key] })
|
||||
if err != nil {
|
||||
t.Fatalf("Load() with RECONCILIATION_ENABLED error = %v", err)
|
||||
}
|
||||
if !config.ReconciliationEnabled {
|
||||
t.Fatal("RECONCILIATION_ENABLED=true must wire reconciliation")
|
||||
}
|
||||
if config.TestWeKnoraEnabled {
|
||||
t.Fatal("reconciliation must not require or imply the legacy test WeKnora pipeline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadUsesSafeDefaults(t *testing.T) {
|
||||
values := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
config, err := Load(func(key string) string { return values[key] })
|
||||
|
||||
@@ -115,6 +115,10 @@ type MonitorOverview struct {
|
||||
// WeKnoraQueues is a safe projection of the test instance runtime queues.
|
||||
// nil means "not configured or unreadable", never "healthy empty".
|
||||
WeKnoraQueues *WeKnoraQueueSummary `json:"weknora_queues"`
|
||||
// WeKnoraQueueError carries the classified reason when WeKnoraQueues is nil
|
||||
// (binding missing, key lacks permission, or instance unreachable). Empty
|
||||
// means no runtime queue reader was wired.
|
||||
WeKnoraQueueError string `json:"weknora_queue_error,omitempty"`
|
||||
}
|
||||
|
||||
// WeKnoraQueueSummary is the bounded queue projection the console may show.
|
||||
|
||||
@@ -46,6 +46,10 @@ func writeReconciliationError(w http.ResponseWriter, err error) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "reconciliation record not found"})
|
||||
case errors.Is(err, reconciliation.ErrActionConflict), errors.Is(err, reconciliation.ErrActionNotAllowed):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_state_changed", "code": "reconciliation_state_changed"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeForbidden):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_read_forbidden", "code": "runtime_read_forbidden"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnreachable):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_read_unreachable", "code": "runtime_read_unreachable"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnavailable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_read_unavailable", "code": "runtime_read_unavailable"})
|
||||
case errors.Is(err, reconciliation.ErrRemoteFailed):
|
||||
|
||||
@@ -126,3 +126,46 @@ func TestReconciliationFindingTypeValidation(t *testing.T) {
|
||||
t.Fatalf("invalid type = %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconciliationProgressRejectsMalformedDocumentIDWith400(t *testing.T) {
|
||||
service := &reconciliationServiceStub{}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{
|
||||
"/api/v1/reconciliation/documents//progress",
|
||||
"/api/v1/reconciliation/documents/doc-1/extra/progress",
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, path, roleViewer, ""))
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "invalid document id") {
|
||||
t.Fatalf("%s = %d %s, want 400 invalid document id", path, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconciliationProgressUpstreamFailureCodes(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
{name: "key lacks permission", err: reconciliation.ErrRuntimeForbidden, status: http.StatusBadGateway, code: "runtime_read_forbidden"},
|
||||
{name: "upstream unreachable", err: reconciliation.ErrRuntimeUnreachable, status: http.StatusBadGateway, code: "runtime_read_unreachable"},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: &reconciliationServiceStub{err: testCase.err}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/documents/doc-1/progress", roleViewer, ""))
|
||||
if recorder.Code != testCase.status || !strings.Contains(recorder.Body.String(), testCase.code) {
|
||||
t.Fatalf("progress = %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -855,15 +855,32 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/job-failures/{id}/requeue", func(w http.ResponseWriter, r *http.Request) {
|
||||
requeueJobFailure(w, r, config)
|
||||
})
|
||||
// 契约要求非法 document_id 返回 400:空段(documents//progress)会被 ServeMux
|
||||
// 规范化成 307,含未编码斜杠的 id 会落到 404。这里在路由前判定形状,且不新增
|
||||
// 端点(契约已冻结);放在鉴权之后,未登录仍是 401,保持 401 → 400 的顺序。
|
||||
guard := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
const prefix = "/api/v1/reconciliation/documents/"
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
rest := strings.TrimPrefix(r.URL.Path, prefix)
|
||||
segments := strings.Split(rest, "/")
|
||||
if strings.Contains(r.URL.Path, "//") || len(segments) != 2 || segments[0] == "" || segments[1] != "progress" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid document id"})
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
if config.Auth != nil {
|
||||
if config.Auth.Store == nil {
|
||||
return nil, errors.New("auth configuration requires a store")
|
||||
}
|
||||
config.authRoutes(mux)
|
||||
config.userRoutes(mux)
|
||||
return masterNoStore(config.Auth.authenticate(mux)), nil
|
||||
return masterNoStore(config.Auth.authenticate(guard(mux))), nil
|
||||
}
|
||||
return masterNoStore(mux), nil
|
||||
return masterNoStore(guard(mux)), nil
|
||||
}
|
||||
|
||||
type createJobRequest struct {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
type Database interface {
|
||||
@@ -133,9 +134,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
governance.MonitorService{Key: "oss", Name: "OSS", State: "unknown", Detail: "未配置独立健康探测", ObservedAt: now},
|
||||
)
|
||||
if provider.runtimeQueues != nil {
|
||||
if queues, queueErr := provider.runtimeQueues.Queues(ctx); queueErr == nil {
|
||||
overview.WeKnoraQueues = queues
|
||||
}
|
||||
overview.WeKnoraQueues, overview.WeKnoraQueueError = runtimeQueueProjection(ctx, provider.runtimeQueues)
|
||||
}
|
||||
rows, err := provider.db.Query(ctx, `SELECT p.test_kb_id,
|
||||
CASE WHEN COUNT(DISTINCT p.target_scope)=1 THEN MIN(p.target_scope) ELSE 'mixed' END,
|
||||
@@ -396,3 +395,16 @@ func monitorStageDetail(ingestState, processingState, errorCode string) string {
|
||||
return "等待远端状态更新"
|
||||
}
|
||||
}
|
||||
|
||||
// runtimeQueueProjection keeps the overview at 200 while stating why the queue
|
||||
// is absent: nil queues + the classified code, never a healthy empty queue.
|
||||
func runtimeQueueProjection(ctx context.Context, reader QueueReader) (*governance.WeKnoraQueueSummary, string) {
|
||||
if reader == nil {
|
||||
return nil, ""
|
||||
}
|
||||
queues, err := reader.Queues(ctx)
|
||||
if err != nil {
|
||||
return nil, reconciliation.RuntimeErrorCode(err)
|
||||
}
|
||||
return queues, ""
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package monitoring
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
func TestParseCPUStatAndMemoryInfo(t *testing.T) {
|
||||
idle, total, err := parseCPUStat("cpu 100 20 30 400 50 6 7 8 0 0\n")
|
||||
@@ -22,3 +29,41 @@ func TestCPUPercentUsesTwoMonotonicSamples(t *testing.T) {
|
||||
t.Fatal("non-monotonic CPU counters must fail closed to zero")
|
||||
}
|
||||
}
|
||||
|
||||
type stubQueueReader struct {
|
||||
summary *governance.WeKnoraQueueSummary
|
||||
err error
|
||||
}
|
||||
|
||||
func (reader stubQueueReader) Queues(context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
return reader.summary, reader.err
|
||||
}
|
||||
|
||||
func TestRuntimeQueueProjectionStatesWhyQueueIsAbsent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{name: "binding unavailable", err: reconciliation.ErrRuntimeUnavailable, code: "runtime_read_unavailable"},
|
||||
{name: "key forbidden", err: reconciliation.ErrRuntimeForbidden, code: "runtime_read_forbidden"},
|
||||
{name: "unreachable", err: reconciliation.ErrRuntimeUnreachable, code: "runtime_read_unreachable"},
|
||||
{name: "unclassified", err: errors.New("boom"), code: ""},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{err: testCase.err})
|
||||
if queues != nil || code != testCase.code {
|
||||
t.Fatalf("queues=%v code=%q, want nil/%q", queues, code, testCase.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{Available: true}
|
||||
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{summary: summary})
|
||||
if queues != summary || code != "" {
|
||||
t.Fatalf("available queue projection = %v/%q", queues, code)
|
||||
}
|
||||
if queues, code := runtimeQueueProjection(context.Background(), nil); queues != nil || code != "" {
|
||||
t.Fatalf("unwired projection = %v/%q", queues, code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,3 +72,91 @@ func TestReconciliationRunUniquenessStaleAndRetentionIntegration(t *testing.T) {
|
||||
t.Fatalf("new findings=%d err=%v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScheduledReconciliationClaimsOncePerDayAfterFailure freezes the operator
|
||||
// expectation "每天最多一批": a failed scheduled batch keeps the day's slot so a
|
||||
// transient upstream error cannot spawn a new batch on every scheduler tick.
|
||||
// A retry after a failure is an explicit manual trigger.
|
||||
func TestScheduledReconciliationClaimsOncePerDayAfterFailure(t *testing.T) {
|
||||
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
dayStart := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
|
||||
run := func(id string, started time.Time) governance.ReconciliationRun {
|
||||
return governance.ReconciliationRun{ID: id, KBID: "kb-sched", State: "running", Trigger: "schedule",
|
||||
StartedAt: started, Counts: governance.ReconciliationCounts{}}
|
||||
}
|
||||
first, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-1", dayStart.Add(2*time.Hour)), dayStart, dayStart.Add(2*time.Hour))
|
||||
if err != nil || !claimed {
|
||||
t.Fatalf("first claim claimed=%t err=%v", claimed, err)
|
||||
}
|
||||
if err := store.FailReconciliationRun(ctx, first.ID, "remote_scan_failed", dayStart.Add(2*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-2", dayStart.Add(3*time.Minute)), dayStart, dayStart.Add(3*time.Minute)); err != nil || claimed {
|
||||
t.Fatalf("same-day reclaim after failure claimed=%t err=%v", claimed, err)
|
||||
}
|
||||
nextDay := dayStart.Add(24 * time.Hour)
|
||||
if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-3", nextDay.Add(2*time.Hour)), nextDay, nextDay.Add(2*time.Hour)); err != nil || !claimed {
|
||||
t.Fatalf("next-day claim claimed=%t err=%v", claimed, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadReconciliationActionViewJoinsWithoutAmbiguity freezes the action-view
|
||||
// SQL: it joins reconciliation_runs and test_publications, both of which also
|
||||
// own id/title/path, so an unqualified column list fails with
|
||||
// `column reference "id" is ambiguous` and every writeback/requeue/remove
|
||||
// answered 500 instead of touching the finding.
|
||||
func TestLoadReconciliationActionViewJoinsWithoutAmbiguity(t *testing.T) {
|
||||
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := time.Date(2026, 12, 1, 2, 0, 0, 0, time.UTC)
|
||||
exec := func(query string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, query, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
exec(`INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-action','dingtalk','处置视图用例',TRUE)`)
|
||||
exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state)
|
||||
VALUES('si-action','conn-action','action.md',repeat('d',64),'处置视图','file','blocked')`)
|
||||
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-action','si-action','r1','verified')`)
|
||||
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
|
||||
VALUES('pub-action','sv-action','kb-action','doc-action','uploaded','completed','unpublished')`)
|
||||
exec(`INSERT INTO reconciliation_runs(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
VALUES('run-action','kb-action','succeeded','manual',$1,'{}'::jsonb,$1)`, started)
|
||||
exec(`INSERT INTO reconciliation_findings(id,run_id,finding_type,publication_id,knowledge_id,title,ledger_state,suggested_action)
|
||||
VALUES('finding-action','run-action','R6','pub-action','doc-action','处置视图','completed','enter_removal')`)
|
||||
|
||||
store := NewStore(pool)
|
||||
view, err := store.LoadReconciliationActionView(ctx, "finding-action")
|
||||
if err != nil {
|
||||
t.Fatalf("action view error = %v (ambiguous columns surface here)", err)
|
||||
}
|
||||
if view.TestKBID != "kb-action" || !view.CurrentExists || view.CurrentProcessingState != "completed" ||
|
||||
view.CurrentKnowledgeID != "doc-action" || view.Finding.ID != "finding-action" {
|
||||
t.Fatalf("action view = %#v", view)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -72,16 +73,19 @@ func (s *Store) ClaimScheduledReconciliationRun(ctx context.Context, run governa
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, false, err
|
||||
}
|
||||
// The KB id is passed twice on purpose: PostgreSQL deduces varchar(255) for
|
||||
// the INSERT target and varchar for the comparison, and one parameter used in
|
||||
// both positions fails with 42P08 "inconsistent types deduced".
|
||||
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
|
||||
(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
SELECT $1,$2,'running','schedule',$3,$4::jsonb,$5
|
||||
WHERE NOT EXISTS(
|
||||
SELECT 1 FROM reconciliation_runs
|
||||
WHERE test_kb_id=$2 AND trigger='schedule' AND state IN ('running','succeeded') AND started_at >= $6
|
||||
WHERE test_kb_id=$7 AND trigger='schedule' AND state IN ('running','succeeded','failed') AND started_at >= $6
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING `+reconciliationRunColumns,
|
||||
run.ID, run.KBID, run.StartedAt, counts, now, since)
|
||||
run.ID, run.KBID, run.StartedAt, counts, now, since, run.KBID)
|
||||
claimed, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, false, nil
|
||||
@@ -312,6 +316,19 @@ const reconciliationFindingColumns = `id,run_id,finding_type,publication_id,know
|
||||
target_scope,ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
|
||||
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,weknora_url`
|
||||
|
||||
// qualifiedFindingColumns prefixes every column with the table alias. A bare
|
||||
// column list breaks as soon as the finding is joined with reconciliation_runs
|
||||
// or test_publications: those tables also have id/title/path/source, so
|
||||
// PostgreSQL rejects the statement with "column reference \"id\" is ambiguous"
|
||||
// and every writeback/requeue/remove answered 500.
|
||||
func qualifiedFindingColumns(alias string) string {
|
||||
columns := strings.Split(reconciliationFindingColumns, ",")
|
||||
for index, column := range columns {
|
||||
columns[index] = alias + "." + strings.TrimSpace(column)
|
||||
}
|
||||
return strings.Join(columns, ",")
|
||||
}
|
||||
|
||||
func scanReconciliationFinding(row rowScanner) (governance.ReconciliationFinding, error) {
|
||||
var finding governance.ReconciliationFinding
|
||||
if err := row.Scan(&finding.ID, &finding.RunID, &finding.Type, &finding.PublicationID, &finding.DocumentID,
|
||||
@@ -387,7 +404,7 @@ func lockOpenReconciliationFinding(ctx context.Context, tx pgx.Tx, id string) er
|
||||
func (s *Store) LoadReconciliationActionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
|
||||
var view governance.ReconciliationActionView
|
||||
var currentExists bool
|
||||
row := s.db.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+`,
|
||||
row := s.db.QueryRow(ctx, `SELECT `+qualifiedFindingColumns("finding")+`,
|
||||
run.test_kb_id,run.started_at,
|
||||
publication.id IS NOT NULL,
|
||||
COALESCE(publication.processing_state,''),COALESCE(publication.knowledge_id,''),
|
||||
|
||||
@@ -47,42 +47,3 @@ func ReadAPIKeyFile(path string) (string, error) {
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
|
||||
// contract at mode 0400: unlike tenant keys (0600), this key must not be
|
||||
// readable by the process owner's group and never leaves the API process.
|
||||
func ReadRuntimeKeyFile(path string) (string, error) {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open runtime key file: %w", err)
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
|
||||
if file == nil {
|
||||
_ = syscall.Close(fd)
|
||||
return "", errors.New("open runtime key file: invalid file descriptor")
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("inspect runtime key file: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", errors.New("runtime key file must be a regular file")
|
||||
}
|
||||
if info.Mode().Perm() != 0o400 {
|
||||
return "", errors.New("runtime key file permissions must be 0400")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read runtime key file: %w", err)
|
||||
}
|
||||
if len(body) > maxAPIKeyFileBytes {
|
||||
return "", errors.New("runtime key file is too large")
|
||||
}
|
||||
key := strings.TrimSpace(string(body))
|
||||
if key == "" {
|
||||
return "", errors.New("runtime key file is empty")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
@@ -53,20 +53,3 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
|
||||
path := t.TempDir() + "/runtime-key"
|
||||
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := ReadRuntimeKeyFile(path)
|
||||
if err != nil || key != "runtime-secret" {
|
||||
t.Fatalf("key=%q err=%v", key, err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadRuntimeKeyFile(path); err == nil {
|
||||
t.Fatal("0600 runtime key must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@ package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -9,9 +13,12 @@ import (
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// RuntimeConfig.Resolve runs for every request instead of once at startup: the
|
||||
// runtime read uses the same knowledge-base binding (test environment) as the
|
||||
// reconciliation remote, so an admin saving a new key must take effect on the
|
||||
// next request without restarting the API.
|
||||
type RuntimeConfig struct {
|
||||
BaseURL func(context.Context) string
|
||||
APIKey string
|
||||
Resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
@@ -19,8 +26,7 @@ type RuntimeConfig struct {
|
||||
}
|
||||
|
||||
type RuntimeProvider struct {
|
||||
baseURL func(context.Context) string
|
||||
apiKey string
|
||||
resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
@@ -32,26 +38,28 @@ func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
|
||||
config.Now = time.Now
|
||||
}
|
||||
return &RuntimeProvider{
|
||||
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
|
||||
resolve: config.Resolve, timeout: config.Timeout,
|
||||
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Available() bool {
|
||||
return p != nil && p.apiKey != "" && p.baseURL != nil
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
|
||||
if !p.Available() {
|
||||
if p == nil || p.resolve == nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL := strings.TrimSpace(p.baseURL(ctx))
|
||||
if baseURL == "" {
|
||||
baseURL, apiKey, err := p.resolve(ctx)
|
||||
if err != nil {
|
||||
// Not configured, storage locked, or the saved key cannot be opened:
|
||||
// all of them mean "no usable binding", never "upstream rejected us".
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL, apiKey = strings.TrimSpace(baseURL), strings.TrimSpace(apiKey)
|
||||
if baseURL == "" || apiKey == "" {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: p.apiKey,
|
||||
APIKey: apiKey,
|
||||
Timeout: p.timeout,
|
||||
AllowDockerHTTP: p.allowDockerHTTP,
|
||||
AllowPrivateHTTP: p.allowPrivateHTTP,
|
||||
@@ -62,6 +70,28 @@ func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, e
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// classifyRuntimeFailure separates the reasons an operator can act on. 401/403
|
||||
// means the bound key lacks system_runtime_read; DNS/timeout/connection failures
|
||||
// mean the instance is unreachable. Everything else keeps the legacy
|
||||
// "unavailable" code so existing callers do not lose their 503 contract.
|
||||
func classifyRuntimeFailure(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch weknora.StatusCode(err) {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return fmt.Errorf("%w: %v", ErrRuntimeForbidden, err)
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return fmt.Errorf("%w: %v", ErrRuntimeUnreachable, err)
|
||||
}
|
||||
var networkErr net.Error
|
||||
if errors.As(err, &networkErr) {
|
||||
return fmt.Errorf("%w: %v", ErrRuntimeUnreachable, err)
|
||||
}
|
||||
return ErrRuntimeUnavailable
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
client, err := p.client(ctx)
|
||||
if err != nil {
|
||||
@@ -73,7 +103,7 @@ func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueS
|
||||
defer cancel()
|
||||
queues, err := client.Queues(queueCtx)
|
||||
if err != nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
return nil, classifyRuntimeFailure(err)
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{
|
||||
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
|
||||
@@ -99,7 +129,7 @@ func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID strin
|
||||
if weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationProgress{}, err
|
||||
}
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
return governance.ReconciliationProgress{}, classifyRuntimeFailure(err)
|
||||
}
|
||||
progress := governance.ReconciliationProgress{
|
||||
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
|
||||
|
||||
@@ -7,12 +7,17 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
func staticConnection(baseURL, apiKey string) func(context.Context) (string, string, error) {
|
||||
return func(context.Context) (string, string, error) { return baseURL, apiKey, nil }
|
||||
}
|
||||
|
||||
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != "runtime-key" {
|
||||
@@ -37,8 +42,8 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
queues, err := provider.Queues(context.Background())
|
||||
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
|
||||
@@ -53,22 +58,135 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The binding is editable from the console, so the provider must ask for the
|
||||
// key on every request instead of freezing the first one it sees.
|
||||
func TestRuntimeProviderResolvesKeyOnEveryRequest(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.Header.Get("X-API-Key"))
|
||||
mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"available": true, "queues": []map[string]any{}})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
mu.Lock()
|
||||
key := "old-key"
|
||||
mu.Unlock()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return server.URL, key, nil
|
||||
},
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
key = "new-key"
|
||||
mu.Unlock()
|
||||
if _, err := provider.Queues(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(seen) != 2 || seen[0] != "old-key" || seen[1] != "new-key" {
|
||||
t.Fatalf("request keys = %v, want [old-key new-key]", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderClassifiesUpstreamFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
want error
|
||||
}{
|
||||
{name: "unauthorized", status: http.StatusUnauthorized, want: ErrRuntimeForbidden},
|
||||
{name: "forbidden", status: http.StatusForbidden, want: ErrRuntimeForbidden},
|
||||
{name: "server error still unavailable", status: http.StatusInternalServerError, want: ErrRuntimeUnavailable},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(testCase.status)
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("queues err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("progress err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderClassifiesUnreachable(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
url := server.URL
|
||||
server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: staticConnection(url, "runtime-key"),
|
||||
Timeout: time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnreachable) {
|
||||
t.Fatalf("queues err = %v, want %v", err, ErrRuntimeUnreachable)
|
||||
}
|
||||
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnreachable) {
|
||||
t.Fatalf("progress err = %v, want %v", err, ErrRuntimeUnreachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) { return "", "", nil },
|
||||
})
|
||||
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("unconfigured queues err=%v", err)
|
||||
}
|
||||
broken := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) {
|
||||
return "", "", errors.New("binding storage is not ready")
|
||||
},
|
||||
})
|
||||
if _, err := broken.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("broken binding err=%v", err)
|
||||
}
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
|
||||
t.Fatalf("missing document err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeErrorCodeDistinguishesStates(t *testing.T) {
|
||||
cases := map[string]error{
|
||||
"runtime_read_unavailable": ErrRuntimeUnavailable,
|
||||
"runtime_read_forbidden": ErrRuntimeForbidden,
|
||||
"runtime_read_unreachable": ErrRuntimeUnreachable,
|
||||
"": errors.New("unclassified"),
|
||||
}
|
||||
for want, err := range cases {
|
||||
if got := RuntimeErrorCode(err); got != want {
|
||||
t.Fatalf("RuntimeErrorCode(%v) = %q, want %q", err, got, want)
|
||||
}
|
||||
}
|
||||
if got := RuntimeErrorCode(nil); got != "" {
|
||||
t.Fatalf("RuntimeErrorCode(nil) = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The progress passthrough is a projection, not a proxy: whatever extra fields
|
||||
// the platform endpoint returns (keys, authorization headers, token echoes) must
|
||||
// never reach the browser. This guards the shape if someone later switches to
|
||||
@@ -89,8 +207,8 @@ func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
|
||||
if err != nil {
|
||||
|
||||
@@ -278,11 +278,7 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
removalByPublication := make(map[string]bool, len(removal))
|
||||
for _, row := range removal {
|
||||
removalByPublication[row.PublicationID] = true
|
||||
}
|
||||
|
||||
// 「需下架」的台账细节沿用上面按 publication 建的台账索引。
|
||||
for _, row := range ledger {
|
||||
if !expectedLive(row) {
|
||||
continue
|
||||
@@ -305,15 +301,6 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
|
||||
if finding, ok := s.r4Finding(row, item, normalized); ok {
|
||||
add(finding)
|
||||
}
|
||||
if removalByPublication[row.PublicationID] && item.ParseStatus == "completed" {
|
||||
add(governance.ReconciliationFinding{
|
||||
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
|
||||
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: "enter_removal",
|
||||
Detail: "来源已判禁止导入,条目仍在测试库可检索",
|
||||
})
|
||||
}
|
||||
if row.ProcessingState == "cancelled" {
|
||||
if normalized != "cancelled" && ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) >= s.grace {
|
||||
add(r5Finding(row, item, normalized, "none", "台账已取消,WeKnora 仍有活动状态"))
|
||||
@@ -355,6 +342,51 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
|
||||
}
|
||||
}
|
||||
|
||||
// R6: 应下架仍在。判定口径 = removal_candidates 视图(与 /monitor/overview 的
|
||||
// 「需下架」共用同一实现,陷阱 15)。这里直接由视图行生成,不再附加「本轮扫描
|
||||
// 见到该条目」「上游 parse_status=completed」这类只有对账侧才有的条件——上游仍在
|
||||
// processing/finalizing、或单条读取失败导致扫描缺行时,两处数字就会永久不一致。
|
||||
for _, row := range removal {
|
||||
finding := governance.ReconciliationFinding{
|
||||
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
// 视图只收录 processing_state='completed' 的台账行。
|
||||
LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "enter_removal",
|
||||
Detail: "来源已判禁止导入,条目仍在测试库可检索",
|
||||
}
|
||||
if own, ok := ledgerByPublication[row.PublicationID]; ok {
|
||||
if finding.DocumentID == "" {
|
||||
finding.DocumentID = own.KnowledgeID
|
||||
}
|
||||
if finding.Title == "" {
|
||||
finding.Title = own.Title
|
||||
}
|
||||
if finding.Path == "" {
|
||||
finding.Path = own.Path
|
||||
}
|
||||
if finding.Source == "" {
|
||||
finding.Source = own.SourceName
|
||||
}
|
||||
if finding.TargetScope == "" {
|
||||
finding.TargetScope = own.TargetScope
|
||||
}
|
||||
if own.ProcessingState != "" {
|
||||
finding.LedgerState = own.ProcessingState
|
||||
}
|
||||
finding.LedgerSHA256 = own.SHA256
|
||||
}
|
||||
if item, ok := byID[finding.DocumentID]; ok {
|
||||
if normalized, known := normalizeParseStatus(item.ParseStatus); known {
|
||||
finding.NormalizedState = normalized
|
||||
}
|
||||
finding.WeKnoraParseState = item.ParseStatus
|
||||
finding.WeKnoraFileMD5 = normalizeMD5(item.FileHash)
|
||||
} else if finding.DocumentID != "" {
|
||||
finding.Detail = "来源已判禁止导入;本轮扫描未见该条目,计数仍与总览「需下架」一致"
|
||||
}
|
||||
add(finding)
|
||||
}
|
||||
|
||||
// R8: one publication id maps to more than one live row.
|
||||
grouped := make(map[string][]weknora.Knowledge)
|
||||
for _, item := range items {
|
||||
|
||||
@@ -21,8 +21,25 @@ var (
|
||||
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
|
||||
ErrRemoteFailed = errors.New("reconciliation remote call failed")
|
||||
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
|
||||
ErrRuntimeForbidden = errors.New("weknora runtime read permission missing")
|
||||
ErrRuntimeUnreachable = errors.New("weknora runtime endpoint unreachable")
|
||||
)
|
||||
|
||||
// RuntimeErrorCode is the stable code the browser branches on. Unclassified
|
||||
// failures return "" so callers keep their generic fallback instead of guessing.
|
||||
func RuntimeErrorCode(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ErrRuntimeForbidden):
|
||||
return "runtime_read_forbidden"
|
||||
case errors.Is(err, ErrRuntimeUnreachable):
|
||||
return "runtime_read_unreachable"
|
||||
case errors.Is(err, ErrRuntimeUnavailable):
|
||||
return "runtime_read_unavailable"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
|
||||
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
|
||||
@@ -214,8 +231,15 @@ func (s *Service) enqueueRun(ctx context.Context, runID string, now time.Time) e
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// jobs.id is VARCHAR(36) and the run id alone already fills it ("rec-" + 32 hex),
|
||||
// so the job carries its own id; idempotency is guaranteed by the unique
|
||||
// idempotency_key below, not by deriving the id from the run.
|
||||
jobID, err := newID("job-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.queue.Enqueue(ctx, jobs.EnqueueRequest{
|
||||
ID: "job-" + runID,
|
||||
ID: jobID,
|
||||
Type: "reconciliation.run",
|
||||
Payload: payload,
|
||||
Priority: 5,
|
||||
@@ -321,6 +345,11 @@ func (s *Service) Progress(ctx context.Context, documentID string) (governance.R
|
||||
return progress, nil
|
||||
case weknora.StatusCode(err) == 404:
|
||||
return governance.ReconciliationProgress{}, ErrNotFound
|
||||
case errors.Is(err, ErrRuntimeUnavailable), errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable):
|
||||
// The provider already classified the failure; collapsing it here would
|
||||
// erase the distinction between "no binding", "no permission" and
|
||||
// "unreachable" that the page needs.
|
||||
return governance.ReconciliationProgress{}, err
|
||||
default:
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/weknoraaccess"
|
||||
@@ -60,6 +61,7 @@ type fakeReconciliationStore struct {
|
||||
removeHit bool
|
||||
requeueDoc string
|
||||
orphan bool
|
||||
enqueued []jobs.EnqueueRequest
|
||||
}
|
||||
|
||||
func (f *fakeReconciliationStore) ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error) {
|
||||
@@ -133,6 +135,11 @@ func (f *fakeReconciliationStore) MarkReconciliationOrphanRemoved(context.Contex
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeReconciliationStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
|
||||
f.enqueued = append(f.enqueued, request)
|
||||
return &jobs.Job{ID: request.ID}, nil
|
||||
}
|
||||
|
||||
type fakeReconciliationRemote struct {
|
||||
items []weknora.Knowledge
|
||||
missing map[string]bool
|
||||
@@ -480,3 +487,132 @@ func TestRemoveR2RechecksOwnershipAndTreats404AsSuccess(t *testing.T) {
|
||||
t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecuteRunR6UsesRemovalCandidatesViewOnly freezes 陷阱 15: R6 and
|
||||
// /monitor/overview must read one implementation. An upstream document still
|
||||
// processing/finalizing, or a single read that misses the listing, must not
|
||||
// remove a row from the R6 set — otherwise the two pages report different
|
||||
// "需下架" numbers for the same instant.
|
||||
func TestExecuteRunR6UsesRemovalCandidatesViewOnly(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
ledger := []governance.ReconciliationLedgerRow{
|
||||
{PublicationID: "pub-a", KnowledgeID: "doc-a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
|
||||
{PublicationID: "pub-b", KnowledgeID: "doc-b", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
|
||||
{PublicationID: "pub-c", KnowledgeID: "doc-c", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
|
||||
}
|
||||
items := []weknora.Knowledge{
|
||||
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-a"}},
|
||||
{ID: "doc-c", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-c"}},
|
||||
}
|
||||
store := &fakeReconciliationStore{
|
||||
run: governance.ReconciliationRun{ID: "run-r6", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
|
||||
ledger: ledger,
|
||||
// The view is the authority: it lists three rows, including one whose
|
||||
// upstream document is still processing and one absent from the scan.
|
||||
removal: []governance.ReconciliationLedgerRow{
|
||||
{PublicationID: "pub-a", KnowledgeID: "doc-a"},
|
||||
{PublicationID: "pub-b", KnowledgeID: "doc-b"},
|
||||
{PublicationID: "pub-c", KnowledgeID: "doc-c"},
|
||||
},
|
||||
}
|
||||
remote := &fakeReconciliationRemote{items: items, missing: map[string]bool{"doc-b": true}}
|
||||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
|
||||
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
|
||||
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
|
||||
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.ExecuteRun(context.Background(), "run-r6"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r6 := map[string]governance.ReconciliationFinding{}
|
||||
for _, finding := range store.findings {
|
||||
if finding.Type == "R6" {
|
||||
r6[finding.PublicationID] = finding
|
||||
}
|
||||
}
|
||||
if len(r6) != len(store.removal) {
|
||||
t.Fatalf("R6 count = %d, removal candidates = %d; findings=%#v", len(r6), len(store.removal), store.findings)
|
||||
}
|
||||
if processing, ok := r6["pub-a"]; !ok || processing.WeKnoraParseState != "processing" || processing.NormalizedState != "processing" {
|
||||
t.Fatalf("R6 must keep an upstream-processing row: %#v", processing)
|
||||
}
|
||||
if missing, ok := r6["pub-b"]; !ok || missing.DocumentID != "doc-b" {
|
||||
t.Fatalf("R6 must keep a row the scan could not list: %#v", missing)
|
||||
}
|
||||
if store.completedRun == nil || store.completedRun.Counts["R6"] != len(store.removal) {
|
||||
t.Fatalf("run counts R6 = %#v", store.completedRun)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateRunEnqueuesJobWithinJobIDLimit freezes the queue contract: jobs.id is
|
||||
// VARCHAR(36), and the run id ("rec-" + 32 hex) already fills it. Deriving the job
|
||||
// id from the run id overflowed the column, so every batch was created `failed`
|
||||
// with queue_unavailable before a worker ever saw it.
|
||||
func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeReconciliationStore{
|
||||
run: governance.ReconciliationRun{ID: "rec-unused", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
|
||||
}
|
||||
service, err := New(Config{Store: store, Queue: store, Remote: &fakeReconciliationRemote{},
|
||||
Now: func() time.Time { return now }, Grace: 30 * time.Minute, StallAfter: 2 * time.Hour,
|
||||
StaleAfter: 6 * time.Hour, ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
|
||||
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, err := service.CreateRun(context.Background(), "kb-1", "manual")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateRun error = %v", err)
|
||||
}
|
||||
if len(store.enqueued) != 1 {
|
||||
t.Fatalf("enqueued %d jobs", len(store.enqueued))
|
||||
}
|
||||
request := store.enqueued[0]
|
||||
if len(request.ID) != 36 {
|
||||
t.Fatalf("job id %q length = %d, want exactly 36 (VARCHAR(36))", request.ID, len(request.ID))
|
||||
}
|
||||
if request.Type != "reconciliation.run" || request.IdempotencyKey != "reconciliation-run:"+run.ID {
|
||||
t.Fatalf("enqueue request = %#v", request)
|
||||
}
|
||||
if string(request.Payload) != `{"run_id":"`+run.ID+`"}` {
|
||||
t.Fatalf("payload = %s", request.Payload)
|
||||
}
|
||||
}
|
||||
|
||||
type failingRuntime struct{ err error }
|
||||
|
||||
func (runtime failingRuntime) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||||
return governance.ReconciliationProgress{}, runtime.err
|
||||
}
|
||||
|
||||
// Progress must not re-collapse the provider's classification: the page needs
|
||||
// "no binding", "no permission" and "unreachable" to stay distinct.
|
||||
func TestProgressPreservesClassifiedRuntimeErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want error
|
||||
}{
|
||||
{name: "unavailable", err: ErrRuntimeUnavailable, want: ErrRuntimeUnavailable},
|
||||
{name: "forbidden", err: ErrRuntimeForbidden, want: ErrRuntimeForbidden},
|
||||
{name: "unreachable", err: ErrRuntimeUnreachable, want: ErrRuntimeUnreachable},
|
||||
{name: "not found", err: &weknora.HTTPError{StatusCode: http.StatusNotFound}, want: ErrNotFound},
|
||||
{name: "unclassified", err: errors.New("boom"), want: ErrRuntimeUnavailable},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
service, err := New(Config{
|
||||
Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{},
|
||||
Runtime: failingRuntime{err: testCase.err},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("Progress err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +110,9 @@ def ready(directory, bundle, test_database=None):
|
||||
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
|
||||
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
|
||||
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
|
||||
# 导入对账(T6)只对测试库做,候选必须真的接线;它与旧的取件/上传链路
|
||||
# (TEST_WEKNORA_ENABLED)解耦,租户 Key 走知识库绑定。
|
||||
env['RECONCILIATION_ENABLED'] = 'true'
|
||||
app_env = directory / 'app.env'
|
||||
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
||||
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
||||
|
||||
@@ -366,9 +366,30 @@ def image_inspect(image):
|
||||
return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0]
|
||||
|
||||
|
||||
def container_log_tail(name, lines=5, limit=400):
|
||||
"""Give the failure text a symptom, not just a verdict.
|
||||
|
||||
A non-running container used to surface only as "expected container is not
|
||||
running"; the actual cause (missing zoneinfo, refused DSN, bad bind) lives in
|
||||
the container log and was thrown away with the container.
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(['docker', 'logs', '--tail', str(lines), name], capture_output=True, timeout=15)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return 'no container log'
|
||||
# docker CLI forwards the container's stderr to its own stderr; keep both.
|
||||
text = ' '.join((result.stdout + result.stderr).decode('utf-8', 'replace').split())
|
||||
return text[-limit:] if text else 'no container log'
|
||||
|
||||
|
||||
def inspect(name):
|
||||
obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0]
|
||||
require(obj['State']['Status'] == 'running' and matches(IMAGE, obj.get('Image')), 'expected container is not running')
|
||||
state = obj.get('State') or {}
|
||||
if state.get('Status') != 'running':
|
||||
raise CDError(f'{name}: container is {state.get("Status") or "unknown"} '
|
||||
f'(exit {state.get("ExitCode")}); log: {container_log_tail(name)}')
|
||||
require(matches(IMAGE, obj.get('Image')),
|
||||
f'{name}: running image {obj.get("Image")!r} is not an approved image ID')
|
||||
return obj
|
||||
|
||||
|
||||
|
||||
@@ -410,53 +410,6 @@ export function ModulePage({
|
||||
return (
|
||||
<div className="release-module">
|
||||
<ReleaseTargets />
|
||||
<details className="release-legacy">
|
||||
<summary>文档级发布(旧流程,折叠保留):单篇文档发布成功不等于整库发布成功</summary>
|
||||
<ReleaseManagement
|
||||
reviewPage={reviewPage}
|
||||
reviewLoading={reviewLoading}
|
||||
reviewError={reviewError}
|
||||
reviewingId={reviewingId}
|
||||
batchPage={batchPage}
|
||||
batchDetail={batchDetail}
|
||||
batchLoading={batchLoading}
|
||||
batchError={batchError}
|
||||
mutatingBatchId={mutatingBatchId}
|
||||
onReview={onReview}
|
||||
onBatchReview={onBatchReview}
|
||||
reviewBatchMessage={reviewBatchMessage}
|
||||
onReviewRefresh={onReviewRefresh}
|
||||
onCreateBatch={onCreateBatch}
|
||||
onSealBatch={onSealBatch}
|
||||
onSelectBatch={onSelectBatch}
|
||||
onBatchRefresh={onBatchRefresh}
|
||||
releaseCapabilities={releaseCapabilities}
|
||||
releasePlan={releasePlan}
|
||||
releaseChangeSet={releaseChangeSet}
|
||||
changeSetBusy={changeSetBusy}
|
||||
changeSetError={changeSetError}
|
||||
onGenerateChangeSet={onGenerateChangeSet}
|
||||
onConfirmChangeSet={onConfirmChangeSet}
|
||||
selectedDeleteIDs={selectedDeleteIDs}
|
||||
onToggleDelete={onToggleDelete}
|
||||
executionPage={executionPage}
|
||||
executionDetail={executionDetail}
|
||||
executionChain={executionChain}
|
||||
executionLoading={executionLoading}
|
||||
executionError={executionError}
|
||||
onSelectExecution={onSelectExecution}
|
||||
onExecutionRefresh={onExecutionRefresh}
|
||||
pendingReleaseAction={pendingReleaseAction}
|
||||
releaseActionPhrase={releaseActionPhrase}
|
||||
releaseActionBusy={releaseActionBusy}
|
||||
releaseActionError={releaseActionError}
|
||||
releaseActionMessage={releaseActionMessage}
|
||||
onStartReleaseAction={onStartReleaseAction}
|
||||
onReleaseActionPhrase={onReleaseActionPhrase}
|
||||
onSubmitReleaseAction={onSubmitReleaseAction}
|
||||
onCancelReleaseAction={onCancelReleaseAction}
|
||||
/>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { associateLegacySource, LegacySourceAssociation } from './LegacySourceAssociation'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const reply = (status: number, data: unknown) => new Response(JSON.stringify(data), { status })
|
||||
|
||||
it('only sends exact snapshot and scope; association is not publishing', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
reply(200, { associated: true, published: false, snapshot_id: 'snapshot', source_id: 'a'.repeat(64) })
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
expect(await associateLegacySource('internal', 'snapshot')).toBe('a'.repeat(64))
|
||||
expect(fetchMock.mock.calls).toHaveLength(1)
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/library/source-associations')
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ scope: 'internal', snapshot_id: 'snapshot' })
|
||||
})
|
||||
|
||||
it('rejects wrong-snapshot and incomplete readback, and shows evidence errors', async () => {
|
||||
for (const value of [
|
||||
{ associated: true, published: false, snapshot_id: 'wrong', source_id: 'a'.repeat(64) },
|
||||
{ associated: true, snapshot_id: 'snapshot' },
|
||||
]) {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(200, value)))
|
||||
await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('来源关联回执')
|
||||
}
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(409, { error: 'original capture identity mismatch' })))
|
||||
await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('original capture identity mismatch')
|
||||
})
|
||||
|
||||
it('hides association controls from non-admin and distinguishes it from publication', () => {
|
||||
expect(
|
||||
renderToStaticMarkup(
|
||||
<LegacySourceAssociation scope="internal" snapshots={[]} admin={false} onBound={async () => {}} />
|
||||
)
|
||||
).toBe('')
|
||||
const html = renderToStaticMarkup(
|
||||
<LegacySourceAssociation scope="internal" snapshots={[]} admin onBound={async () => {}} />
|
||||
)
|
||||
expect(html).toContain('只追加治理关联')
|
||||
expect(html).toContain('disabled')
|
||||
expect(html).toContain('核验原证据并关联')
|
||||
})
|
||||
@@ -1,83 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import type { LibrarySnapshot } from './librarySnapshots'
|
||||
|
||||
export async function associateLegacySource(scope: string, snapshotID: string): Promise<string> {
|
||||
const response = await fetch('/api/v1/library/source-associations', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ scope, snapshot_id: snapshotID }),
|
||||
})
|
||||
const value = (await response.json().catch(() => null)) as Record<string, unknown> | null
|
||||
if (!response.ok)
|
||||
throw new Error(typeof value?.error === 'string' ? value.error : `来源关联失败(HTTP ${response.status})`)
|
||||
if (
|
||||
value?.associated !== true ||
|
||||
value.published !== false ||
|
||||
value.snapshot_id !== snapshotID ||
|
||||
typeof value.source_id !== 'string' ||
|
||||
!/^[a-f0-9]{64}$/.test(value.source_id)
|
||||
) {
|
||||
throw new Error('来源关联回执不完整或快照身份不符')
|
||||
}
|
||||
return value.source_id
|
||||
}
|
||||
|
||||
export function LegacySourceAssociation({
|
||||
scope,
|
||||
snapshots,
|
||||
admin,
|
||||
onBound,
|
||||
}: {
|
||||
scope: string
|
||||
snapshots: LibrarySnapshot[]
|
||||
admin: boolean
|
||||
onBound: () => Promise<void>
|
||||
}) {
|
||||
const [snapshotID, setSnapshotID] = useState('')
|
||||
const [pending, setPending] = useState(false)
|
||||
const [notice, setNotice] = useState('')
|
||||
if (!admin) return null
|
||||
const choices = snapshots.filter((item) => item.scope === scope)
|
||||
const bind = async () => {
|
||||
if (pending || !choices.some((item) => item.snapshot_id === snapshotID)) return
|
||||
setPending(true)
|
||||
setNotice('')
|
||||
try {
|
||||
const sourceID = await associateLegacySource(scope, snapshotID)
|
||||
setNotice(`来源证据已核验关联:${sourceID}。没有发布内容;发布授权与写入闸门仍独立检查。`)
|
||||
await onBound()
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : '来源关联失败')
|
||||
} finally {
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<details className="rel-source-identity">
|
||||
<summary>关联旧封存的原始来源证据(管理员)</summary>
|
||||
<p>
|
||||
只追加治理关联,保留原快照与摘要。服务端核对原捕获响应、执行器指纹及清单;备份、来源不符或证据缺失均拒绝,不凭同一范围认领。
|
||||
</p>
|
||||
<label>
|
||||
待核验的历史快照
|
||||
<select
|
||||
aria-label="待核验的历史快照"
|
||||
value={snapshotID}
|
||||
disabled={pending}
|
||||
onChange={(event) => setSnapshotID(event.target.value)}
|
||||
>
|
||||
<option value="">选择准确快照摘要</option>
|
||||
{choices.map((item) => (
|
||||
<option key={item.snapshot_id} value={item.snapshot_id}>
|
||||
{item.snapshot_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" disabled={pending || !snapshotID} onClick={() => void bind()}>
|
||||
{pending ? '核验中…' : '核验原证据并关联'}
|
||||
</button>
|
||||
{notice ? <p role="status">{notice}</p> : null}
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { FindingDetail, ReconciliationFindingsView } from './ReconciliationFindings'
|
||||
import { FindingDetail, ReconciliationFindingsView, ServiceStrip } from './ReconciliationFindings'
|
||||
import type { MonitorOverview } from './monitor'
|
||||
import type { ReconciliationFinding, ReconciliationRun } from './reconciliationApi'
|
||||
|
||||
const run: ReconciliationRun = {
|
||||
@@ -114,3 +115,59 @@ describe('reconciliation findings', () => {
|
||||
expect(html).toContain('在 WeKnora 中打开')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ServiceStrip queue availability', () => {
|
||||
const overview = (queues: MonitorOverview['weknora_queues'], queueError?: string) =>
|
||||
({ weknora_queues: queues, weknora_queue_error: queueError, health: [] }) as unknown as MonitorOverview
|
||||
|
||||
it('states an unavailable queue instead of rendering 0 waiting · 0 active', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_unavailable')} />)
|
||||
expect(html).toContain('未配置知识库绑定或绑定不可用')
|
||||
expect(html).not.toContain('0 等待')
|
||||
})
|
||||
|
||||
it('tells the operator to authorize the missing permission', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_forbidden')} />)
|
||||
expect(html).toContain('当前 Key 缺少平台运行时读权限')
|
||||
expect(html).not.toContain('连不上 WeKnora')
|
||||
expect(html).not.toContain('runtime_read_forbidden')
|
||||
})
|
||||
|
||||
it('reports an unreachable instance instead of a missing key', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_unreachable')} />)
|
||||
expect(html).toContain('连不上 WeKnora')
|
||||
expect(html).not.toContain('缺少平台运行时读权限')
|
||||
})
|
||||
|
||||
it('falls back to a neutral sentence for an unknown reason', () => {
|
||||
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null)} />)
|
||||
expect(html).toContain('队列暂不可用')
|
||||
})
|
||||
|
||||
it('prints queue depth when the queue is available', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ServiceStrip
|
||||
overview={overview({
|
||||
available: true,
|
||||
queues_error: false,
|
||||
workers_error: false,
|
||||
timestamp: 0,
|
||||
queues: [
|
||||
{
|
||||
name: 'default',
|
||||
pool: 'default',
|
||||
pending: 2,
|
||||
active: 1,
|
||||
scheduled: 0,
|
||||
retry: 0,
|
||||
archived: 0,
|
||||
processed: 0,
|
||||
failed: 0,
|
||||
},
|
||||
],
|
||||
})}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('2 等待 · 1 运行')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -62,11 +62,41 @@ interface FindingsProps {
|
||||
onDetail: (finding: ReconciliationFinding) => void
|
||||
}
|
||||
|
||||
// The runtime read has three operator-actionable failure modes, each with its
|
||||
// own next step. Codes are never shown; the permission name is the only token
|
||||
// the admin needs to paste into WeKnora's authorization page.
|
||||
function queueUnavailableText(code?: string): string {
|
||||
switch (code) {
|
||||
case 'runtime_read_forbidden':
|
||||
return '当前 Key 缺少平台运行时读权限,请在 WeKnora 授权 system_runtime_read'
|
||||
case 'runtime_read_unreachable':
|
||||
return '连不上 WeKnora,请检查测试环境地址与网络'
|
||||
case 'runtime_read_unavailable':
|
||||
return '未配置知识库绑定或绑定不可用,请在「系统设置 → 知识库绑定」填写测试环境地址与 Key'
|
||||
default:
|
||||
return '队列暂不可用'
|
||||
}
|
||||
}
|
||||
|
||||
function progressErrorText(code?: string): string {
|
||||
switch (code) {
|
||||
case 'runtime_read_forbidden':
|
||||
return '当前 Key 缺少平台运行时读权限,请在 WeKnora 授权 system_runtime_read。'
|
||||
case 'runtime_read_unreachable':
|
||||
return '连不上 WeKnora,请检查测试环境地址与网络。'
|
||||
case 'runtime_read_unavailable':
|
||||
return '未配置知识库绑定或绑定不可用,请在「系统设置 → 知识库绑定」填写测试环境地址与 Key。'
|
||||
default:
|
||||
return '读取 WeKnora 处理详情失败'
|
||||
}
|
||||
}
|
||||
|
||||
// ServiceStrip is the page-top one-line status required by §8: the service and
|
||||
// dependency area collapses into a row on both tabs. Queue truth comes from
|
||||
// weknora_queues; an unavailable queue is stated, never rendered as a zero.
|
||||
export function ServiceStrip({ overview }: { overview: MonitorOverview | null }) {
|
||||
const queue = overview?.weknora_queues
|
||||
const queueError = overview?.weknora_queue_error
|
||||
const ready = overview?.health.filter((item) => item.readiness === 'ready').length
|
||||
const attention = overview?.health.filter(
|
||||
(item) => item.applicable && item.configured && item.readiness !== 'ready'
|
||||
@@ -75,13 +105,13 @@ export function ServiceStrip({ overview }: { overview: MonitorOverview | null })
|
||||
<section className="monitor-service-strip" aria-label="服务与队列">
|
||||
<span>
|
||||
WeKnora 队列:
|
||||
{queue ? (
|
||||
{queue?.available ? (
|
||||
<b>
|
||||
{queue.queues.reduce((sum, item) => sum + item.pending, 0)} 等待 ·{' '}
|
||||
{queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行
|
||||
</b>
|
||||
) : (
|
||||
<b className="monitor-muted">未配置只读 Key 或队列不可用</b>
|
||||
<b className="monitor-muted">{queueUnavailableText(queueError)}</b>
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
@@ -369,10 +399,12 @@ export function WeKnoraProgress({
|
||||
.catch((err) => {
|
||||
if (controller.signal.aborted) return
|
||||
setProgress(null)
|
||||
if (err instanceof ReconciliationRequestError && err.code === 'runtime_read_unavailable') {
|
||||
setError('未配置 WeKnora 只读 Key,无法读取实时处理详情。')
|
||||
if (err instanceof ReconciliationRequestError && err.code.startsWith('runtime_read_')) {
|
||||
setError(progressErrorText(err.code))
|
||||
} else if (err instanceof Error) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : '读取 WeKnora 处理详情失败')
|
||||
setError(progressErrorText())
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
|
||||
@@ -19,7 +19,7 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
describe('WeKnora progress drawer block', () => {
|
||||
it('degrades to a read-only key message on 503', async () => {
|
||||
it('degrades to a binding message on 503', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
@@ -30,7 +30,40 @@ describe('WeKnora progress drawer block', () => {
|
||||
)
|
||||
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
|
||||
expect(container.textContent).toContain('未配置知识库绑定或绑定不可用')
|
||||
})
|
||||
it('names the missing permission when the key is rejected', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_read_forbidden', code: 'runtime_read_forbidden' }), {
|
||||
status: 502,
|
||||
})
|
||||
)
|
||||
)
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<WeKnoraProgress documentID="doc-1" weknoraURL="https://weknora.test/platform/knowledge-bases/kb-1" />
|
||||
)
|
||||
)
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('当前 Key 缺少平台运行时读权限')
|
||||
expect(container.textContent).not.toContain('runtime_read_forbidden')
|
||||
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
|
||||
})
|
||||
it('says the instance is unreachable instead of blaming the key', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_read_unreachable', code: 'runtime_read_unreachable' }), {
|
||||
status: 502,
|
||||
})
|
||||
)
|
||||
)
|
||||
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('连不上 WeKnora')
|
||||
expect(container.textContent).not.toContain('缺少平台运行时读权限')
|
||||
})
|
||||
it('shows stages and failures when available', async () => {
|
||||
vi.stubGlobal(
|
||||
|
||||
@@ -892,6 +892,36 @@ describe('ReleaseTargetsView(确认稿布局)', () => {
|
||||
expect(known).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/)
|
||||
})
|
||||
|
||||
it('生产生效版本就是当前测试封存时,主按钮是不可点的“已同步”,前进方向换成重新封存', () => {
|
||||
const html = render({
|
||||
sync: { canSign: true, pendingGrant: false, onGrant: vi.fn(), canStart: true, pending: false, onStart: vi.fn() },
|
||||
overview: {
|
||||
...overview,
|
||||
gate: { sync_allowed: true, reasons: [] },
|
||||
production: {
|
||||
state: 'known',
|
||||
version: {
|
||||
id: 'v-same',
|
||||
kind: 'production_effective',
|
||||
snapshot_id: internalSnapshot.snapshot_id,
|
||||
version_label: '',
|
||||
source_job_id: 'libsync-1',
|
||||
evidence: {},
|
||||
created_by: 'admin',
|
||||
created_at: '2026-10-29T09:00:00Z',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
// 闸口放行也不许再把同一份内容同步一遍
|
||||
expect(html).not.toContain('▶ 启动同步')
|
||||
expect(html).toMatch(/<button[^>]*class="rel-primary rel-synced"[^>]*disabled[^>]*>✓ 已同步/)
|
||||
expect(html).toContain('生产已是当前测试封存')
|
||||
expect(html).toMatch(/class="rel-secondary"[^>]*>重新封存测试版本/)
|
||||
// 已同步时签发授权没有意义,不出现签发入口
|
||||
expect(html).not.toContain('签发同步授权(30 分钟)')
|
||||
})
|
||||
|
||||
it('闸口全满足时“启动同步”真的可点,并给出执行说明', () => {
|
||||
const html = render({
|
||||
sync: { canSign: false, pendingGrant: false, onGrant: vi.fn(), canStart: true, pending: false, onStart: vi.fn() },
|
||||
|
||||
+76
-69
@@ -1,4 +1,3 @@
|
||||
import { LegacySourceAssociation } from './LegacySourceAssociation'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
createLibraryRestoreAuthorization,
|
||||
@@ -981,10 +980,6 @@ interface ReadyProps {
|
||||
prebackup: LibraryOverview['prebackup']
|
||||
gate: LibraryOverview['gate']
|
||||
authorization: LibraryOverview['authorization']
|
||||
canCapture: boolean
|
||||
canWrite: boolean
|
||||
pendingCapture: boolean
|
||||
onCapture: () => void
|
||||
onOpen: () => void
|
||||
sync: ReleaseSyncActions
|
||||
baseline: ReleaseBaselineActions
|
||||
@@ -1006,16 +1001,12 @@ function ReadyBody({
|
||||
sync,
|
||||
baseline,
|
||||
verification,
|
||||
canCapture,
|
||||
canWrite,
|
||||
pendingCapture,
|
||||
onCapture,
|
||||
onOpen,
|
||||
}: ReadyProps) {
|
||||
const snapshot = view.snapshot
|
||||
return (
|
||||
<>
|
||||
<div className="rel-grid">
|
||||
<div>
|
||||
<ProtectionCard
|
||||
production={production}
|
||||
productionNote={productionNote}
|
||||
@@ -1043,17 +1034,6 @@ function ReadyBody({
|
||||
</header>
|
||||
<StageBar view={view} />
|
||||
</div>
|
||||
<div className="rel-panel rel-seal">
|
||||
<div>
|
||||
<h2>测试库封存</h2>
|
||||
<p>
|
||||
{snapshot
|
||||
? `最近一次封存 ${stamp(snapshot.created_at)},快照 ${snapshot.snapshot_id.slice(0, 12)}。封存只读测试库,不影响生产。`
|
||||
: '还没有测试库封存。封存会短暂停住测试写入者,导出完整版本后恢复。'}
|
||||
</p>
|
||||
</div>
|
||||
<span className="rel-hint">{canCapture ? '封存入口在页面顶部“下一步”。' : captureHint(view, canWrite)}</span>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1884,7 +1864,22 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
|
||||
const sealed = Boolean(view.snapshot)
|
||||
const authorizationActive = authorization.state === 'active'
|
||||
// 主按钮永远是"同步"或"查看当前任务";准备动作(封存/基线/恢复验证/授权)
|
||||
// 生产生效版本就是这份测试封存时,再同步只会把同一份内容重写一遍(还要停机维护),
|
||||
// 所以主按钮改成不可点的"已同步",前进方向换成封存新版本。闸口放行与否不影响这个判断。
|
||||
const inSync =
|
||||
!runningJob &&
|
||||
productionClass === 'known' &&
|
||||
Boolean(target?.snapshot_id) &&
|
||||
production?.version?.snapshot_id === target?.snapshot_id
|
||||
const captureAction = {
|
||||
label: pendingCapture ? '封存中…' : sealed ? '重新封存测试版本' : '封存测试版本',
|
||||
hint: sealed
|
||||
? '生产已是当前测试封存,无需同步;测试库有新内容时先封存新版本。'
|
||||
: '还没有测试库封存。封存只读导出测试库(短暂停住测试写入者),不影响生产。',
|
||||
disabled: pendingCapture,
|
||||
run: onCapture,
|
||||
}
|
||||
// 主按钮永远是"同步"、"已同步"或"查看当前任务";准备动作(封存/基线/授权)
|
||||
// 作为次要按钮按状态出现,页面因此只有一个前进方向。
|
||||
const primaryAction = runningJob
|
||||
? {
|
||||
@@ -1893,38 +1888,44 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
disabled: false,
|
||||
run: () => document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }),
|
||||
}
|
||||
: {
|
||||
label: sync.pending ? '投递中…' : '▶ 启动同步',
|
||||
hint: sync.canStart
|
||||
? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。'
|
||||
: `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`,
|
||||
disabled: !sync.canStart || sync.pending,
|
||||
run: sync.onStart,
|
||||
}
|
||||
: inSync
|
||||
? {
|
||||
label: '✓ 已同步',
|
||||
hint: canCapture ? captureAction.hint : `生产已是当前测试封存,无需同步。${captureHint(view, canWrite)}`,
|
||||
disabled: true,
|
||||
run: () => {},
|
||||
}
|
||||
: {
|
||||
label: sync.pending ? '投递中…' : '▶ 启动同步',
|
||||
hint: sync.canStart
|
||||
? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。'
|
||||
: `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`,
|
||||
disabled: !sync.canStart || sync.pending,
|
||||
run: sync.onStart,
|
||||
}
|
||||
const prepAction = !sealed
|
||||
? canCapture
|
||||
? {
|
||||
label: pendingCapture ? '封存中…' : '封存测试版本',
|
||||
hint: '只读导出测试库,生成一份可发布的整库版本。',
|
||||
disabled: pendingCapture,
|
||||
run: onCapture,
|
||||
}
|
||||
? captureAction
|
||||
: { label: '尚无封存', hint: captureHint(view, canWrite), disabled: true, run: () => {} }
|
||||
: productionClass === 'nonempty' && baseline.canStart
|
||||
? {
|
||||
label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)',
|
||||
hint: '生产目标非空但还没有权威版本,先登记一份基线。',
|
||||
disabled: baseline.pending,
|
||||
run: baseline.onStart,
|
||||
}
|
||||
: !authorizationActive && sync.canSign
|
||||
? {
|
||||
label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)',
|
||||
hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。',
|
||||
disabled: sync.pendingGrant,
|
||||
run: sync.onGrant,
|
||||
}
|
||||
: inSync
|
||||
? canCapture
|
||||
? captureAction
|
||||
: null
|
||||
: productionClass === 'nonempty' && baseline.canStart
|
||||
? {
|
||||
label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)',
|
||||
hint: '生产目标非空但还没有权威版本,先登记一份基线。',
|
||||
disabled: baseline.pending,
|
||||
run: baseline.onStart,
|
||||
}
|
||||
: !authorizationActive && sync.canSign
|
||||
? {
|
||||
label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)',
|
||||
hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。',
|
||||
disabled: sync.pendingGrant,
|
||||
run: sync.onGrant,
|
||||
}
|
||||
: null
|
||||
|
||||
const productionText =
|
||||
productionClass === 'known' && production?.version
|
||||
@@ -1988,8 +1989,13 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
<div className="rel-panel rel-status">
|
||||
<p className="rel-scope-state">
|
||||
{scopeName(scope)} ·{' '}
|
||||
{active ? `${jobKindText(view.job?.kind)}进行中` : sealed ? '已封存,同步按条件放行' : '尚无测试封存'}
|
||||
{sealed ? '(需要新版本时点上方“封存测试版本”)' : ''}
|
||||
{active
|
||||
? `${jobKindText(view.job?.kind)}进行中`
|
||||
: inSync
|
||||
? '生产已是当前测试封存'
|
||||
: sealed
|
||||
? '已封存,同步按条件放行'
|
||||
: '尚无测试封存'}
|
||||
</p>
|
||||
<dl className="rel-status-grid">
|
||||
<div>
|
||||
@@ -1998,6 +2004,15 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
{sealed ? `快照 ${view.snapshot!.snapshot_id.slice(0, 12)}` : '尚无'}
|
||||
</dd>
|
||||
<small>{sealed ? stamp(view.snapshot!.created_at) : '先封存测试版本'}</small>
|
||||
{/* 封存入口跟着"测试封存"这一格走:主操作区已经放了封存按钮时不再重复;
|
||||
不能封存时把接口给的真实原因写在这里,而不是只藏在按钮 title 里。 */}
|
||||
{runningJob || prepAction === captureAction ? null : canCapture ? (
|
||||
<button type="button" className="rel-link rel-cell-action" onClick={onCapture} disabled={pendingCapture}>
|
||||
{captureAction.label}
|
||||
</button>
|
||||
) : (
|
||||
<small className="rel-unknown">{captureHint(view, canWrite)}</small>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<dt>生产当前</dt>
|
||||
@@ -2010,9 +2025,11 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
<small>
|
||||
{authorizationActive
|
||||
? `有效至 ${stamp(authorization.expires_at ?? '')}`
|
||||
: sync.canSign
|
||||
? '可在下方签发'
|
||||
: '需管理员签发'}
|
||||
: inSync
|
||||
? '已同步,无需签发'
|
||||
: sync.canSign
|
||||
? '可在下方签发'
|
||||
: '需管理员签发'}
|
||||
</small>
|
||||
</div>
|
||||
<div>
|
||||
@@ -2045,7 +2062,7 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="rel-primary"
|
||||
className={inSync ? 'rel-primary rel-synced' : 'rel-primary'}
|
||||
onClick={primaryAction.run}
|
||||
disabled={primaryAction.disabled}
|
||||
title={primaryAction.hint}
|
||||
@@ -2056,12 +2073,13 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
版本与快照
|
||||
</button>
|
||||
</div>
|
||||
{gate.reasons.length > 0 ? (
|
||||
{/* 已同步时闸口缺项(多半只是授权过期)跟下一步无关:不催、不自动展开,缺项仍在折叠区里可查。 */}
|
||||
{gate.reasons.length > 0 && !inSync ? (
|
||||
<p className="rel-hint">还差 {gate.reasons.length} 项条件,展开“发布前检查”查看原因。</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<details className="rel-check" id="rel-check" open={gate.reasons.length > 0}>
|
||||
<details className="rel-check" id="rel-check" open={gate.reasons.length > 0 && !inSync}>
|
||||
<summary>
|
||||
发布前检查
|
||||
{gate.reasons.length > 0 ? `(${gate.reasons.length} 项未满足)` : '(已满足)'}
|
||||
@@ -2127,10 +2145,6 @@ export function ReleaseTargetsView(props: ViewProps) {
|
||||
sync={sync}
|
||||
baseline={baseline}
|
||||
verification={verification}
|
||||
canCapture={canCapture}
|
||||
canWrite={canWrite}
|
||||
pendingCapture={pendingCapture}
|
||||
onCapture={onCapture}
|
||||
onOpen={() => onDrawer(true)}
|
||||
/>
|
||||
)}
|
||||
@@ -2560,13 +2574,6 @@ export function ReleaseTargets() {
|
||||
onCapture={() => void startCapture()}
|
||||
onRecover={(windowJobID) => void recover(windowJobID)}
|
||||
/>
|
||||
<LegacySourceAssociation
|
||||
key={scope}
|
||||
scope={scope}
|
||||
snapshots={page?.snapshots ?? []}
|
||||
admin={role === 'admin'}
|
||||
onBound={() => load()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('platform task drawer', () => {
|
||||
)
|
||||
await act(async () => root.render(<TaskDetail item={item} onClose={vi.fn()} />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
|
||||
expect(container.textContent).toContain('未配置知识库绑定或绑定不可用')
|
||||
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -85,6 +85,8 @@ export interface MonitorOverview {
|
||||
pipeline?: IngestionPipeline
|
||||
health: ServiceHealth[]
|
||||
weknora_queues?: WeKnoraQueues | null
|
||||
/** 队列不可用时后端给出的原因码:runtime_read_unavailable / forbidden / unreachable */
|
||||
weknora_queue_error?: string
|
||||
}
|
||||
export interface MonitorFile {
|
||||
name: string
|
||||
|
||||
+255
-162
@@ -1,11 +1,13 @@
|
||||
/* 发布管理:按已确认稿的布局与色系(浅底、青绿主色、白色圆角面板)。 */
|
||||
/* 发布管理:沿用全站工作台视觉(styles.css 的钴蓝 + 中性灰 token)。
|
||||
以前这一页自带一套青绿色并用 !important 压过全局按钮,看起来像另一个系统;
|
||||
现在只在这里起别名,颜色一律回到全局 token,语义色(绿=完成、红=失败)也取全局。 */
|
||||
.release-targets {
|
||||
--rel-ink: #26394a;
|
||||
--rel-muted: #7b8d9a;
|
||||
--rel-line: #dce6ed;
|
||||
--rel-teal: #269e88;
|
||||
--rel-teal-dark: #228b75;
|
||||
--rel-teal-soft: #eaf8f3;
|
||||
--rel-ink: var(--ink-strong);
|
||||
--rel-muted: var(--ink-mute);
|
||||
--rel-line: var(--border-base);
|
||||
--rel-accent: var(--c-primary);
|
||||
--rel-accent-hover: var(--c-primary-hover);
|
||||
--rel-accent-soft: var(--bg-active);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
@@ -15,11 +17,13 @@
|
||||
}
|
||||
.release-targets h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.release-targets h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.rel-head {
|
||||
display: flex;
|
||||
@@ -42,27 +46,44 @@
|
||||
.release-targets button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
background: #fff;
|
||||
border: 1px solid #d6e2e8;
|
||||
border-radius: 7px;
|
||||
padding: 7px 14px;
|
||||
color: #41596b;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--r-md);
|
||||
padding: 6px 14px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.release-targets button:hover:not(:disabled) {
|
||||
background: #edf8f5;
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.release-targets button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.release-targets button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--c-focus-ring);
|
||||
}
|
||||
.rel-primary {
|
||||
background: var(--rel-teal) !important;
|
||||
border-color: var(--rel-teal) !important;
|
||||
background: var(--rel-accent) !important;
|
||||
border-color: var(--rel-accent) !important;
|
||||
color: #fff !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
.rel-primary:hover:not(:disabled) {
|
||||
background: var(--rel-accent-hover) !important;
|
||||
border-color: var(--rel-accent-hover) !important;
|
||||
}
|
||||
/* "已同步"是结论不是失效按钮:不走半透明禁用态,用完成色说清楚已经到位。 */
|
||||
.rel-primary.rel-synced,
|
||||
.rel-primary.rel-synced:disabled {
|
||||
opacity: 1;
|
||||
cursor: default;
|
||||
background: var(--c-done-bg) !important;
|
||||
border-color: var(--c-done-border) !important;
|
||||
color: var(--c-done) !important;
|
||||
}
|
||||
.rel-secondary {
|
||||
background: #fff;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.rel-tabs {
|
||||
display: flex;
|
||||
@@ -70,54 +91,63 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.rel-tab {
|
||||
width: 310px;
|
||||
width: 300px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 13px 18px !important;
|
||||
padding: 12px 16px !important;
|
||||
text-align: left;
|
||||
border-radius: 9px !important;
|
||||
border-radius: var(--r-lg) !important;
|
||||
border: 1px solid var(--rel-line) !important;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.rel-tab strong {
|
||||
font-size: 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.rel-tab.selected {
|
||||
background: var(--rel-teal-soft) !important;
|
||||
border: 2px solid var(--rel-teal) !important;
|
||||
background: var(--rel-accent-soft) !important;
|
||||
border-color: var(--rel-accent) !important;
|
||||
box-shadow: inset 0 0 0 1px var(--rel-accent);
|
||||
}
|
||||
.rel-tab.selected strong {
|
||||
color: var(--rel-accent);
|
||||
}
|
||||
.rel-pill {
|
||||
border-radius: 5px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
padding: 2px 9px;
|
||||
padding: 1px 9px;
|
||||
white-space: nowrap;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.rel-pill.green {
|
||||
color: #228368;
|
||||
background: #e6f5ef;
|
||||
border-color: #bfe6d8;
|
||||
color: var(--c-done);
|
||||
background: var(--c-done-bg);
|
||||
border-color: var(--c-done-border);
|
||||
}
|
||||
.rel-pill.blue {
|
||||
color: #387eb8;
|
||||
background: #eaf3fc;
|
||||
border-color: #c6ddf1;
|
||||
color: var(--c-run);
|
||||
background: var(--c-run-bg);
|
||||
border-color: var(--c-run-border);
|
||||
}
|
||||
.rel-pill.gray {
|
||||
color: #7c8d99;
|
||||
background: #eff3f6;
|
||||
border-color: #dde5ea;
|
||||
color: var(--c-dead);
|
||||
background: var(--c-dead-bg);
|
||||
border-color: var(--border-base);
|
||||
}
|
||||
.rel-pill.red {
|
||||
color: #b4381f;
|
||||
background: #fdecea;
|
||||
border-color: #f3c6bc;
|
||||
color: var(--c-fail);
|
||||
background: var(--c-fail-bg);
|
||||
border-color: var(--c-fail-border);
|
||||
}
|
||||
.rel-panel {
|
||||
background: #fff;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: 12px;
|
||||
padding: 20px 22px;
|
||||
border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-card);
|
||||
padding: 18px 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
.rel-between {
|
||||
@@ -129,7 +159,7 @@
|
||||
}
|
||||
.rel-panel-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
@@ -140,18 +170,18 @@
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
.rel-jobhead h2 {
|
||||
font-size: 19px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.rel-versionline {
|
||||
margin: 12px 0 0;
|
||||
color: #496579;
|
||||
font-size: 14px;
|
||||
color: var(--ink-base);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rel-versionline b {
|
||||
color: var(--rel-teal-dark);
|
||||
color: var(--rel-accent);
|
||||
}
|
||||
.rel-unknown {
|
||||
color: #9aa9b4 !important;
|
||||
color: var(--ink-faint) !important;
|
||||
font-weight: 500;
|
||||
}
|
||||
.rel-metrics {
|
||||
@@ -161,8 +191,8 @@
|
||||
margin: 16px 0 0;
|
||||
}
|
||||
.rel-metrics div {
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 9px;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.rel-metrics dt {
|
||||
@@ -173,21 +203,22 @@
|
||||
margin: 4px 0 0;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-checklist {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
gap: 22px;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 14px 0 0;
|
||||
padding: 11px 14px;
|
||||
border-radius: 9px;
|
||||
background: #f2faf6;
|
||||
padding: 12px 14px;
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
font-size: 13px;
|
||||
color: #228368;
|
||||
color: var(--c-done);
|
||||
}
|
||||
.rel-checklist .unknown {
|
||||
color: #8a9aa6;
|
||||
color: var(--ink-faint);
|
||||
}
|
||||
.rel-footnote {
|
||||
margin: 12px 0 0;
|
||||
@@ -216,8 +247,8 @@
|
||||
.rel-drawer-table th,
|
||||
.rel-parts th {
|
||||
text-align: left;
|
||||
background: #f8fafb;
|
||||
color: #8a9aa6;
|
||||
background: var(--bg-soft);
|
||||
color: var(--rel-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: 9px 12px;
|
||||
@@ -227,7 +258,7 @@
|
||||
.rel-drawer-table td,
|
||||
.rel-parts td {
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid #eef2f5;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
vertical-align: top;
|
||||
}
|
||||
.rel-table-empty {
|
||||
@@ -238,8 +269,8 @@
|
||||
}
|
||||
.rel-protection dl {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 8px 14px;
|
||||
grid-template-columns: 11.5em 1fr;
|
||||
gap: 8px 16px;
|
||||
margin: 0 0 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -249,6 +280,8 @@
|
||||
.rel-protection dd {
|
||||
margin: 0;
|
||||
color: var(--rel-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
word-break: break-all;
|
||||
}
|
||||
.rel-hint {
|
||||
margin: 0 0 10px;
|
||||
@@ -259,39 +292,39 @@
|
||||
.rel-warn {
|
||||
margin: 12px 0 0;
|
||||
font-size: 12px;
|
||||
color: #986b24;
|
||||
background: #fff8e8;
|
||||
border: 1px solid #ead7b0;
|
||||
border-radius: 7px;
|
||||
color: var(--c-warn);
|
||||
background: var(--c-warn-bg);
|
||||
border: 1px solid var(--c-warn-border);
|
||||
border-radius: var(--r-md);
|
||||
padding: 8px 10px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.rel-notice {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: #986b24;
|
||||
background: #fff8e8;
|
||||
border: 1px solid #ead7b0;
|
||||
border-radius: 8px;
|
||||
color: var(--c-warn);
|
||||
background: var(--c-warn-bg);
|
||||
border: 1px solid var(--c-warn-border);
|
||||
border-radius: var(--r-md);
|
||||
padding: 9px 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.rel-blocked {
|
||||
border: 1px solid #f3c2b8;
|
||||
background: #fff6f3;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--c-fail-border);
|
||||
background: var(--c-fail-bg);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.rel-blocked strong {
|
||||
display: block;
|
||||
color: #a03a1e;
|
||||
color: var(--c-fail);
|
||||
font-size: 13px;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
.rel-blocked p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: #7c2d12;
|
||||
color: var(--c-fail);
|
||||
}
|
||||
|
||||
/* 阶段条 */
|
||||
@@ -300,7 +333,7 @@
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
list-style: none;
|
||||
margin: 16px 0 6px;
|
||||
margin: 4px 0 8px;
|
||||
padding: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
@@ -310,11 +343,11 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 11px 12px;
|
||||
border-radius: 8px;
|
||||
background: #f5f8fa;
|
||||
border: 1px solid #e1e8ed;
|
||||
color: #8a9aa6;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
border: 1px solid var(--border-soft);
|
||||
color: var(--ink-faint);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rel-step strong {
|
||||
@@ -325,13 +358,14 @@
|
||||
font-size: 11px;
|
||||
}
|
||||
.rel-step.done {
|
||||
color: #25886b;
|
||||
background: #f0faf5;
|
||||
color: var(--c-done);
|
||||
background: var(--c-done-bg);
|
||||
border-color: var(--c-done-border);
|
||||
}
|
||||
.rel-step.live {
|
||||
color: #167f70;
|
||||
background: #e9f8f4;
|
||||
border-color: #4eb49f;
|
||||
color: var(--c-run);
|
||||
background: var(--c-run-bg);
|
||||
border-color: var(--c-run-border);
|
||||
font-weight: 700;
|
||||
}
|
||||
.rel-step-mark {
|
||||
@@ -350,22 +384,6 @@
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 仅剩的次级操作:封存测试版本 */
|
||||
.rel-seal {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
background: #fbfdfe;
|
||||
}
|
||||
.rel-seal p {
|
||||
margin: 6px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--rel-muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 同步中 */
|
||||
.rel-jobmeta {
|
||||
margin: 8px 0 0;
|
||||
@@ -374,7 +392,7 @@
|
||||
}
|
||||
.rel-progress-foot {
|
||||
margin-top: 12px;
|
||||
border-top: 1px solid #eef2f5;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
padding-top: 10px;
|
||||
font-size: 12px;
|
||||
color: var(--rel-muted);
|
||||
@@ -383,14 +401,14 @@
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
padding: 2px 4px !important;
|
||||
color: #2b7fa6 !important;
|
||||
color: var(--rel-accent) !important;
|
||||
font-size: 12px;
|
||||
}
|
||||
.rel-datacard {
|
||||
border: 1px solid #dce6ed;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 14px 16px;
|
||||
background: #fff;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.rel-datacard header {
|
||||
display: flex;
|
||||
@@ -405,19 +423,20 @@
|
||||
}
|
||||
.rel-datacount strong {
|
||||
font-size: 24px;
|
||||
color: #9aa9b4;
|
||||
color: var(--ink-faint);
|
||||
margin-right: 4px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-progress {
|
||||
height: 6px;
|
||||
border-radius: 8px;
|
||||
background: #edf1f4;
|
||||
background: var(--bg-softer);
|
||||
overflow: hidden;
|
||||
}
|
||||
.rel-progress span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--rel-teal);
|
||||
background: var(--rel-accent);
|
||||
}
|
||||
.rel-datadetail {
|
||||
margin: 10px 0 0;
|
||||
@@ -434,27 +453,27 @@
|
||||
padding: 4px 11px;
|
||||
}
|
||||
.rel-filters .chosen {
|
||||
color: #168b73;
|
||||
background: #ebf8f3;
|
||||
border-color: #a6d7c8;
|
||||
color: var(--rel-accent);
|
||||
background: var(--rel-accent-soft);
|
||||
border-color: var(--c-run-border);
|
||||
}
|
||||
.rel-log {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
background: #f9fbfc;
|
||||
border-top: 1px solid #eef2f5;
|
||||
background: var(--bg-soft);
|
||||
border-top: 1px solid var(--border-soft);
|
||||
padding: 10px 12px;
|
||||
font-size: 12px;
|
||||
color: #7b8e9c;
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
|
||||
/* 版本与快照抽屉 */
|
||||
.rel-drawer-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(20, 52, 74, 0.4);
|
||||
background: rgb(0 0 0 / 32%);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
z-index: 40;
|
||||
@@ -463,9 +482,9 @@
|
||||
width: min(1024px, 92vw);
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
border-left: 1px solid #dce6ed;
|
||||
box-shadow: -12px 0 32px rgba(19, 44, 61, 0.18);
|
||||
background: var(--bg-panel);
|
||||
border-left: 1px solid var(--rel-line);
|
||||
box-shadow: var(--shadow-float);
|
||||
padding: 22px 26px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -493,13 +512,13 @@
|
||||
margin-top: 2px;
|
||||
}
|
||||
.rel-drawer-table tr.selected td {
|
||||
background: #f4fbf8;
|
||||
background: var(--rel-accent-soft);
|
||||
}
|
||||
.rel-snapshot {
|
||||
border: 1px solid #cfe6dd;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 16px 18px;
|
||||
background: #fbfefd;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.rel-snapshot header {
|
||||
display: flex;
|
||||
@@ -515,9 +534,9 @@
|
||||
margin: 12px 0;
|
||||
}
|
||||
.rel-snapshot-grid div {
|
||||
border: 1px solid #e2eef7;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-panel);
|
||||
padding: 9px 11px;
|
||||
}
|
||||
.rel-snapshot-grid dt {
|
||||
@@ -534,12 +553,12 @@
|
||||
.rel-parts summary {
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: #2b7fa6;
|
||||
color: var(--rel-accent);
|
||||
}
|
||||
.rel-parts table {
|
||||
margin-top: 8px;
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
overflow: hidden;
|
||||
}
|
||||
.rel-drawer-actions {
|
||||
@@ -548,12 +567,12 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.rel-danger {
|
||||
border-color: #e7b4a8 !important;
|
||||
color: #b4381f !important;
|
||||
border-color: var(--c-fail-border) !important;
|
||||
color: var(--c-fail) !important;
|
||||
}
|
||||
.rel-drawer-foot {
|
||||
margin-top: auto;
|
||||
border-top: 1px solid #eef2f5;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
padding-top: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -602,7 +621,7 @@
|
||||
margin: 2px 0 0;
|
||||
font-style: normal;
|
||||
font-size: 11px;
|
||||
color: var(--rel-muted, #7b8d9a);
|
||||
color: var(--ink-faint);
|
||||
}
|
||||
|
||||
.rel-scope-note {
|
||||
@@ -617,13 +636,13 @@
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.rel-drawer-kinds div {
|
||||
border: 1px solid var(--rel-line, #dce6ed);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-md);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
.rel-drawer-kinds dt {
|
||||
font-size: 11px;
|
||||
color: var(--rel-muted, #7b8d9a);
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
.rel-drawer-kinds dd {
|
||||
margin: 3px 0 0;
|
||||
@@ -645,12 +664,12 @@
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
border-bottom: 1px dashed var(--rel-line, #dce6ed);
|
||||
border-bottom: 1px dashed var(--rel-line);
|
||||
padding: 4px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.rel-maintenance-rows span {
|
||||
color: var(--rel-muted, #7b8d9a);
|
||||
color: var(--rel-muted);
|
||||
}
|
||||
.rel-maintenance-rows b {
|
||||
font-variant-numeric: tabular-nums;
|
||||
@@ -687,9 +706,9 @@
|
||||
padding: 4px 10px;
|
||||
}
|
||||
.rel-history-filters button.active {
|
||||
color: #168b73;
|
||||
background: #ebf8f3;
|
||||
border-color: #a6d7c8;
|
||||
color: var(--rel-accent);
|
||||
background: var(--rel-accent-soft);
|
||||
border-color: var(--c-run-border);
|
||||
}
|
||||
.rel-history-pager {
|
||||
display: flex;
|
||||
@@ -706,33 +725,44 @@
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-size: 11px;
|
||||
background: #f7fafc;
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 7px;
|
||||
background: var(--bg-soft);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
/* 发布管理精简版:一个状态卡 + 一个主按钮,其余收进折叠区。 */
|
||||
.rel-status {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
gap: 16px;
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.rel-scope-state {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
/* 四格状态是一条从测试到生产的链:用竖分隔线排成一行,不再各自加框。 */
|
||||
.rel-status-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 14px;
|
||||
gap: 14px 0;
|
||||
margin: 0;
|
||||
}
|
||||
.rel-status-grid div {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 10px 12px;
|
||||
background: var(--card);
|
||||
padding: 2px 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
.rel-status-grid > div:first-child {
|
||||
padding-left: 0;
|
||||
}
|
||||
.rel-status-grid > div + div {
|
||||
border-left: 1px solid var(--border-soft);
|
||||
}
|
||||
.rel-status-grid dt {
|
||||
font-size: 12px;
|
||||
color: var(--muted-foreground);
|
||||
color: var(--ink-mute);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.rel-status-grid dd {
|
||||
@@ -740,23 +770,30 @@
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
word-break: break-all;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-status-grid small {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
color: var(--muted-foreground);
|
||||
color: var(--ink-mute);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rel-status-grid .rel-cell-action {
|
||||
margin: 4px 0 0 -4px;
|
||||
}
|
||||
.rel-status-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
.rel-next {
|
||||
flex: 1 1 320px;
|
||||
margin: 0;
|
||||
color: var(--muted-foreground);
|
||||
color: var(--ink-mute);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rel-next span {
|
||||
@@ -764,27 +801,83 @@
|
||||
margin-right: 8px;
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: var(--foreground);
|
||||
background: var(--bg-active);
|
||||
color: var(--rel-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 折叠区统一成一种样式:卡片 + 自绘箭头,取代浏览器默认的小三角。 */
|
||||
.rel-check,
|
||||
.rel-advanced {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 4px 16px 12px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--rel-line);
|
||||
border-radius: var(--r-lg);
|
||||
padding: 0 18px;
|
||||
background: var(--bg-panel);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.rel-check summary,
|
||||
.rel-advanced summary {
|
||||
.rel-check > summary,
|
||||
.rel-advanced > summary {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
padding: 10px 0;
|
||||
padding: 13px 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.rel-check > summary::-webkit-details-marker,
|
||||
.rel-advanced > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.rel-check > summary::before,
|
||||
.rel-advanced > summary::before {
|
||||
content: '';
|
||||
flex: none;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-right: 1.5px solid var(--ink-mute);
|
||||
border-bottom: 1.5px solid var(--ink-mute);
|
||||
transform: rotate(-45deg);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
.rel-check[open] > summary::before,
|
||||
.rel-advanced[open] > summary::before {
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.rel-check[open],
|
||||
.rel-advanced[open] {
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
.rel-check .rel-gate,
|
||||
.rel-check .rel-checklist {
|
||||
margin: 6px 0 10px;
|
||||
}
|
||||
/* 恢复验证是嵌在检查区里的子块:给它统一行距,按钮不再贴着上面的报告折叠。 */
|
||||
.rel-verification {
|
||||
margin-top: 14px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
.rel-verification > * + * {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.rel-verification > p.rel-hint {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.rel-advanced > * + * {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 放在文件末尾:要压过上面同优先级的桌面规则。 */
|
||||
@media (max-width: 760px) {
|
||||
.rel-status-grid div,
|
||||
.rel-status-grid > div:first-child {
|
||||
padding: 0;
|
||||
}
|
||||
.rel-status-grid > div + div {
|
||||
border-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user