Compare commits
110 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e33f21206 | |||
| 83bba09cde | |||
| 868924d074 | |||
| 03e622e9c7 | |||
| 9eef078ed0 | |||
| 2ca98a6a35 | |||
| 746b982c43 | |||
| 5ff6768027 | |||
| 2a639392e4 | |||
| 9cfe2114b1 | |||
| 1e7e986b70 | |||
| 8faabdcf9e | |||
| 922ff66533 | |||
| 0246db357f | |||
| 1beaa31771 | |||
| 8c76c54d8e | |||
| 084ee1b176 | |||
| 71971e8164 | |||
| 47428a8b58 | |||
| 91988a0d3b | |||
| 07a0ee2644 | |||
| 0b5de6ef7e | |||
| e892bfdd48 | |||
| d7d636792d | |||
| 89c484cdc4 | |||
| 5e3362e2b0 | |||
| 768ad53fe2 | |||
| 7d91343e5f | |||
| edd07a65d6 | |||
| 7c120b3adc | |||
| ea159ca2fb | |||
| cb026e8dd1 | |||
| 4b615abe53 | |||
| 341c3154ac | |||
| 63984dbfbe | |||
| 033f702d41 | |||
| 9eacf6473e | |||
| 6444814123 | |||
| 6ae5150fdf | |||
| 1f5bf72aec | |||
| ce2a155ebc | |||
| df69b278ce | |||
| 399b5756ea | |||
| 3da82d48d9 | |||
| afc38c921f | |||
| 0dd4ad2737 | |||
| d2f9060b33 | |||
| 3825859da6 | |||
| e0fa31c9d6 | |||
| b2cea6ed84 | |||
| 6c10f71c28 | |||
| cf65d3f363 | |||
| 8e6094e9e5 | |||
| 33afdb9f11 | |||
| 8a574903a1 | |||
| 0fb78cfe26 | |||
| cbc6b981c6 | |||
| ecf518e3bb | |||
| 0b753e550e | |||
| 2066bedbbe | |||
| 5f1a8f565c | |||
| 4fce49478f | |||
| 4d2cb13b0e | |||
| 0aa9f273e6 | |||
| fba2713b4e | |||
| 10568943af | |||
| 3f2626f621 | |||
| e8bfdbbc06 | |||
| ef3c1fbf84 | |||
| 2da96da592 | |||
| 10182b027e | |||
| 060872a144 | |||
| 0f7b8987b4 | |||
| 5e850e96f5 | |||
| 719876d039 | |||
| 9d445f4953 | |||
| 2eff9447e1 | |||
| 146ac832a2 | |||
| 77bbc3ac6b | |||
| eaa388f76b | |||
| cf11343cf4 | |||
| 7511c59987 | |||
| b81fcd07e3 | |||
| 1a0f99e346 | |||
| 7675e2cd88 | |||
| 5bf4aae30e | |||
| 1c80b07f2c | |||
| dfbf3336b2 | |||
| 600cca02e5 | |||
| e735ae603d | |||
| 2a2e98bd8e | |||
| 92684c6f60 | |||
| 537a6df46d | |||
| 0d9091e464 | |||
| e0fc2c32b8 | |||
| 6042955498 | |||
| a55319d972 | |||
| 017765763a | |||
| bd452e85b3 | |||
| 71f23c6763 | |||
| b4add6c9b0 | |||
| f9457fab52 | |||
| 5e1482e349 | |||
| 4421dd38ce | |||
| 22fb33aa75 | |||
| 0d180aa401 | |||
| 0a87dc8e03 | |||
| 96472c1dde | |||
| bad9034cf7 | |||
| f330a75641 |
@@ -24,6 +24,11 @@ DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT=20m
|
||||
# Independent governance AI: endpoint/model/write-only API key are stored via the admin page.
|
||||
# Mount the same 32-byte regular 0600 master-key file into API and ordinary worker.
|
||||
QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
||||
QA_AI_DNS_OVER_TLS=
|
||||
# Only opt in behind an already trusted TLS-terminating same-origin reverse proxy.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
name: deploy-production
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
action:
|
||||
description: deploy 或 writeback
|
||||
required: true
|
||||
default: deploy
|
||||
sha:
|
||||
description: 验收过的完整提交 SHA
|
||||
required: true
|
||||
bundle:
|
||||
description: release.json 的完整 SHA256
|
||||
required: true
|
||||
task:
|
||||
description: 对应的 HiFox 任务 UUID
|
||||
required: true
|
||||
confirm:
|
||||
description: deploy-production 或 retry-writeback
|
||||
required: true
|
||||
approval_event:
|
||||
description: HiFox 自动触发填写的状态事件 UUID
|
||||
required: false
|
||||
acceptance_digest:
|
||||
description: HiFox 自动触发填写的验收记录摘要
|
||||
required: false
|
||||
|
||||
concurrency:
|
||||
group: cloud-test-governance-main-production
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: 核对手动入口及发布输入
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
git init -q .
|
||||
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
|
||||
git checkout -q --detach "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
python3 scripts/production_cd.py guard --event "$GITHUB_EVENT_PATH"
|
||||
|
||||
publish:
|
||||
needs: [guard]
|
||||
runs-on: kg-production-cd
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- name: 取同一提交的控制端代码
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
git init -q .
|
||||
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
|
||||
git checkout -q --detach "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
- name: 调用云主站受限发布入口并读回回执
|
||||
env:
|
||||
KG_CD_SSH_KEY: ${{ secrets.KG_CD_SSH_KEY }}
|
||||
KG_CD_KNOWN_HOSTS: ${{ secrets.KG_CD_KNOWN_HOSTS }}
|
||||
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
||||
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
||||
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
||||
@@ -0,0 +1,80 @@
|
||||
name: prepare-candidate
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
plan:
|
||||
description: 'Release task UUID, exact SHA, baseline, requirement PRs and additional reviewed commits (JSON)'
|
||||
required: true
|
||||
mode:
|
||||
description: 'verify or prepare'
|
||||
required: true
|
||||
default: verify
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: knowledge-governance-candidate
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Verify release scope and CI
|
||||
env:
|
||||
KG_CANDIDATE_READ_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
case "$GITHUB_SERVER_URL" in
|
||||
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
case "$GITHUB_REF" in refs/heads/*) ;; *) exit 1 ;; esac
|
||||
git init -q .
|
||||
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
|
||||
auth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$KG_CANDIDATE_READ_TOKEN"; }; f' "$@"; }
|
||||
auth fetch -q origin "$GITHUB_REF" +refs/heads/main:refs/remotes/origin/main
|
||||
git checkout --detach -q "$GITHUB_SHA"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
export KG_CANDIDATE_FORGE="$GITHUB_SERVER_URL"
|
||||
python3 scripts/candidate_release.py guard --event "$GITHUB_EVENT_PATH" --repo .
|
||||
|
||||
prepare:
|
||||
if: ${{ inputs.mode == 'prepare' && gitea.ref == 'refs/heads/main' }}
|
||||
needs: [guard]
|
||||
runs-on: kg-candidate
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Build and deploy isolated candidate
|
||||
env:
|
||||
KG_CANDIDATE_ACCESS: ${{ secrets.KG_CANDIDATE_ACCESS }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
|
||||
test "$GITHUB_EVENT_NAME" = workflow_dispatch
|
||||
test "$GITHUB_REF" = refs/heads/main
|
||||
test -n "$KG_CANDIDATE_ACCESS"
|
||||
python3 - <<'PY'
|
||||
import json, os, sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
with open(os.environ['GITHUB_EVENT_PATH']) as source:
|
||||
event = json.load(source)
|
||||
if event.get('inputs', {}).get('mode') != 'prepare':
|
||||
sys.exit('candidate workflow mode is not prepare')
|
||||
data = json.dumps({'run': os.environ['GITHUB_RUN_ID'], 'plan': json.loads(event['inputs']['plan'])}).encode()
|
||||
request = Request('http://127.0.0.1:38984/prepare', data=data, headers={
|
||||
'Authorization': 'Bearer ' + os.environ['KG_CANDIDATE_ACCESS'], 'Content-Type': 'application/json'})
|
||||
opener = build_opener(ProxyHandler({}))
|
||||
try:
|
||||
with opener.open(request, timeout=2540) as response:
|
||||
print(response.read(65536).decode())
|
||||
except HTTPError as exc:
|
||||
print(exc.read(4096).decode(), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PY
|
||||
+5911
-12
File diff suppressed because it is too large
Load Diff
+3
-2
@@ -50,7 +50,8 @@ RUN set -eux; \
|
||||
dws version
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/ /app/
|
||||
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/artifact_fetch.py \
|
||||
scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \
|
||||
scripts/pp_client.py scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
RUN chmod 0644 /app/scripts/*.py
|
||||
USER 65532:65532
|
||||
CMD ["/app/api"]
|
||||
|
||||
@@ -27,6 +27,14 @@ BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
verify:
|
||||
$(PY) scripts/ci_checks.py
|
||||
|
||||
.PHONY: qa qa-doctor qa-self-test
|
||||
qa:
|
||||
$(PY) scripts/qa_env.py run
|
||||
qa-doctor:
|
||||
$(PY) scripts/qa_env.py doctor
|
||||
qa-self-test:
|
||||
$(PY) -m unittest discover -s scripts -p test_qa_env.py -v
|
||||
|
||||
# 清单:哪些是必需项、在哪个档案(local / ci)下必需
|
||||
list:
|
||||
$(PY) scripts/ci_checks.py --list
|
||||
|
||||
@@ -52,9 +52,9 @@ Knowledge Adapter / DobotAI 网关
|
||||
|
||||
| 来源 | 当前接入方式 | 参考文档 |
|
||||
| --- | --- | --- |
|
||||
| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) |
|
||||
| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [登录授权](docs/DWS_LOGIN.md) · [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) |
|
||||
| AList | 来源目录与资料获取,依赖指定连接和凭据 | [用户操作流程](docs/OPERATIONS_RUNBOOK.md) |
|
||||
| PP(资料门户) | 本地清单、历史账本接管与只读扫描 | [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) |
|
||||
| PP(资料门户) | 页面管理 API 与认证配置;真实校验、只读扫描及取件 | [认证配置](docs/SOURCE_AUTH_CONFIGURATION.md) · [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) |
|
||||
|
||||
IT、行政等是待扩展的业务资料范围,不是已经完成的新连接器。接入敏感资料前,需要先确认 Owner、有效版本、可见范围与知识库路由。
|
||||
|
||||
@@ -71,15 +71,16 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|
||||
|
||||
## 访问与部署
|
||||
|
||||
### 已部署环境
|
||||
### 运行架构与访问入口
|
||||
|
||||
Compose 中网页入口固定映射为 **宿主机 `8088` → Web 容器 `8080`**。网页和 `/api/` 使用同源入口。
|
||||
| 组件 | 职责 | 接手时从这里看 |
|
||||
|---|---|---|
|
||||
| React/Vite + Web Nginx | 提供静态页面,同源转发 `/api/` 和 `/health` | [前端开发代理](web/vite.config.ts)、[Compose 的 Nginx 配置](deploy/nginx.conf) |
|
||||
| Go API + 治理 PostgreSQL | 认证、角色、来源、绑定、审核、任务与发布记录。云测试使用独立逻辑库 `knowledge_governance_test` | [API](cmd/api)、[接口契约](api/openapi.yaml) |
|
||||
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源接入](docs/OPERATIONS_RUNBOOK.md#接入外部平台)、[来源认证](docs/SOURCE_AUTH_CONFIGURATION.md) |
|
||||
| 发布 worker + 生产 WeKnora | 按已锁定的批次和目标执行受控发布与读回。问答端通过下游服务使用已发布知识 | [发布 worker](cmd/release-worker)、[操作手册](docs/OPERATIONS_RUNBOOK.md) |
|
||||
|
||||
- 本机访问:`http://127.0.0.1:8088/`
|
||||
- 局域网访问:`http://<服务器内网IP>:8088/`
|
||||
- 健康入口:`http://127.0.0.1:8088/health`
|
||||
|
||||
可以由 NAS 反向代理提供 HTTPS 域名入口,目标为平台服务器的 `8088`,保持路径原样转发。公网开放前必须验证鉴权、访问控制及转发头配置,不直接暴露数据库或内部管理接口。
|
||||
从自己的电脑做系统设置验收,使用 SSH 转发后的 `http://127.0.0.1:28189/`。云测试主控制台使用受限内网入口 `http://100.85.111.121:8088/`。仓内 Compose 则将宿主 `8088` 映射到 Web 容器 `8080`。选择入口时先确认要看的部署。隧道命令、生产 `090` 服务地址和 HTTPS 反代示例见[运维手册](docs/OPERATIONS_RUNBOOK.md#入口与反向代理)。
|
||||
|
||||
**平台入口展示当前部署版本,不是每次 CI 的构建预览。** CI 静态预览由独立链路提供;CI 通过不会自动更新运行服务。
|
||||
|
||||
@@ -94,13 +95,7 @@ Compose 中网页入口固定映射为 **宿主机 `8088` → Web 容器 `8080`*
|
||||
- 来源目录、spool 与运行状态挂载;按部署主机调整路径和 UID/GID。
|
||||
- 测试 WeKnora 连接与对内/对外路由;生产发布按独立配置和授权接线。
|
||||
|
||||
准备完成后,由获授权的操作者执行:
|
||||
|
||||
```bash
|
||||
docker compose up --build -d
|
||||
```
|
||||
|
||||
主机需要提权时,由操作者按本机权限规则执行,不在自动化中默认使用 sudo。停止服务可用 `docker compose down`;**不要执行 `docker compose down -v`,除非明确批准删除数据库卷。**
|
||||
仓内 Compose 含 `postgres` 演练服务。云测试和生产使用阿里云 RDS,部署前先核对目标逻辑库、当前迁移版本、待运行的迁移及所用的环境配置。API 和 worker 启动可执行迁移。已有环境先用 `docker compose config --services` 检查服务清单,按该环境的发布手册切换已验证的产物。前端开发可直接使用下面的 Vite 流程。
|
||||
|
||||
## 配置与安全边界
|
||||
|
||||
@@ -114,7 +109,7 @@ docker compose up --build -d
|
||||
|
||||
## 开发与 CI
|
||||
|
||||
基础环境:Go 1.26、Node.js 22、npm,以及检查脚本所需的 Python 3 和工具链。依赖以仓库锁文件和实际 CI 配置为准。
|
||||
本机和 QA 虚拟机的依赖安装、前后端启动、测试命令及 PostgreSQL 测试库准备见 [开发与测试指南](docs/DEVELOPMENT_AND_TESTING.md)。页面验收标准见[运维手册](docs/OPERATIONS_RUNBOOK.md#开发测试和现场验收)。
|
||||
|
||||
```bash
|
||||
make verify # 完整检查入口:本地与 CI 使用同一套规则
|
||||
@@ -127,7 +122,7 @@ make list # 查看检查清单与适用范围
|
||||
|
||||
## 问答运营模型配置
|
||||
|
||||
管理员在「系统设置 → 服务配置 → 问答评估模型」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。页面顶部显示当前已保存的模型与服务端核验结果,下方编辑的是独立草稿:测试连接只核验草稿,保存才更新当前连接,保存成功后按服务端响应回显。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显、默认收起,只有「更换密钥」或首次录入才显示输入框,更换基础地址须重新录入密钥;「清除密钥并停用」在单独折叠区里二次确认,只作用于已保存连接。录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
|
||||
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}": {"get":{"operationId":"getQAWeeklyMailConfirmation","tags":["QA operations"],"summary":"读取该周是否已确认自动发送;current=false表示确认后正文已被修改,需要重新确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"post":{"operationId":"confirmQAWeeklyMail","tags":["QA operations"],"summary":"确认本周周报可自动发送,绑定当前草稿版本与正文哈希;后续改动使确认失效,不发送改动后的正文","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-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"delete":{"operationId":"unconfirmQAWeeklyMail","tags":["QA operations"],"summary":"取消该周的自动发送确认","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-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/sends": {"get":{"operationId":"listQAWeeklyMailSends","tags":["QA operations"],"summary":"读取周报邮件发送记录:周次、草稿版本、发送中/已发送/失败及错误摘要,不返回正文或收件人","parameters":[{"name":"week","in":"query","required":false,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/test": {"post":{"operationId":"sendQAWeeklyMailTest","tags":["QA operations"],"summary":"管理员用当前已保存的邮件设置立即发送一封测试邮件,正文取该周已保存草稿;不写入发送记录、不改变确认状态、不把该周标记为已发送","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["week"],"properties":{"week":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可测试发送"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因"},"503":{"description":"邮件设置存储不可用"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/send/{week}": {"get":{"operationId":"previewQAWeeklyMailSend","tags":["QA operations"],"summary":"管理员补发前核对:按周、已确认版本与正文hash返回真实主送/抄送人数、版本与是否已发送;不投递、不写记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"revision","in":"query","required":true,"schema":{"type":"integer","minimum":1}},{"name":"body_sha256","in":"query","required":true,"schema":{"type":"string","pattern":"^[0-9a-f]{64}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"邮件设置存储不可用"}}},"post":{"operationId":"sendQAWeeklyMailFormal","tags":["QA operations"],"summary":"管理员正式补发周报:精确指定周、已确认版本与正文hash;已结束周可发、当前周须到设定时点、未来周拒绝;正文/看板图片/主送/抄送与自动发送共用,写入正式发送记录并返回真实message_id;已发送幂等、结果未知不重发","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-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["revision","body_sha256"],"properties":{"revision":{"type":"integer","minimum":1},"body_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且需同源操作意图"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知/授权码缺失"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因且不写已发送"},"503":{"description":"邮件设置存储不可用"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image": {"post":{"operationId":"saveQAWeeklyMailImage","tags":["QA operations"],"summary":"管理员保存该周确认对应的统计看板 PNG;发送时作为内嵌图片(cid)放在正文末尾,正文改动使确认失效后不再使用旧图","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-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["png_base64"],"properties":{"png_base64":{"type":"string","maxLength":12000000}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可上传"},"429":{"description":"请求过快"},"503":{"description":"邮件设置存储不可用"}}}},
|
||||
"/api/v1/qa-ops/departments/statistics": {
|
||||
"post": {
|
||||
@@ -1368,6 +1369,45 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/jobs/{id}/reconcile-capture": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "reconcileLibraryCapture",
|
||||
"summary": "仅在 completed capture queue、精确 test_sealed 版本与归档复核一致时,修复该封存作业终态;不重新封存",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "已修复或已成功(幂等)"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限"
|
||||
},
|
||||
"404": {
|
||||
"description": "作业不存在"
|
||||
},
|
||||
"409": {
|
||||
"description": "队列/阶段/版本/归档证据不一致,拒绝修复"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/restore-availability": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -1655,6 +1695,93 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/verifications": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "getLibraryRestoreVerification",
|
||||
"summary": "当前整库目标的恢复验证证据:verified 只由真实演练记录回答(按 target_id 绑定,换目标自动失效),并返回完整目标与失败原因",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "scope",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"internal",
|
||||
"external"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "目标与证据:verified/reason/latest/history/target"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "恢复验证存储不可用或证据读取失败"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "startLibraryRestoreVerification",
|
||||
"summary": "发起一次真实恢复验证(管理员):维护隔离下捕获目标 → 校验基线 → 写 canary 证明校验有效 → 按预备份恢复 → 复核,通过后才产生同步闸口认的证据",
|
||||
"responses": {
|
||||
"202": {
|
||||
"description": "已创建 verify 作业(worker 在维护窗口内真实执行)"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"description": "不是管理员"
|
||||
},
|
||||
"409": {
|
||||
"description": "目标正在维护或已有在飞写作业(同步/恢复/基线/验证互斥)"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "生产写入闸口关闭或恢复验证存储不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"scope"
|
||||
],
|
||||
"properties": {
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"internal",
|
||||
"external"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/snapshots/{id}": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -1845,6 +1972,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/backup-schedule/inventory": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getBackupScheduleInventory",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/ServiceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/backup-schedule/apply": {
|
||||
"post": {
|
||||
"tags": [
|
||||
@@ -2555,6 +2705,211 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/pp-connection": {
|
||||
"get": {
|
||||
"operationId": "getPPConnection",
|
||||
"summary": "管理员读取 PP 配置元数据及最近检查结果",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPConnectionView"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"operationId": "savePPConnection",
|
||||
"summary": "管理员保存并真实校验 PP 配置",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPConnectionView"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PPConnectionDraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/pp-connection/test": {
|
||||
"post": {
|
||||
"operationId": "testPPConnection",
|
||||
"summary": "管理员使用草稿真实登录并读取最小目录,不登记来源",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PPConnectionDraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/dingtalk-spaces/validate": {
|
||||
"post": {
|
||||
"operationId": "validateDingtalkSourceSpaces",
|
||||
"summary": "管理员用共享 DWS 身份真实检查所选空间可见性",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "请求完成"
|
||||
},
|
||||
"400": {
|
||||
"description": "输入格式错误"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录或重新授权"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限或缺少目录权限"
|
||||
},
|
||||
"409": {
|
||||
"description": "配置或账号已变化"
|
||||
},
|
||||
"422": {
|
||||
"description": "明确拒绝本次配置,原配置保留"
|
||||
},
|
||||
"500": {
|
||||
"description": "内部错误"
|
||||
},
|
||||
"503": {
|
||||
"description": "依赖服务暂不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"urls"
|
||||
],
|
||||
"properties": {
|
||||
"urls": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/dingtalk-spaces": {
|
||||
"post": {
|
||||
"tags": [
|
||||
@@ -3307,6 +3662,26 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/system/worker-capabilities": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getWorkerCapabilities",
|
||||
"summary": "读取 worker 能力心跳(执行器是否注册上传/解析链)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/routing-bindings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -3355,6 +3730,61 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings": {
|
||||
"get": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "getKBBindings",
|
||||
"summary": "读取测试/生产环境的 WeKnora 连接与内外库绑定(密钥不回显)",
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings/{environment}/catalog": {
|
||||
"post": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "catalogKBBindingConnection",
|
||||
"summary": "用草稿地址与密钥真实列库(管理员,只读,分页)",
|
||||
"parameters": [
|
||||
{"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBCatalogInput"}}}
|
||||
},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"409": {"$ref": "#/components/responses/Conflict"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings/{environment}": {
|
||||
"put": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "saveKBBinding",
|
||||
"summary": "一次保存当前环境的连接与内外库绑定(管理员)",
|
||||
"parameters": [
|
||||
{"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBBindingSaveInput"}}}
|
||||
},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"409": {"$ref": "#/components/responses/Conflict"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/production-kb-bindings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -5732,6 +6162,208 @@
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"KBBindingEnvironmentView": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["environment", "revision", "base_url", "key_configured", "internal_kb_id", "external_kb_id", "verification", "storage_ready", "source"],
|
||||
"properties": {
|
||||
"environment": {"type": "string", "enum": ["test", "production"]},
|
||||
"revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_configured": {"type": "boolean"},
|
||||
"key_source": {"type": "string", "enum": ["sealed", "file", "none"]},
|
||||
"internal_kb_id": {"type": "string"},
|
||||
"internal_kb_name": {"type": "string"},
|
||||
"external_kb_id": {"type": "string"},
|
||||
"external_kb_name": {"type": "string"},
|
||||
"verification": {"type": "string"},
|
||||
"checked_at": {"type": ["string", "null"]},
|
||||
"updated_by": {"type": "string"},
|
||||
"updated_at": {"type": ["string", "null"]},
|
||||
"source": {"type": "string", "enum": ["web", "legacy"]},
|
||||
"storage_ready": {"type": "boolean"},
|
||||
"replanned": {"type": "integer", "minimum": 0},
|
||||
"retired_duplicates": {"type": "integer", "minimum": 0}
|
||||
}
|
||||
},
|
||||
"KBBindingSnapshot": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["environments", "storage_ready"],
|
||||
"properties": {
|
||||
"environments": {"type": "array", "items": {"$ref": "#/components/schemas/KBBindingEnvironmentView"}},
|
||||
"storage_ready": {"type": "boolean"}
|
||||
}
|
||||
},
|
||||
"KBCatalogInput": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["base_url", "key_action", "page", "page_size"],
|
||||
"properties": {
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_action": {"type": "string", "enum": ["keep", "replace"]},
|
||||
"api_key": {"type": "string", "writeOnly": true, "maxLength": 4096},
|
||||
"page": {"type": "integer", "minimum": 1},
|
||||
"page_size": {"type": "integer", "minimum": 1, "maximum": 100}
|
||||
}
|
||||
},
|
||||
"KBBindingSaveInput": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["base_url", "key_action", "internal_kb_id", "external_kb_id"],
|
||||
"properties": {
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_action": {"type": "string", "enum": ["keep", "replace"]},
|
||||
"api_key": {"type": "string", "writeOnly": true, "maxLength": 4096},
|
||||
"internal_kb_id": {"type": "string"},
|
||||
"external_kb_id": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"KBCatalogOption": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"knowledge_count": {"type": "integer"}
|
||||
}
|
||||
},
|
||||
"PPConnectionDraft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"base_url",
|
||||
"username",
|
||||
"revision"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"base_url": {
|
||||
"type": "string",
|
||||
"format": "uri",
|
||||
"description": "HTTPS API 根地址"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"maxLength": 255
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"writeOnly": true,
|
||||
"maxLength": 8192,
|
||||
"description": "省略或空值保留已存密码"
|
||||
},
|
||||
"revision": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"pending_id": {
|
||||
"type": "string",
|
||||
"description": "继续校验已保存的待验证修改"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPSafeMetadata": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"base_url",
|
||||
"username",
|
||||
"password_configured"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"base_url": {
|
||||
"type": "string",
|
||||
"format": "uri"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
},
|
||||
"password_configured": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPObservation": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"state",
|
||||
"message",
|
||||
"checked_at"
|
||||
],
|
||||
"properties": {
|
||||
"state": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"valid",
|
||||
"auth_failed",
|
||||
"permission_denied",
|
||||
"incomplete",
|
||||
"unavailable",
|
||||
"invalid_response"
|
||||
]
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"checked_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PPConnectionView": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"revision": {
|
||||
"type": "integer"
|
||||
},
|
||||
"active": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPSafeMetadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pending": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPSafeMetadata"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"observation": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pending_observation": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PPObservation"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"QAReportedHistoricalRate": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
|
||||
+146
-34
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
@@ -16,16 +17,20 @@ import (
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/qawemail"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
@@ -52,6 +57,25 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s
|
||||
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
|
||||
}
|
||||
|
||||
// 宿主快照的展示路径必须与采集 root 同一份:容器内快照路径不可给操作者复制,
|
||||
// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。
|
||||
func backupInventoryHostRoot(config appconfig.Config) string {
|
||||
if config.BackupHostReadonlyHostPath != "" {
|
||||
return config.BackupHostReadonlyHostPath
|
||||
}
|
||||
return path.Join(config.BackupHostRoot, "rds-logical")
|
||||
}
|
||||
|
||||
func backupInventorySource(config appconfig.Config) string {
|
||||
if config.BackupHostReadonlySource != "" {
|
||||
return config.BackupHostReadonlySource
|
||||
}
|
||||
if config.BackupHostTarget == "" {
|
||||
return ""
|
||||
}
|
||||
return config.BackupHostTarget + ":" + backupInventoryHostRoot(config)
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -90,48 +114,109 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return errors.New("read production release authorization token")
|
||||
}
|
||||
}
|
||||
// P10: with a mounted API key the probe verifies a real knowledge-base read
|
||||
// (readiness); without one it degrades to the liveness-only HTTP check.
|
||||
var weknoraReadiness func(context.Context) error
|
||||
var knowledgeBaseLister httpapi.KnowledgeBaseLister
|
||||
if strings.TrimSpace(config.TestWeKnoraBaseURL) != "" {
|
||||
if apiKey, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); keyErr == nil {
|
||||
probeTimeout := config.TestWeKnoraHTTPTimeout
|
||||
if probeTimeout > 10*time.Second || probeTimeout <= 0 {
|
||||
probeTimeout = 10 * time.Second
|
||||
}
|
||||
if probeClient, clientErr := weknora.NewClient(weknora.ClientConfig{BaseURL: config.TestWeKnoraBaseURL, APIKey: apiKey, Timeout: probeTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}); clientErr == nil {
|
||||
knowledgeBaseLister = probeClient
|
||||
routingKB := config.InternalRoutingKnowledgeBaseID
|
||||
weknoraReadiness = func(probeCtx context.Context) error {
|
||||
_, _, err := probeClient.ListKnowledge(probeCtx, routingKB, 1, 1)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Production WeKnora is probed for liveness only: the console must show the
|
||||
// real state of that endpoint, while credentials and the publish target stay
|
||||
// in the release runtime config (RELEASE_CONFIG_FILE).
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 服务配置」,管理员保存的值是
|
||||
// 生产 WeKnora 端点:配置入口在网页「系统设置 → 知识库映射」,管理员保存的值是
|
||||
// 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在
|
||||
// release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。
|
||||
actionStore := postgresstore.NewStore(pool)
|
||||
kbBindings := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
|
||||
Timeout: 10 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
|
||||
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
},
|
||||
AllowPrivateHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.WeKnoraAllowPrivateHTTP,
|
||||
kbbinding.EnvProduction: config.WeKnoraAllowPrivateHTTP,
|
||||
},
|
||||
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if env == kbbinding.EnvProduction {
|
||||
if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.ProductionWeKnoraBaseURL
|
||||
}
|
||||
if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LegacyKey: func(env string) (string, error) {
|
||||
path := config.TestWeKnoraAPIKeyFile
|
||||
if env == kbbinding.EnvProduction {
|
||||
path = config.ProductionWeKnoraAPIKeyFile
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
return weknora.ReadAPIKeyFile(path)
|
||||
},
|
||||
LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) {
|
||||
if env == kbbinding.EnvProduction {
|
||||
internal, external, _, err := actionStore.LoadProductionKBBindings(resolveCtx)
|
||||
return internal, external, err
|
||||
}
|
||||
internal, external, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
return internal, external, err
|
||||
},
|
||||
})
|
||||
productionEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.ProductionWeKnoraBaseURL
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction)
|
||||
}
|
||||
testEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.TestWeKnoraBaseURL
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest)
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
// P10 readiness 与执行链看同一目标:当前持久化绑定、当前有效连接(加密存储优先、
|
||||
// 旧部署 file 凭据兜底)。任何一项读取失败都必须显式报错,不能静默退回旧值。
|
||||
readinessResolver := func(resolveCtx context.Context) (readiness.Target, error) {
|
||||
target := readiness.Target{KnowledgeBaseID: config.InternalRoutingKnowledgeBaseID}
|
||||
stored, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
if err != nil {
|
||||
return readiness.Target{}, fmt.Errorf("读取当前知识库绑定失败")
|
||||
}
|
||||
if strings.TrimSpace(stored) != "" {
|
||||
target.KnowledgeBaseID = strings.TrimSpace(stored)
|
||||
}
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
if err != nil {
|
||||
return readiness.Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err)
|
||||
}
|
||||
target.BaseURL, target.APIKey = connection.BaseURL, connection.APIKey
|
||||
return target, nil
|
||||
}
|
||||
readinessProber := readiness.Prober{
|
||||
Resolve: readinessResolver,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
weknoraProbe := func(probeCtx context.Context) (string, error) {
|
||||
result := readinessProber.Check(probeCtx)
|
||||
return result.Target, result.Err
|
||||
}
|
||||
knowledgeBaseLister := &weKnoraLister{
|
||||
resolve: func(resolveCtx context.Context) (string, string, error) {
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return connection.BaseURL, connection.APIKey, err
|
||||
},
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -143,6 +228,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
})
|
||||
productionKnowledgeBases := &productionKnowledgeBaseLister{bindings: kbBindings, timeout: 10 * time.Second, allowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP}
|
||||
// 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。
|
||||
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
@@ -177,7 +263,20 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return fmt.Errorf("快照搬运接线无效: %w", handoffErr)
|
||||
}
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
ppStateFile := getenv("PP_AUTH_STATE_FILE")
|
||||
if ppStateFile == "" {
|
||||
ppStateFile = "/data/source-auth/pp/settings.json"
|
||||
}
|
||||
ppPython := getenv("PP_AUTH_PYTHON")
|
||||
if ppPython == "" {
|
||||
ppPython = "/usr/bin/python3"
|
||||
}
|
||||
ppScript := getenv("PP_AUTH_CHECK_SCRIPT")
|
||||
if ppScript == "" {
|
||||
ppScript = "/app/scripts/pp_client.py"
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
PPConnection: &ppauth.Manager{Path: ppStateFile, LegacyPath: getenv("PP_LEGACY_CREDENTIALS_FILE"), Probe: ppauth.CommandProbe(ppPython, ppScript)},
|
||||
LibraryHandoffEnabled: handoffConfigured,
|
||||
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
|
||||
QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil),
|
||||
@@ -190,14 +289,16 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
QAOpsTenantKey: qaSettings.TenantKey,
|
||||
QAOpsEnabled: qaSettings.Enabled,
|
||||
QAOpsProblem: qaSettings.Problem,
|
||||
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()),
|
||||
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
|
||||
Monitor: monitorProvider,
|
||||
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
|
||||
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
|
||||
RoutingBindings: postgresstore.NewStore(pool),
|
||||
KnowledgeBases: knowledgeBaseLister,
|
||||
ProductionBindings: postgresstore.NewStore(pool),
|
||||
ProductionKnowledgeBases: serviceTargetVerifier,
|
||||
ProductionKnowledgeBases: productionKnowledgeBases,
|
||||
KBBindings: kbBindings,
|
||||
WeKnoraAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL,
|
||||
ServiceTargetVerifier: serviceTargetVerifier,
|
||||
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
|
||||
@@ -207,6 +308,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
|
||||
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
|
||||
DingtalkSources: dingtalkSourceLister{},
|
||||
DWSLogin: dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{}),
|
||||
DingtalkDocuments: dingtalkSourceLister{},
|
||||
BackupSchedule: postgresstore.NewStore(pool),
|
||||
VersionHistory: versionHistoryStore,
|
||||
@@ -217,6 +319,8 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
LibraryTargetWriters: config.LibraryTargetWriters,
|
||||
LibraryTargetIngressURL: config.LibraryTargetIngressURL,
|
||||
LibraryTargetIngressService: config.LibraryTargetIngressService,
|
||||
LibraryTargetIngressMode: config.LibraryTargetIngressMode,
|
||||
LibraryTargetHealthURL: config.LibraryTargetHealthURL,
|
||||
LibraryTargetDockerSocket: config.LibraryTargetDockerSocket,
|
||||
LibraryTargetJournalRoot: config.LibraryTargetJournalRoot,
|
||||
LibrarySourceInstance: config.SourceInstance(),
|
||||
@@ -232,6 +336,8 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
LibraryProductionInternalKB: config.LibraryProductionInternalKB,
|
||||
LibraryProductionExternalKB: config.LibraryProductionExternalKB,
|
||||
LibraryProductionTenantID: config.LibraryProductionTenantID,
|
||||
LibraryProductionIndex: config.LibraryProductionIndex,
|
||||
LibraryProductionS3Bucket: config.LibraryProductionS3Bucket,
|
||||
LibraryRetentionVersions: config.LibraryRetentionVersions,
|
||||
LibraryRetentionDays: config.LibraryRetentionDays,
|
||||
BackupHost: backuphost.New(backuphost.Config{
|
||||
@@ -240,6 +346,12 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ScriptDir: config.BackupHostScriptDir,
|
||||
Root: config.BackupHostRoot,
|
||||
}),
|
||||
BackupInventory: backupinventory.New(backupinventory.Config{
|
||||
MetadataPath: config.BackupHostMetadataPath,
|
||||
HostRoot: config.BackupHostReadonlyHostPath,
|
||||
Source: backupInventorySource(config),
|
||||
MaxAge: config.BackupHostMetadataMaxAge,
|
||||
}),
|
||||
Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour},
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
|
||||
// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源:
|
||||
// 端点来自网页「知识库映射」保存的连接配置(endpoint 内部已做 env 兜底),知识库来自
|
||||
// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。
|
||||
// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。
|
||||
func newWeKnoraReadinessResolver(
|
||||
endpoint func(context.Context) string,
|
||||
envKnowledgeBaseID string,
|
||||
loadBinding func(context.Context) (string, error),
|
||||
readKey func() (string, error),
|
||||
) func(context.Context) (readiness.Target, error) {
|
||||
resolver := readiness.Resolver{
|
||||
Endpoint: endpoint,
|
||||
DefaultKB: envKnowledgeBaseID,
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
if loadBinding == nil {
|
||||
return "", nil
|
||||
}
|
||||
stored, err := loadBinding(resolveCtx)
|
||||
if err != nil {
|
||||
log.Printf("readiness: load routing bindings: %v", err)
|
||||
}
|
||||
return stored, err
|
||||
},
|
||||
ReadKey: func() (string, error) {
|
||||
if readKey == nil {
|
||||
return "", nil
|
||||
}
|
||||
value, err := readKey()
|
||||
if err != nil {
|
||||
log.Printf("readiness: read WeKnora API key: %v", err)
|
||||
}
|
||||
return value, err
|
||||
},
|
||||
}
|
||||
return resolver.Resolve
|
||||
}
|
||||
|
||||
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
|
||||
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
|
||||
type weKnoraLister struct {
|
||||
resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
|
||||
if lister.resolve == nil {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
baseURL, apiKey, err := lister.resolve(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
baseURL = strings.TrimSpace(baseURL)
|
||||
if baseURL == "" {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
if strings.TrimSpace(apiKey) == "" {
|
||||
return nil, fmt.Errorf("WeKnora API Key 未配置")
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.ListKnowledgeBases(ctx)
|
||||
}
|
||||
|
||||
// productionKnowledgeBaseLister 列生产端知识库时使用「生产环境」保存的连接
|
||||
// (加密密钥),而不是另一条文件凭据。显式传入的地址必须与已保存连接一致,
|
||||
// 防止把生产密钥发往另一个地址。
|
||||
type productionKnowledgeBaseLister struct {
|
||||
bindings *kbbinding.Store
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (lister *productionKnowledgeBaseLister) ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error) {
|
||||
if lister.bindings == nil {
|
||||
return nil, fmt.Errorf("生产知识库连接存储未接线")
|
||||
}
|
||||
target, err := lister.bindings.Resolve(ctx, kbbinding.EnvProduction)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if explicit := strings.TrimSpace(baseURL); explicit != "" && explicit != target.BaseURL {
|
||||
return nil, fmt.Errorf("生产地址与已保存的连接不一致:请在生产工作区重新保存连接")
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: target.BaseURL, APIKey: target.APIKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.ListKnowledgeBases(ctx)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
|
||||
// F13 的接线回归:探测目标必须来自「网页保存的端点 + 当前持久化绑定」,
|
||||
// env 只能是未绑定时的引导兜底;任何一项都不许在启动时固化。
|
||||
func TestReadinessResolverUsesPersistedBindingOverEnv(t *testing.T) {
|
||||
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
|
||||
const storedKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
|
||||
resolve := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
envKB,
|
||||
func(context.Context) (string, error) { return storedKB, nil },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
target, err := resolve(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if target.KnowledgeBaseID != storedKB || target.BaseURL != "https://weknora.test" || target.APIKey != "key-1" {
|
||||
t.Fatalf("resolved target = %#v", target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessResolverFallsBackToEnvOnlyWhenUnbound(t *testing.T) {
|
||||
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
|
||||
resolve := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
envKB,
|
||||
func(context.Context) (string, error) { return "", nil },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
target, err := resolve(context.Background())
|
||||
if err != nil || target.KnowledgeBaseID != envKB {
|
||||
t.Fatalf("unbound fallback = %#v, %v", target, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessResolverReportsBindingAndCredentialFailures(t *testing.T) {
|
||||
bindingDown := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
"env-kb",
|
||||
func(context.Context) (string, error) { return "", errors.New("db unavailable") },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
target, err := bindingDown(context.Background())
|
||||
if err == nil {
|
||||
t.Fatalf("binding read failure must not silently probe env: %#v", target)
|
||||
}
|
||||
keyDown := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
"env-kb",
|
||||
func(context.Context) (string, error) { return "", nil },
|
||||
func() (string, error) { return "", errors.New("key file missing") },
|
||||
)
|
||||
if _, err := keyDown(context.Background()); err == nil {
|
||||
t.Fatal("missing API key must surface, not degrade to liveness-only")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessResolverMarksUnconfiguredEndpoint(t *testing.T) {
|
||||
resolve := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "" },
|
||||
"env-kb",
|
||||
func(context.Context) (string, error) { return "", nil },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
// 端点缺失时归类为「未配置」,不是「服务不可用」。
|
||||
result := readiness.Prober{Resolve: resolve}.Check(context.Background())
|
||||
if !errors.Is(result.Err, readiness.ErrNotConfigured) {
|
||||
t.Fatalf("blank endpoint probe = %v, want ErrNotConfigured", result.Err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) {
|
||||
base := func(name string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != "/api/v1/knowledge-bases" {
|
||||
writer.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"success":true,"data":[{"id":"` + name + `","name":"` + name + `"}]}`))
|
||||
}))
|
||||
}
|
||||
first, second := base("kb-a"), base("kb-b")
|
||||
defer first.Close()
|
||||
defer second.Close()
|
||||
endpoint := first.URL
|
||||
lister := &weKnoraLister{
|
||||
resolve: func(context.Context) (string, string, error) { return endpoint, "key-1", nil },
|
||||
timeout: time.Second,
|
||||
}
|
||||
bases, err := lister.ListKnowledgeBases(context.Background())
|
||||
if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" {
|
||||
t.Fatalf("initial endpoint bases = %#v, %v", bases, err)
|
||||
}
|
||||
endpoint = second.URL
|
||||
bases, err = lister.ListKnowledgeBases(context.Background())
|
||||
if err != nil || len(bases) != 1 || bases[0].ID != "kb-b" {
|
||||
t.Fatalf("rotated endpoint bases = %#v, %v", bases, err)
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,13 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
"knowledge-governance/internal/librarydsn"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
)
|
||||
|
||||
@@ -25,22 +28,43 @@ func main() {
|
||||
flag.StringVar(&config.ArchiveRoot, "archive", filepath.Join(home, ".local/share/knowledge-governance/library"), "sealed artifact root")
|
||||
flag.StringVar(&config.JournalRoot, "journal", filepath.Join(home, ".local/share/knowledge-governance/freeze"), "freeze journal root")
|
||||
flag.StringVar(&config.SourceApp, "source-app", "WKNFull-app", "source container describing the stack")
|
||||
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container")
|
||||
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container; empty = the source DB lives on a managed instance and is reached with the source app env (DB_HOST/...)")
|
||||
flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container")
|
||||
flag.StringVar(&config.SourceS3Endpoint, "source-s3-endpoint", "", "host-reachable source object-store endpoint (overrides the container-internal one)")
|
||||
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container")
|
||||
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
|
||||
flag.StringVar(&config.Project, "project", "weknora071full", "Compose project owning the writers")
|
||||
flag.StringVar(&config.Writers, "writers", "app", "declared writer services")
|
||||
nonWriters := flag.String("non-writers", defaultNonWriters, "service=reason for every other project service")
|
||||
allowUIDs := flag.String("allow-peer-uid", "", "extra peer uids allowed to connect (comma separated; default: same uid only)")
|
||||
flag.DurationVar(&config.MaxDuration, "max-duration", 10*time.Minute, "upper bound for one operation")
|
||||
describe := flag.Bool("describe", false, "print the fixed configuration and exit")
|
||||
flag.Parse()
|
||||
if strings.TrimSpace(*allowUIDs) != "" {
|
||||
for _, raw := range strings.Split(*allowUIDs, ",") {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
uid, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil {
|
||||
log.Fatalf("--allow-peer-uid 需要十进制 uid:%q", raw)
|
||||
}
|
||||
config.AllowedPeerUIDs = append(config.AllowedPeerUIDs, uint32(uid))
|
||||
}
|
||||
}
|
||||
config.NonWriters = *nonWriters
|
||||
|
||||
agent, err := libraryagent.New(config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if *describe {
|
||||
// describe 只回答"这两个库从哪来"。地址与凭据一律不出现:这段输出会被贴进
|
||||
// 工单与日志,而 RDS 的连接串里带口令。
|
||||
log.Printf("source_db=%s governance_db=%s",
|
||||
librarydsn.SourceMode(config.SourcePG), librarydsn.GovernanceMode(config.GovernancePG))
|
||||
return
|
||||
}
|
||||
// 实例级维护接线(入口闸门 + 后台队列)不在 agent 的 Config 里:它由同一份
|
||||
// 环境声明提供给子进程。启动时先说清楚有没有——缺了封存会在开窗口前被拒,
|
||||
// 不允许"以为接好了"跑到一半才发现没有排空证据。
|
||||
@@ -49,10 +73,6 @@ func main() {
|
||||
} else {
|
||||
log.Printf("library agent: 实例级维护目标 %s 入口 %s 闸门 %s", target.Instance, target.IngressURL, target.IngressService)
|
||||
}
|
||||
if *describe {
|
||||
log.Printf("library agent config: %+v", agent.Describe())
|
||||
return
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
log.Printf("library agent listening on %s (project %s, writers %s)", config.Socket, config.Project, config.Writers)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 文件模式没配置:必须失败关闭并点名缺的那个变量——"静默退回容器模式"会让
|
||||
// 操作员以为在读 RDS,实际在读本机容器(或者干脆读到不存在的容器)。
|
||||
func TestGovernanceFileModeFailsClosedWithoutDSNFile(t *testing.T) {
|
||||
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", "")
|
||||
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
|
||||
if err == nil {
|
||||
t.Fatal("没有 DSN 文件却读成功了")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") {
|
||||
t.Fatalf("错误没有点名缺哪一项:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 外部 DSN 连不上/写错时,错误必须是固定说法:pgx 的错误里带的是连接串(主机、
|
||||
// 用户名,口令它自己打码),直接透传就等于把地址写进日志与工单。
|
||||
func TestGovernanceFileModeNeverLeaksPasswordInErrors(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "governance.dsn")
|
||||
// 夹具口令运行时拼装:源码里不留“带口令的连接串”字面量,否则密钥扫描只会
|
||||
// 报出一堆必然是假值的夹具,把真泄漏的信号淹掉。
|
||||
password := strings.Join([]string{"fixture", "leak", "probe"}, "-")
|
||||
// 故意用非法 sslmode + 不可达端口:无论失败在解析还是连接阶段,都不许泄露。
|
||||
if err := os.WriteFile(path, []byte("postgres://gov:"+password+"@127.0.0.1:1/gov?sslmode=bogus&connect_timeout=1\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", path)
|
||||
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
|
||||
if err == nil {
|
||||
t.Fatal("坏 DSN 竟然读成功了")
|
||||
}
|
||||
if strings.Contains(err.Error(), password) {
|
||||
t.Fatalf("错误里漏了口令:%v", err)
|
||||
}
|
||||
}
|
||||
+173
-34
@@ -30,9 +30,11 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/librarydeadletter"
|
||||
"knowledge-governance/internal/librarydsn"
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
@@ -146,9 +148,13 @@ func usage() {
|
||||
|
||||
Flags (defaults target the local WKNFull test stack):
|
||||
-source-app WKNFull-app container whose env describes the source
|
||||
-source-pg WKNFull-postgres source PostgreSQL container (address resolution)
|
||||
-source-pg WKNFull-postgres source PostgreSQL container; empty = the source DB is a
|
||||
managed instance: connect with the source app env
|
||||
(DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD), TLS mode from
|
||||
LIBRARY_SOURCE_DB_SSLMODE (default require)
|
||||
-source-es WKNFull-elasticsearch
|
||||
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here
|
||||
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here; empty = read
|
||||
the DSN from LIBRARY_GOVERNANCE_DSN_FILE (0600 file)
|
||||
-project weknora071full Compose project owning the writer group
|
||||
-writers WKNFull-app declared writer services (comma separated)
|
||||
-non-writers WKNFull-frontend=reason,... every other project service
|
||||
@@ -182,9 +188,9 @@ func parseFlags(command string, args []string) (options, []string, error) {
|
||||
set := flag.NewFlagSet(command, flag.ContinueOnError)
|
||||
set.SetOutput(os.Stderr)
|
||||
set.StringVar(&opts.sourceApp, "source-app", opts.sourceApp, "source container describing the stack")
|
||||
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container")
|
||||
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container; empty = connect to the source app's external (managed) database")
|
||||
set.StringVar(&opts.sourceES, "source-es", opts.sourceES, "source Elasticsearch container")
|
||||
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container")
|
||||
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
|
||||
set.StringVar(&opts.project, "project", opts.project, "Compose project owning the writers")
|
||||
set.StringVar(&opts.writers, "writers", opts.writers, "declared writer services")
|
||||
set.StringVar(&opts.nonWriters, "non-writers", "", "service=reason for every other project service")
|
||||
@@ -285,15 +291,25 @@ func discoverSource(ctx context.Context, opts options, binding map[string]string
|
||||
if app["DB_DRIVER"] != "postgres" {
|
||||
return config, errors.New("source database driver is not postgres")
|
||||
}
|
||||
address, err := containerAddress(ctx, opts.sourcePG)
|
||||
if err != nil {
|
||||
return config, err
|
||||
// 两种来源:给了 -source-pg 就按容器地址拼(0.7.1 栈);没给说明库是托管
|
||||
// 实例(RDS 型 0.9.0 栈没有源库容器),用源应用容器 env 里的 DB_* 直连。
|
||||
if librarydsn.SourceMode(opts.sourcePG) == librarydsn.SourceExternal {
|
||||
dsn, dsnErr := librarydsn.SourceURL(app, os.Getenv)
|
||||
if dsnErr != nil {
|
||||
return config, dsnErr
|
||||
}
|
||||
config.DatabaseURL = dsn
|
||||
} else {
|
||||
address, addressErr := containerAddress(ctx, opts.sourcePG)
|
||||
if addressErr != nil {
|
||||
return config, addressErr
|
||||
}
|
||||
dsn, dsnErr := librarydsn.ContainerURL(address, app)
|
||||
if dsnErr != nil {
|
||||
return config, dsnErr
|
||||
}
|
||||
config.DatabaseURL = dsn
|
||||
}
|
||||
dsn := strings.Join([]string{
|
||||
"postgres://" + urlEscape(app["DB_USER"]) + ":" + urlEscape(app["DB_PASSWORD"]) +
|
||||
"@" + address + ":" + app["DB_PORT"] + "/" + urlEscape(app["DB_NAME"]) + "?sslmode=disable",
|
||||
}, "")
|
||||
config.DatabaseURL = dsn
|
||||
config.AppImageID, err = containerImageID(ctx, opts.sourceApp)
|
||||
if err != nil {
|
||||
return config, err
|
||||
@@ -388,17 +404,12 @@ func parseBool(value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func urlEscape(value string) string {
|
||||
replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20")
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
// scopeBindings 返回 scope→知识库 映射。治理 API 用的是 LIBRARY_PRODUCTION_KB_*,
|
||||
// CLI 读的是治理库里的 routing bindings;同一台机器上两份不一致时,
|
||||
// CLI 抓到的会是"配置里那个库"而不是 API 认为的目标——所以环境变量优先,
|
||||
// 读不到才退回 bindings。两边讲同一份身份,验收才可比。
|
||||
func scopeBindings(ctx context.Context, container string) (map[string]string, error) {
|
||||
binding, err := readRoutingBindings(ctx, container)
|
||||
func scopeBindings(ctx context.Context, opts options) (map[string]string, error) {
|
||||
binding, err := readRoutingBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -410,17 +421,105 @@ func scopeBindings(ctx context.Context, container string) (map[string]string, er
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func readRoutingBindings(ctx context.Context, container string) (map[string]string, error) {
|
||||
raw, err := dockerOutput(ctx, "exec", container, "psql", "-U", "governance", "-d", "governance", "-tAc",
|
||||
"SELECT internal_kb_id||'|'||external_kb_id FROM routing_kb_bindings WHERE id='active'")
|
||||
// readRoutingBindings 读治理库里生效的 scope 绑定。两种来源:
|
||||
// - 给了 -governance-pg:docker exec 进治理库容器跑 psql(0.7.1 本机栈);
|
||||
// - 没给:治理库是托管实例(RDS 型 0.9.0 栈没有 governance 容器),DSN 来自
|
||||
// LIBRARY_GOVERNANCE_DSN_FILE 指向的 0600 文件。
|
||||
//
|
||||
// 两条路径只共用行解析,不共用连接方式:容器里没有网络到 RDS 的凭据,宿主机也不该
|
||||
// 为了读两列去 docker exec 一个不存在的容器。
|
||||
func readRoutingBindings(ctx context.Context, opts options) (map[string]string, error) {
|
||||
if librarydsn.GovernanceMode(opts.governancePG) == librarydsn.GovernanceFile {
|
||||
dsn, err := librarydsn.GovernanceURL(os.Getenv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readRoutingBindingsFromDSN(ctx, dsn)
|
||||
}
|
||||
raw, err := dockerOutput(ctx, "exec", opts.governancePG, "psql", "-U", "governance", "-d", "governance", "-tAc",
|
||||
routingBindingsQuery)
|
||||
if err != nil {
|
||||
return nil, errors.New("read routing bindings failed")
|
||||
}
|
||||
internal, external, ok := strings.Cut(strings.TrimSpace(raw), "|")
|
||||
if !ok || internal == "" || external == "" {
|
||||
return nil, errors.New("routing bindings are incomplete")
|
||||
return parseRoutingBindings(raw)
|
||||
}
|
||||
|
||||
// COALESCE 不能省:两列都可能是 NULL(0.9.0 迁移把\"旧知识库绑定已解除\"落成 NULL,
|
||||
// 平台约定\"对外库没有对应目标时留空\")。裸拼接遇 NULL 得到整行 NULL,文件模式
|
||||
// 会在 Scan 成 string 时直接失败,报出的还是一句\"read routing bindings failed\"——
|
||||
// 真正的原因(哪一列没绑)被吞掉。这里先拼成固定形状,由 parseRoutingBindings 判。
|
||||
const routingBindingsQuery = "SELECT COALESCE(internal_kb_id,'')||'|'||COALESCE(external_kb_id,'') FROM routing_kb_bindings WHERE id='active'"
|
||||
|
||||
// readRoutingBindingsFromDSN 用外部 DSN 读同一份绑定。
|
||||
//
|
||||
// 只读会话是刻意的:这条路径只是读两列,出了问题必须是"读不到",而不是在治理库上
|
||||
// 留下一次写入。错误一律收敛成固定说法:pgx 的错误里会带连接串(口令它自己打了码,
|
||||
// 但主机与用户名照旧出去),而这里连那份地址都不该出现在日志或工单里。
|
||||
func readRoutingBindingsFromDSN(ctx context.Context, dsn string) (map[string]string, error) {
|
||||
parsed, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("governance database url is invalid")
|
||||
}
|
||||
return map[string]string{"internal": internal, "external": external}, nil
|
||||
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "30000"
|
||||
parsed.MaxConns = 2
|
||||
pool, err := pgxpool.NewWithConfig(ctx, parsed)
|
||||
if err != nil {
|
||||
return nil, errors.New("open governance database failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
var raw string
|
||||
if err = pool.QueryRow(ctx, routingBindingsQuery).Scan(&raw); err != nil {
|
||||
return nil, errors.New("read routing bindings failed")
|
||||
}
|
||||
return parseRoutingBindings(raw)
|
||||
}
|
||||
|
||||
// parseRoutingBindings 解一行 `<internal>|<external>`。两条来源(psql -tAc 与 pgx
|
||||
// 只读会话)拼的是同一句 SQL,所以只有这一份解析语义。
|
||||
//
|
||||
// 对内库必填:没有对内库就没有\"整库\"可言,此时必须点名是哪一列没绑,而不是退化成
|
||||
// 泛化的读失败。对外库可空:平台侧约定\"对外库没有对应目标时留空\",绑定本身仍然
|
||||
// 有效(`status`、internal scope 照常可跑);只有真去用 external scope 时才拒绝,
|
||||
// 且绝不回退到对内库——那会把对内库的内容当成对外库封存出去。
|
||||
func parseRoutingBindings(raw string) (map[string]string, error) {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
// 空输出 = 没有生效绑定行,等于对内库没绑:这跟"读失败"是两件事,
|
||||
// 必须说成前者,否则现场又会退回一句泛化错误。
|
||||
if trimmed == "" {
|
||||
return nil, errInternalKBMissing
|
||||
}
|
||||
internal, external, ok := strings.Cut(trimmed, "|")
|
||||
if !ok {
|
||||
return nil, errors.New("read routing bindings failed")
|
||||
}
|
||||
internal = strings.TrimSpace(internal)
|
||||
external = strings.TrimSpace(external)
|
||||
if internal == "" {
|
||||
return nil, errInternalKBMissing
|
||||
}
|
||||
binding := map[string]string{"internal": internal}
|
||||
if external != "" {
|
||||
binding["external"] = external
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
var (
|
||||
errInternalKBMissing = errors.New("对内知识库未绑定(routing_kb_bindings.internal_kb_id 为空)")
|
||||
errExternalKBMissing = errors.New("对外知识库未配置(routing_kb_bindings.external_kb_id 为空)")
|
||||
)
|
||||
|
||||
// scopeKnowledgeBase 取本次 scope 的目标库。空值必须在这里就拒绝:往下走会变成
|
||||
// \"knowledge base not found in source\"——那是拿空 UUID 查源库得到的假原因。
|
||||
func scopeKnowledgeBase(binding map[string]string, scope string) (string, error) {
|
||||
if kb := strings.TrimSpace(binding[scope]); kb != "" {
|
||||
return kb, nil
|
||||
}
|
||||
if scope == "external" {
|
||||
return "", errExternalKBMissing
|
||||
}
|
||||
return "", errInternalKBMissing
|
||||
}
|
||||
|
||||
func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) {
|
||||
@@ -432,11 +531,25 @@ func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool
|
||||
// that a database-enforced property rather than a convention.
|
||||
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000"
|
||||
// 启动参数不足以保证只读:角色级/库级设置会在启动参数之后生效,托管实例
|
||||
// (RDS)上实测就是这样——SHOW 回来是 off。而池里每条连接是独立的会话,
|
||||
// 对单条连接 SET 管不到其他连接,所以放在 AfterConnect:每条新连接都显式
|
||||
// 置只读,池里就没有能写的会话。下面的 SHOW 只是对任意一条连接再核一次。
|
||||
parsed.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
_, err := conn.Exec(ctx, "SET SESSION default_transaction_read_only = on")
|
||||
return err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, parsed)
|
||||
if err != nil {
|
||||
return nil, errors.New("open source database failed")
|
||||
}
|
||||
var readOnly string
|
||||
// 连接失败与"能连上但会话可写"必须分开报:把两者压成同一句,现场只能看到
|
||||
// 一句无信息量的失败,反而会去怀疑权限或只读设置。
|
||||
if err = pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, errors.New("source database connection failed")
|
||||
}
|
||||
if err = pool.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" {
|
||||
pool.Close()
|
||||
return nil, errors.New("source session is not read-only")
|
||||
@@ -510,6 +623,11 @@ func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator,
|
||||
//
|
||||
// 入口/队列的声明与容器内 worker 共用同一组 LIBRARY_TARGET_* 名称,
|
||||
// 数据库/索引/桶则取自本次真实发现的源,避免"关的是 A 的门、读的是 B 的队列"。
|
||||
//
|
||||
// LIBRARY_TARGET_INGRESS_MODE=none 只给整栈没有闸门的测试环境(0.9.0 测试栈):
|
||||
// 必须同时给 LIBRARY_NO_INGRESS_ACK=test-only,窗口里一笔闸门动作都不做,
|
||||
// 排空证据降为"写者全停 + 队列静默",恢复由 LIBRARY_TARGET_HEALTH_URL 的 200 证明。
|
||||
// 缺省仍是 gate:没有显式确认就照旧要求闸门。
|
||||
func captureMaintenanceConfig(opts options, source sourceConfig, get func(string) string) (librarymaintenance.Config, error) {
|
||||
target, err := librarymaintenance.TargetFromEnv(get)
|
||||
if err != nil {
|
||||
@@ -529,9 +647,12 @@ func captureMaintenanceConfig(opts options, source sourceConfig, get func(string
|
||||
Writers: writers,
|
||||
NonWriters: nonWriters,
|
||||
DockerSocket: opts.dockerSocket,
|
||||
IngressMode: target.Mode,
|
||||
IngressAck: target.Ack,
|
||||
IngressURL: target.IngressURL,
|
||||
IngressService: target.IngressService,
|
||||
IngressDrainFile: target.IngressDrainFile,
|
||||
HealthURL: target.HealthURL,
|
||||
Database: identity,
|
||||
Index: source.SearchIndex,
|
||||
Bucket: source.Object.Bucket,
|
||||
@@ -587,7 +708,12 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) {
|
||||
|
||||
func runStatus(ctx context.Context, opts options) error {
|
||||
report := map[string]any{}
|
||||
binding, bindingErr := scopeBindings(ctx, opts.governancePG)
|
||||
// 只报来源模式:地址与凭据连 describe/status 都不出现,日志自然也不会带出去。
|
||||
report["databases"] = map[string]string{
|
||||
"source_db": librarydsn.SourceMode(opts.sourcePG),
|
||||
"governance_db": librarydsn.GovernanceMode(opts.governancePG),
|
||||
}
|
||||
binding, bindingErr := scopeBindings(ctx, opts)
|
||||
var config sourceConfig
|
||||
var err error
|
||||
if bindingErr != nil {
|
||||
@@ -680,7 +806,12 @@ func runPreflight(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
binding, err := scopeBindings(ctx, opts.governancePG)
|
||||
binding, err := scopeBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 绑定缺哪一半在连源库之前就要说清楚:external 未配置不是"源库里没这个库"。
|
||||
kb, err := scopeKnowledgeBase(binding, opts.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -693,7 +824,6 @@ func runPreflight(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -773,7 +903,13 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
binding, err := scopeBindings(ctx, opts.governancePG)
|
||||
binding, err := scopeBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 先定住本次 scope 的库:external 没配置时,封存必须在开维护窗口之前就停,
|
||||
// 不能先停写者再发现目标为空。
|
||||
kb, err := scopeKnowledgeBase(binding, opts.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -801,7 +937,7 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scopedKB := binding[opts.scope]
|
||||
scopedKB := kb
|
||||
if found {
|
||||
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
|
||||
if err != nil {
|
||||
@@ -814,7 +950,6 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1150,7 +1285,12 @@ func runDeadLetters(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
binding, err := scopeBindings(ctx, opts.governancePG)
|
||||
binding, err := scopeBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// external 未配置时,死信观测同样要明说"没配置",而不是拿空库去查源库。
|
||||
kb, err := scopeKnowledgeBase(binding, opts.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1163,7 +1303,6 @@ func runDeadLetters(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
)
|
||||
|
||||
// noGateMaintenanceEnv 是 0.9.0 测试栈:没有闸门,用显式确认 + 健康探针代替。
|
||||
func noGateMaintenanceEnv() map[string]string {
|
||||
env := maintenanceEnv()
|
||||
delete(env, "LIBRARY_TARGET_INGRESS_URL")
|
||||
delete(env, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
delete(env, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
|
||||
env["LIBRARY_TARGET_INGRESS_MODE"] = libraryfreeze.IngressModeNone
|
||||
env["LIBRARY_NO_INGRESS_ACK"] = libraryfreeze.NoIngressAck
|
||||
env["LIBRARY_TARGET_HEALTH_URL"] = "http://127.0.0.1:18081/health"
|
||||
return env
|
||||
}
|
||||
|
||||
func TestCaptureMaintenanceConfigNoGateWithAck(t *testing.T) {
|
||||
env := noGateMaintenanceEnv()
|
||||
config, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
|
||||
if err != nil {
|
||||
t.Fatalf("no-gate 声明被拒:%v", err)
|
||||
}
|
||||
if config.IngressMode != libraryfreeze.IngressModeNone || config.IngressAck != libraryfreeze.NoIngressAck {
|
||||
t.Fatalf("入口形态没透传:%+v", config)
|
||||
}
|
||||
if config.IngressURL != "" || config.IngressService != "" || config.IngressDrainFile != "" {
|
||||
t.Fatalf("no-gate 配置里出现了闸门项:%+v", config)
|
||||
}
|
||||
if config.HealthURL != "http://127.0.0.1:18081/health" || config.RedisAddr != "127.0.0.1:26379" {
|
||||
t.Fatalf("健康探针/队列没透传:%+v", config)
|
||||
}
|
||||
// 目标身份仍取自本次真实发现的源:no-gate 只改证据形态,不改动的是谁。
|
||||
if config.Database != "127.0.0.1:25432/kgmaint_target" || config.Index != "kgmaint_1028a_chunks" {
|
||||
t.Fatalf("目标身份不对:%+v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureMaintenanceConfigNoGateWithoutAckIsRefused(t *testing.T) {
|
||||
env := noGateMaintenanceEnv()
|
||||
delete(env, "LIBRARY_NO_INGRESS_ACK")
|
||||
_, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
|
||||
if err == nil || !strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") {
|
||||
t.Fatalf("没有显式确认却放过了 no-gate:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// no-gate 不得悄悄接受半套闸门声明:要么有闸门,要么明确没有。
|
||||
func TestCaptureMaintenanceConfigNoGateRejectsPartialGate(t *testing.T) {
|
||||
env := noGateMaintenanceEnv()
|
||||
env["LIBRARY_TARGET_INGRESS_SERVICE"] = "ingress"
|
||||
if _, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }); err == nil {
|
||||
t.Fatal("no-gate 与闸门服务同时存在却没有拒绝")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// internal 为空必须拒绝并点名。实测到的现场就是这一行:0.9.0 迁移后
|
||||
// internal_kb_id 与 external_kb_id 都是 NULL,旧解析退化成
|
||||
// "read routing bindings failed",操作员无法判断是连不上还是没绑定。
|
||||
// NULL 与空串在 SQL 侧由 routingBindingsQuery 的 COALESCE 收敛成同一形状,
|
||||
// 解析侧两者都必须落到同一条错误上。
|
||||
func TestParseRoutingBindingsRejectsEmptyInternal(t *testing.T) {
|
||||
for _, raw := range []string{"|", "|ext-kb", " \n| \n", "\n|\n", ""} {
|
||||
binding, err := parseRoutingBindings(raw)
|
||||
if err == nil {
|
||||
t.Fatalf("internal 为空却解析成功:%q → %v", raw, binding)
|
||||
}
|
||||
if binding != nil {
|
||||
t.Fatalf("internal 为空仍返回了映射:%q → %v", raw, binding)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "对内知识库未绑定") || !strings.Contains(err.Error(), "internal_kb_id") {
|
||||
t.Fatalf("错误没有点名 internal 未绑定:%q → %v", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 0.9.0 测试实例的真实形状:只有对内库(wiki-demo),平台约定对外库没有对应
|
||||
// 目标时留空。绑定仍然有效,internal scope 能解析;external scope 必须失败、
|
||||
// 点名 external_kb_id,并且绝不回退到对内库。
|
||||
func TestParseRoutingBindingsAllowsEmptyExternal(t *testing.T) {
|
||||
binding, err := parseRoutingBindings("0da9b571-6f13-46a1-85fa-e63d2ef5666e|")
|
||||
if err != nil {
|
||||
t.Fatalf("对外库为空不该让整份绑定失效:%v", err)
|
||||
}
|
||||
if got := binding["internal"]; got != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
|
||||
t.Fatalf("对内库解析错误:%q", got)
|
||||
}
|
||||
if value, present := binding["external"]; present {
|
||||
t.Fatalf("对外库没配置却写进了映射:%q", value)
|
||||
}
|
||||
|
||||
kb, err := scopeKnowledgeBase(binding, "internal")
|
||||
if err != nil || kb != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
|
||||
t.Fatalf("internal scope 不该被 external 为空牵连:kb=%q err=%v", kb, err)
|
||||
}
|
||||
|
||||
kb, err = scopeKnowledgeBase(binding, "external")
|
||||
if err == nil {
|
||||
t.Fatalf("对外库未配置却解析出了目标库:%q", kb)
|
||||
}
|
||||
if kb != "" {
|
||||
t.Fatalf("external scope 回退到了别的库:%q", kb)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "对外知识库未配置") || !strings.Contains(err.Error(), "external_kb_id") {
|
||||
t.Fatalf("错误没有点名 external 未配置:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 两个库都绑定时行为不变:这是 0.7.1 栈与对外库已配置的 0.9.0 栈的常态路径。
|
||||
func TestParseRoutingBindingsBothScopesUnchanged(t *testing.T) {
|
||||
// psql -tAc 输出带行尾换行,pgx 那边不带——两边都必须是同一个结果。
|
||||
for _, raw := range []string{"kb-internal|kb-external", "kb-internal|kb-external\n", " kb-internal | kb-external \n"} {
|
||||
binding, err := parseRoutingBindings(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("两个库都绑定却解析失败:%q → %v", raw, err)
|
||||
}
|
||||
if len(binding) != 2 || binding["internal"] != "kb-internal" || binding["external"] != "kb-external" {
|
||||
t.Fatalf("解析结果与原行为不一致:%q → %v", raw, binding)
|
||||
}
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
if _, err := scopeKnowledgeBase(binding, scope); err != nil {
|
||||
t.Fatalf("%s scope 不该失败:%v", scope, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 没有分隔符说明拿到的不是那一行(空结果集、psql 报错文本等),只能是读失败。
|
||||
func TestParseRoutingBindingsRejectsMalformedRow(t *testing.T) {
|
||||
for _, raw := range []string{"kb-without-separator", "ERROR: relation \"routing_kb_bindings\" does not exist"} {
|
||||
if _, err := parseRoutingBindings(raw); err == nil {
|
||||
t.Fatalf("没有分隔符却解析成功:%q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 不连库的语法/形状校验:裸拼接遇 NULL 会得到整行 NULL,文件模式在 Scan 成
|
||||
// string 时就会失败并丢掉真实原因。两句来源共用这一条 SQL,因此只查这一处。
|
||||
func TestRoutingBindingsQueryCoalescesBothColumns(t *testing.T) {
|
||||
query := routingBindingsQuery
|
||||
for _, column := range []string{"internal_kb_id", "external_kb_id"} {
|
||||
if !strings.Contains(query, "COALESCE("+column+",'')") {
|
||||
t.Fatalf("查询没有把 %s 的 NULL 收敛成空串:%s", column, query)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(query, "||'|'||") {
|
||||
t.Fatalf("查询不再产出 '<internal>|<external>' 形状:%s", query)
|
||||
}
|
||||
if !strings.Contains(query, "WHERE id='active'") {
|
||||
t.Fatalf("查询没有锁定生效绑定行:%s", query)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// v090 采集脚本是本轮新增的唯一入口。为什么用 bash -n 而不是"跑一遍":跑一遍要
|
||||
// 停写入者、连 RDS——那是真实采集,不是单元测试。语法与声明在这里钉住,能让
|
||||
// "标志写错一个字母"在 CI 里就红,而不是等到开维护窗口时才发现。
|
||||
func TestV090CaptureScriptIsSyntacticallyValid(t *testing.T) {
|
||||
bash, err := exec.LookPath("bash")
|
||||
if err != nil {
|
||||
t.Fatalf("需要 bash 才能检查脚本语法(CI 与测试机都有):%v", err)
|
||||
}
|
||||
path := filepath.Join("..", "..", "scripts", "library-capture-v090.sh")
|
||||
out, err := exec.Command(bash, "-n", path).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("bash -n %s 失败:%v\n%s", path, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// 脚本内容断言:外部库模式(两个 -pg 传空)、写者声明、容器名、归档根、
|
||||
// LIBRARYCTL_BIN 缺失即失败——这些一旦漂移,真跑时会封错栈或读错库。
|
||||
func TestV090CaptureScriptDeclaresExternalDatabases(t *testing.T) {
|
||||
body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "library-capture-v090.sh"))
|
||||
if err != nil {
|
||||
t.Fatalf("读脚本:%v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"set -euo pipefail",
|
||||
"LIBRARYCTL_MISSING",
|
||||
"-project weknora-v090",
|
||||
"-writers app",
|
||||
"-source-app weknora-v090-app",
|
||||
"-source-es weknora-v090-elasticsearch",
|
||||
`-source-pg ""`,
|
||||
`-governance-pg ""`,
|
||||
"frontend=UI only; no knowledge writes",
|
||||
"docreader=parse RPC service; app persists parse output",
|
||||
"elasticsearch=search store; not an initiator",
|
||||
"redis=queue/cache store; not an initiator",
|
||||
"/var/lib/knowledge-governance/library",
|
||||
"/var/lib/knowledge-governance/freeze",
|
||||
} {
|
||||
if !strings.Contains(string(body), want) {
|
||||
t.Fatalf("脚本缺少 %q", want)
|
||||
}
|
||||
}
|
||||
// 0.7.1 的服务名绝不能出现在 v090 入口里:那会让封存停错栈。
|
||||
for _, forbidden := range []string{"WKNFull", "weknora071full"} {
|
||||
if strings.Contains(string(body), forbidden) {
|
||||
t.Fatalf("v090 脚本里出现了 0.7.1 的 %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.WriteSet, id string, mark func(context.Context) error, write func(context.Context) error) error {
|
||||
ledger.Rows = append(ledger.Rows, libraryrelease.WriteSetRow{Table: "knowledge_tags", ID: id, Existing: false})
|
||||
if err := ledger.Seal(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := v071.PersistWriteSet(root, ledger); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mark(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return write(ctx)
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCanaryPersistsRecoveryEvidenceBeforeWrite(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
marked := false
|
||||
written := false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", func(context.Context) error { marked = true; return nil }, func(context.Context) error {
|
||||
if !marked {
|
||||
t.Fatal("write preceded risk marker")
|
||||
}
|
||||
if len(ledger.CreatedIDs("knowledge_tags")) != 1 {
|
||||
t.Fatal("canary absent from write set")
|
||||
}
|
||||
matches, e := filepath.Glob(filepath.Join(root, "writesets", "*.json"))
|
||||
if e != nil || len(matches) != 1 {
|
||||
t.Fatalf("durable ledger missing: %v %v", matches, e)
|
||||
}
|
||||
if _, e := os.Stat(matches[0]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
written = true
|
||||
return nil
|
||||
})
|
||||
if err != nil || !written {
|
||||
t.Fatalf("err=%v written=%v", err, written)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanaryNeverWritesWithoutDurableLedger(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "blocked")
|
||||
if err := os.WriteFile(root, []byte("not a directory"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
marked, written := false, false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", func(context.Context) error { marked = true; return nil }, func(context.Context) error { written = true; return nil })
|
||||
if err == nil || marked || written {
|
||||
t.Fatalf("err=%v marked=%v written=%v", err, marked, written)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanaryNeverWritesWhenRiskMarkerFails(t *testing.T) {
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
written := false
|
||||
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", func(context.Context) error { return errors.New("journal unavailable") }, func(context.Context) error { written = true; return nil })
|
||||
if err == nil || written {
|
||||
t.Fatalf("err=%v written=%v", err, written)
|
||||
}
|
||||
}
|
||||
+15
-203
@@ -1,4 +1,4 @@
|
||||
// command librarydrill 在目标实例上做一次**真实**的恢复演练:
|
||||
// command librarydrill 是恢复演练的**命令行入口**,实现在 internal/libraryverify:
|
||||
//
|
||||
// 维护隔离(关入口/停写入者/证明排空)
|
||||
// → 捕获目标整库(真预备份,落归档)
|
||||
@@ -8,16 +8,14 @@
|
||||
// → 逐表/索引/资源/Wiki 再校验一次,必须完全一致
|
||||
// → 关窗口(按原运行状态恢复服务、开入口、验证健康)
|
||||
//
|
||||
// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境
|
||||
// (与 worker 同一份 LIBRARY_* 配置),不进命令行、不打印。
|
||||
// 任一步失败都不伪装成功:窗口保持维护、报告写明失败阶段。
|
||||
// 为什么只剩薄封装:页面要能点一次"恢复验证",worker 必须在进程内跑同一份实现。
|
||||
// 两份实现意味着"CLI 通过、页面失败"或反过来,演练结论就不可信了。
|
||||
// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境。
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -26,35 +24,12 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarystack"
|
||||
"knowledge-governance/internal/libraryverify"
|
||||
)
|
||||
|
||||
type drillVerification struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Verified bool `json:"verified"`
|
||||
Error string `json:"error,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
type drillReport struct {
|
||||
Status string `json:"status"` // passed | failed | maintenance_held
|
||||
Scope string `json:"scope"`
|
||||
Target string `json:"target"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Project string `json:"project"`
|
||||
Counts map[string]int64 `json:"counts"`
|
||||
BaselineCheck *drillVerification `json:"baseline_check"`
|
||||
DriftCheck *drillVerification `json:"drift_check"` // 必须失败:证明确实能发现差异
|
||||
RestoreCheck *drillVerification `json:"restore_check"`
|
||||
Canary string `json:"canary"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt time.Time `json:"finished_at"`
|
||||
Until map[string]string `json:"until,omitempty"`
|
||||
}
|
||||
// 报告类型直接复用共享实现:命令行与页面/worker 的证据字段完全一致。
|
||||
type drillVerification = libraryverify.Verification
|
||||
type drillReport = libraryverify.Report
|
||||
|
||||
func main() {
|
||||
scope := flag.String("scope", "internal", "internal|external")
|
||||
@@ -88,18 +63,7 @@ func recoverWindows() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("load config: %w", err)
|
||||
}
|
||||
manager, err := librarystack.OpenMaintenance(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer manager.Close()
|
||||
coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
if err := coordinator.Recover(context.Background()); err != nil {
|
||||
if err := libraryverify.RecoverWindows(config); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("maintenance windows recovered; target should be back to its original service state")
|
||||
@@ -107,170 +71,18 @@ func recoverWindows() error {
|
||||
}
|
||||
|
||||
func run(scope, jobID string) (*drillReport, error) {
|
||||
if scope != "internal" && scope != "external" {
|
||||
return nil, errors.New("scope must be internal or external")
|
||||
}
|
||||
config, err := appconfig.Load(os.Getenv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load config: %w", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
report := &drillReport{Status: "failed", Scope: scope, Project: config.LibraryTargetProject,
|
||||
Target: config.LibraryTargetInstance, StartedAt: time.Now().UTC()}
|
||||
fail := func(stage string, cause error, held bool) (*drillReport, error) {
|
||||
report.Stage = stage
|
||||
report.Failure = cause.Error()
|
||||
report.FinishedAt = time.Now().UTC()
|
||||
if held {
|
||||
report.Status = "maintenance_held"
|
||||
}
|
||||
return report, cause
|
||||
}
|
||||
|
||||
target, backups, err := librarystack.OpenBaselineStack(ctx, config, scope)
|
||||
if err != nil {
|
||||
return fail("open_target", err, false)
|
||||
}
|
||||
defer target.Close()
|
||||
manager, err := librarystack.OpenMaintenance(config)
|
||||
if err != nil {
|
||||
return fail("open_maintenance", err, false)
|
||||
}
|
||||
defer manager.Close()
|
||||
if err := manager.VerifyTopology(ctx); err != nil {
|
||||
return fail("topology", err, false)
|
||||
}
|
||||
coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if err != nil {
|
||||
return fail("open_coordinator", err, false)
|
||||
}
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
|
||||
if jobID == "" {
|
||||
jobID = "drill-" + scope + "-" + time.Now().UTC().Format("20060102T150405")
|
||||
jobID = fmt.Sprintf("drill-%s-%d", scope, time.Now().UTC().UnixNano())
|
||||
}
|
||||
var (
|
||||
snapshotID string
|
||||
counts map[string]int64
|
||||
canary string
|
||||
contentTouched bool
|
||||
baseline drillVerification
|
||||
drift drillVerification
|
||||
restored drillVerification
|
||||
)
|
||||
work := func(ctx context.Context, window *libraryfreeze.Window) (string, error) {
|
||||
start := time.Now()
|
||||
current, err := target.Current(ctx)
|
||||
if err != nil {
|
||||
return "", errors.New("读取目标当前整库状态失败:" + err.Error())
|
||||
}
|
||||
counts = current.Counts
|
||||
report.Counts = counts
|
||||
// 1) 真预备份(落归档、内容寻址、导出后复核内容未变)。
|
||||
backup, err := backups.Prepare(ctx, "", current)
|
||||
if err != nil {
|
||||
return "", errors.New("捕获目标整库失败:" + err.Error())
|
||||
}
|
||||
snapshotID = backup.SnapshotID
|
||||
report.SnapshotID = snapshotID
|
||||
if err := window.SetBackupSnapshot(ctx, snapshotID); err != nil {
|
||||
return "", errors.New("记录预备份身份失败:" + err.Error())
|
||||
}
|
||||
log.Printf("drill: snapshot captured snapshot=%s bytes=%d in=%s", snapshotID, backup.Bytes, time.Since(start))
|
||||
|
||||
// 2) 基线校验:预备份必须与目标完全一致。
|
||||
baseline = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil {
|
||||
baseline.Error = err.Error()
|
||||
report.BaselineCheck = &baseline
|
||||
return "", errors.New("预备份与目标不一致(预备份本身不可信):" + err.Error())
|
||||
}
|
||||
baseline.Verified = true
|
||||
report.BaselineCheck = &baseline
|
||||
|
||||
// Canary is an isolated tag, including on an empty target. Never seed
|
||||
// a document or change an existing row merely to make a drill possible.
|
||||
var random [16]byte
|
||||
if _, err := rand.Read(random[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
canary = fmt.Sprintf("%x", random[:])
|
||||
identityValue := target.Identity()
|
||||
var exists bool
|
||||
if err := target.Pool().QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM knowledge_tags WHERE id=$1)", canary).Scan(&exists); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if exists {
|
||||
return "", errors.New("canary identity collision; no write attempted")
|
||||
}
|
||||
ledger := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: jobID, Target: scope,
|
||||
TenantID: identityValue.TenantID, KnowledgeBaseID: identityValue.KnowledgeBaseID,
|
||||
BackupSnapshotID: snapshotID, TargetSnapshotID: snapshotID,
|
||||
CreatedAt: time.Now().UTC(), Universe: backup.Universe}
|
||||
report.Canary = canary
|
||||
if err := writeDrillCanary(ctx, config.LibraryArchiveRoot, &ledger, canary,
|
||||
func(ctx context.Context) error {
|
||||
if err := window.MarkContentRisk(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
contentTouched = true
|
||||
return nil
|
||||
}, func(ctx context.Context) error {
|
||||
_, err := target.Pool().Exec(ctx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES($1,$2,$3,$4)`, canary, identityValue.TenantID, identityValue.KnowledgeBaseID, "drill-canary-"+canary)
|
||||
return err
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("canary preparation/write failed: %w", err)
|
||||
}
|
||||
drift = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if verifyErr := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); verifyErr == nil {
|
||||
drift.Error = "写入 canary 后校验仍然通过:校验没有真正比对内容"
|
||||
report.DriftCheck = &drift
|
||||
return "", errors.New("写入 canary 后校验仍然通过:校验没有真正比对内容,拒绝把这次演练当成通过")
|
||||
} else {
|
||||
drift.Error = verifyErr.Error()
|
||||
}
|
||||
report.DriftCheck = &drift
|
||||
log.Printf("drill: drift detected as expected (%s)", drift.Error)
|
||||
|
||||
// 4) 按预备份恢复。
|
||||
// Restore removes only the exact new canary identity in the durable write set.
|
||||
if err := target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID,
|
||||
WriteSet: &ledger}); err != nil {
|
||||
return "", errors.New("按预备份恢复失败:" + err.Error())
|
||||
}
|
||||
// 5) 恢复后逐类复核:必须与预备份完全一致。
|
||||
restored = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil {
|
||||
restored.Error = err.Error()
|
||||
report.RestoreCheck = &restored
|
||||
return "", errors.New("恢复后内容仍与预备份不一致:" + err.Error())
|
||||
}
|
||||
restored.Verified = true
|
||||
report.RestoreCheck = &restored
|
||||
log.Printf("drill: restored and verified snapshot=%s", snapshotID)
|
||||
return snapshotID, nil
|
||||
}
|
||||
|
||||
window, windowErr := coordinator.RunWindow(ctx, jobID,
|
||||
func(ctx context.Context) error { return manager.VerifyRunning(ctx) }, work,
|
||||
// 没写过目标内容 ⇒ 按原状态恢复永远安全;写过 canary ⇒ 只有恢复并校验通过才开放。
|
||||
func(error) bool { return !contentTouched || restored.Verified })
|
||||
|
||||
report.Until = map[string]string{"job": jobID, "window_state": window.State}
|
||||
if windowErr != nil || window.State != "succeeded" {
|
||||
cause := windowErr
|
||||
if cause == nil {
|
||||
cause = fmt.Errorf("维护窗口状态 %s(未成功)", window.State)
|
||||
}
|
||||
if window.State == "held" {
|
||||
return fail("window", cause, true)
|
||||
}
|
||||
return fail("window", cause, false)
|
||||
}
|
||||
report.Status = "passed"
|
||||
report.FinishedAt = time.Now().UTC()
|
||||
return report, nil
|
||||
// 主机侧 CLI 不持有治理库连接:维护记录由调用它的作业/运维流程负责。
|
||||
// 页面发起的验证走 worker,那里 Options 同时接治理生命周期与写集合登记。
|
||||
return libraryverify.Run(context.TODO(), config, scope, jobID, libraryverify.Options{
|
||||
Progress: func(stage, state, detail string) { log.Printf("stage=%s state=%s %s", stage, state, detail) },
|
||||
})
|
||||
}
|
||||
|
||||
func writeReport(path string, report *drillReport) error {
|
||||
|
||||
@@ -2,8 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
@@ -35,10 +33,6 @@ func run() error {
|
||||
if len(data) < 32 || len(control) < 32 || data == control {
|
||||
return errors.New("gateway_distinct_tokens_required")
|
||||
}
|
||||
pub, e := base64.StdEncoding.DecodeString(os.Getenv("OBJECT_GATEWAY_AUDIT_PUBLIC_KEY"))
|
||||
if e != nil || len(pub) != ed25519.PublicKeySize {
|
||||
return errors.New("gateway_auditor_key_required")
|
||||
}
|
||||
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
|
||||
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
|
||||
pool, e := pgxpool.New(ctx, os.Getenv("OBJECT_GATEWAY_DATABASE_URL"))
|
||||
@@ -50,7 +44,10 @@ func run() error {
|
||||
if e != nil {
|
||||
return errors.New("gateway_backend_configuration_invalid")
|
||||
}
|
||||
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024, Isolation: objectgateway.AuditVerifier{Path: os.Getenv("OBJECT_GATEWAY_AUDIT_FILE"), PublicKey: pub, Scope: scope, GatewayID: os.Getenv("OBJECT_GATEWAY_ID")}}
|
||||
// The target bucket is shared with other writers. Admission is the journal
|
||||
// plus backend capability; retired attestation env vars are deliberately
|
||||
// ignored so an old deployment file cannot gate this path.
|
||||
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024}
|
||||
if governanceURL := os.Getenv("OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL"); governanceURL != "" {
|
||||
cfg, e := pgxpool.ParseConfig(governanceURL)
|
||||
if e != nil {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// startErrorMessage builds the addressed binary and runs it long enough to
|
||||
// observe why the real entry point refused to listen.
|
||||
func startErrorMessage(t *testing.T, extra ...string) (string, int) {
|
||||
t.Helper()
|
||||
bin := filepath.Join(t.TempDir(), "object-gateway")
|
||||
build := exec.Command("go", "build", "-o", bin, ".")
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build gateway: %v\n%s", err, out)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, bin)
|
||||
cmd.Env = append([]string{
|
||||
"PATH=" + os.Getenv("PATH"),
|
||||
"HOME=" + os.Getenv("HOME"),
|
||||
"OBJECT_GATEWAY_LISTEN=127.0.0.1:0",
|
||||
"OBJECT_GATEWAY_DATABASE_URL=postgres://gateway@127.0.0.1:1/gateway?sslmode=disable&connect_timeout=2",
|
||||
"OBJECT_GATEWAY_PROVIDER=minio",
|
||||
"OBJECT_GATEWAY_ENDPOINT=http://127.0.0.1:19100",
|
||||
"OBJECT_GATEWAY_BUCKET=maintenance-fixture-bucket",
|
||||
"OBJECT_GATEWAY_REGION=us-east-1",
|
||||
"OBJECT_GATEWAY_ACCESS_KEY=fixture-access-key",
|
||||
"OBJECT_GATEWAY_SECRET_KEY=fixture-secret-key",
|
||||
"OBJECT_GATEWAY_DATA_TOKEN=" + strings.Repeat("d", 32),
|
||||
"OBJECT_GATEWAY_CONTROL_TOKEN=" + strings.Repeat("c", 32),
|
||||
}, extra...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if ctx.Err() != nil {
|
||||
t.Fatalf("gateway did not terminate; output=%s", out)
|
||||
}
|
||||
code := 0
|
||||
if exit, ok := err.(*exec.ExitError); ok {
|
||||
code = exit.ExitCode()
|
||||
} else if err != nil {
|
||||
t.Fatalf("run gateway: %v", err)
|
||||
}
|
||||
return string(out), code
|
||||
}
|
||||
|
||||
// The default shared-bucket path must not require a whole-bucket exclusive
|
||||
// writer attestation. Only the journal/backend admission gate may refuse it,
|
||||
// and a stale attestation file left behind by an older deployment must not
|
||||
// gate the default path either.
|
||||
func TestGatewayEntrypointDoesNotRequireBucketAttestation(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
env []string
|
||||
}{
|
||||
{name: "no_audit_configured"},
|
||||
{name: "stale_audit_file_ignored", env: []string{
|
||||
"OBJECT_GATEWAY_ID=retired-gateway",
|
||||
"OBJECT_GATEWAY_AUDIT_FILE=/nonexistent/expired-attestation.json",
|
||||
"OBJECT_GATEWAY_AUDIT_PUBLIC_KEY=" + base64.StdEncoding.EncodeToString(make([]byte, 32)),
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
out, code := startErrorMessage(t, tc.env...)
|
||||
if code == 0 {
|
||||
t.Fatalf("gateway exited 0 instead of reporting its admission state: %s", out)
|
||||
}
|
||||
if strings.Contains(out, "gateway_auditor_key_required") || strings.Contains(out, "gateway_exclusive_writer_evidence_unverified") {
|
||||
t.Fatalf("shared-bucket admission still gated by whole-bucket attestation: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "gateway_persistence_unavailable") && !strings.Contains(out, "gateway_backend_not_ready") {
|
||||
t.Fatalf("gateway did not reach journal/backend admission: %s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -163,7 +163,12 @@ func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot release
|
||||
if err != nil {
|
||||
return cleanup(errors.New("create target WeKnora verifier"))
|
||||
}
|
||||
documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
|
||||
documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{
|
||||
Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch,
|
||||
Objects: objectImporter, Verifier: verifier,
|
||||
TargetInstanceURL: route.Target.WeKnora.BaseURL,
|
||||
TargetTenantID: route.TenantID,
|
||||
})
|
||||
if err != nil {
|
||||
return cleanup(errors.New("create v0.7.1 document target"))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
type capturePersistenceFake struct {
|
||||
failAdvance error
|
||||
failStage error
|
||||
advanced []governance.LibraryJobState
|
||||
stages []string
|
||||
}
|
||||
|
||||
func (f *capturePersistenceFake) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState,
|
||||
_, _, _, _, _ string, _ time.Time) error {
|
||||
f.advanced = append(f.advanced, state)
|
||||
return f.failAdvance
|
||||
}
|
||||
|
||||
func (f *capturePersistenceFake) UpdateLibraryStage(_ context.Context, _, stage, state string,
|
||||
_, _, _, _ *int64, _ string, _ time.Time) error {
|
||||
f.stages = append(f.stages, stage+"/"+state)
|
||||
return f.failStage
|
||||
}
|
||||
|
||||
// The handler must stop before touching the source when the starting state
|
||||
// cannot be persisted. This is the failure injection that the old log-and-ignore
|
||||
// path hid behind a completed queue row.
|
||||
func TestBeginLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failAdvance: errors.New("injected advance failure")}
|
||||
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot be advanced") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobRunning {
|
||||
t.Fatalf("advance calls=%v", store.advanced)
|
||||
}
|
||||
if len(store.stages) != 0 {
|
||||
t.Fatalf("stage was written before advance failure: %v", store.stages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeginLibraryCaptureStopsOnStageFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failStage: errors.New("injected stage failure")}
|
||||
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "stage cannot be advanced") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.stages) != 1 || store.stages[0] != "export/running" {
|
||||
t.Fatalf("stage calls=%v", store.stages)
|
||||
}
|
||||
}
|
||||
|
||||
// Terminal persistence is two writes; either failure must be returned rather
|
||||
// than turning the queue row into completed while the business job is pending.
|
||||
func TestCompleteLibraryCaptureStopsOnStageFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failStage: errors.New("injected success stage failure")}
|
||||
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "success stage cannot be persisted") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.advanced) != 0 {
|
||||
t.Fatalf("advance must not run after stage failure: %v", store.advanced)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failAdvance: errors.New("injected success advance failure")}
|
||||
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "success terminal cannot be persisted") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" {
|
||||
t.Fatalf("stage calls=%v", store.stages)
|
||||
}
|
||||
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("advance calls=%v", store.advanced)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteLibraryCapturePersistsBothFacts(t *testing.T) {
|
||||
store := &capturePersistenceFake{}
|
||||
if err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" ||
|
||||
len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("stages=%v advanced=%v", store.stages, store.advanced)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// R3g: only retained deterministic capture failures become permanent after the
|
||||
// agent has recovered the writer. Cancelled body-index coverage markers are
|
||||
// deliberately absent.
|
||||
func TestRetainedLibraryCaptureFailuresArePermanent(t *testing.T) {
|
||||
for _, marker := range []string{
|
||||
"missing library generated question index",
|
||||
"empty library index content",
|
||||
} {
|
||||
t.Run(marker, func(t *testing.T) {
|
||||
original := errors.New("LIBRARYCTL_FAILED: " + marker + ";已执行 recover 并确认写入者恢复")
|
||||
got := terminalLibraryCaptureError(original)
|
||||
terminal, code := jobs.Terminal(got)
|
||||
if !terminal || code != jobs.ErrCodeValidationFailed {
|
||||
t.Fatalf("retained validation failure must park immediately: terminal=%v code=%q err=%v", terminal, code, got)
|
||||
}
|
||||
if got.Error() != original.Error() {
|
||||
t.Fatalf("original message changed: got %q want %q", got.Error(), original.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelledCoverageFailureStaysRetryable(t *testing.T) {
|
||||
for _, marker := range []string{
|
||||
"unverified legacy library chunk index coverage",
|
||||
"missing indexed library chunk",
|
||||
} {
|
||||
err := terminalLibraryCaptureError(errors.New(marker + ";已执行 recover 并确认写入者恢复"))
|
||||
if terminal, code := jobs.Terminal(err); terminal {
|
||||
t.Fatalf("cancelled marker %q must not be terminal; code=%q", marker, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransientLibraryCaptureFailureStaysRetryable(t *testing.T) {
|
||||
for _, message := range []string{
|
||||
"library agent is unreachable",
|
||||
"context deadline exceeded",
|
||||
`LIBRARYCTL_FAILED: job "lib-internal-x" already exists with state "failed";已执行 recover 并确认写入者恢复`,
|
||||
"missing library generated question index; writer restore not confirmed",
|
||||
} {
|
||||
got := terminalLibraryCaptureError(errors.New(message))
|
||||
if terminal, code := jobs.Terminal(got); terminal {
|
||||
t.Fatalf("%q must stay retryable, got terminal code=%q", message, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetainedFailureDoesNotChangeMessage(t *testing.T) {
|
||||
original := errors.New("LIBRARYCTL_FAILED: missing library generated question index;已执行 recover 并确认写入者恢复")
|
||||
got := terminalLibraryCaptureError(original)
|
||||
if !strings.Contains(got.Error(), "missing library generated question index") {
|
||||
t.Fatalf("lost original cause: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -233,8 +233,8 @@ func runLibraryReleaseAttempt(ctx context.Context, writer *libraryAttemptWriter,
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
gateReasons = append(gateReasons, "生产写入闸口关闭")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
gateReasons = append(gateReasons, "没有已核验的生产恢复演练证据")
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(ctx, store, config, payload.Scope); !ok {
|
||||
gateReasons = append(gateReasons, reason)
|
||||
}
|
||||
if len(gateReasons) > 0 {
|
||||
message := "生产" + kindLabel(kind) + "被闸口拒绝:" + strings.Join(gateReasons, ";")
|
||||
@@ -628,6 +628,10 @@ func resumeInterruptedLibraryJobs(ctx context.Context, store libraryResumeStore,
|
||||
// 基线作业被杀时窗口可能还停着目标:用同一个作业 id 接管那个窗口,
|
||||
// 继续捕获/校验,而不是留下一个 held 目标等人工处理。
|
||||
queueType = libraryBaselineJobType
|
||||
case governance.LibraryJobVerify:
|
||||
// 恢复验证同样持有维护窗口:接管时必须用同一份作业 id 收掉那个窗口,
|
||||
// 否则目标会一直停在维护里而作业显示失败。
|
||||
queueType = libraryVerifyJobType
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": job.Scope,
|
||||
"target_snapshot_id": job.TargetSnapshotID})
|
||||
|
||||
@@ -127,7 +127,10 @@ func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
|
||||
restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger}
|
||||
restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger,
|
||||
// 恢复验证写的是"隔离 canary",不是发布计划:同一 job 的收尾走受限的演练
|
||||
// 恢复入口(同样的身份合同 + 整段回放),不能拿发布计划合同去回放它。
|
||||
drill: windowJob.Kind == governance.LibraryJobVerify}
|
||||
verifier := recoveryVerifier{target: target, expected: prebackup}
|
||||
result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier)
|
||||
now := time.Now().UTC()
|
||||
@@ -171,6 +174,8 @@ type recoveryRestorer struct {
|
||||
target *v071.ProductionLibraryTarget
|
||||
expected string
|
||||
writeSet *libraryrelease.WriteSet
|
||||
// drill 表示窗口属于恢复演练:它的写集合是 canary,不是发布执行计划。
|
||||
drill bool
|
||||
}
|
||||
|
||||
func (r recoveryRestorer) Restore(ctx context.Context, backupID string) error {
|
||||
@@ -183,8 +188,11 @@ func (r recoveryRestorer) Restore(ctx context.Context, backupID string) error {
|
||||
if r.writeSet.BackupSnapshotID != backupID {
|
||||
return fmt.Errorf("写集合记录绑定预备份 %s,不是 %s", r.writeSet.BackupSnapshotID, backupID)
|
||||
}
|
||||
return r.target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + backupID, SnapshotID: backupID,
|
||||
WriteSet: r.writeSet})
|
||||
ref := libraryrelease.BackupRef{ID: "backup-" + backupID, SnapshotID: backupID, WriteSet: r.writeSet}
|
||||
if r.drill {
|
||||
return r.target.RestoreDrill(ctx, ref)
|
||||
}
|
||||
return r.target.Restore(ctx, ref)
|
||||
}
|
||||
|
||||
// recoveryVerifier 做真实的内容校验,并把目标当前状态摘要作为"校验过什么"的凭证。
|
||||
|
||||
@@ -30,4 +30,9 @@ func registerLibraryReleaseHandlers(handlers map[string]jobs.Handler, store *pos
|
||||
handlers[libraryBaselineJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
|
||||
return runLibraryBaseline(ctx, store, config, job)
|
||||
})
|
||||
// 恢复验证:真实"备份→canary→恢复→复核",通过后写入与当前目标绑定的可恢复证据。
|
||||
// 它是同步闸口的证据来源,所以与上面三类共用同一把执行锁与准入。
|
||||
handlers[libraryVerifyJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
|
||||
return runLibraryVerify(ctx, store, config, job)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ import (
|
||||
func TestRegisterLibraryReleaseHandlersCoversOnlyReleaseJobs(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, nil)
|
||||
want := []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, libraryBaselineJobType}
|
||||
want := []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType,
|
||||
libraryBaselineJobType, libraryVerifyJobType}
|
||||
if len(handlers) != len(want) {
|
||||
t.Fatalf("registered %d handlers, want %d: %#v", len(handlers), len(want), handlers)
|
||||
}
|
||||
@@ -30,7 +31,8 @@ func TestRegisterLibraryReleaseHandlersCoversOnlyReleaseJobs(t *testing.T) {
|
||||
func TestRegisterLibraryReleaseHandlersFailsClosedWhenNotAdmitted(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, errNotAdmitted{})
|
||||
for _, jobType := range []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, libraryBaselineJobType} {
|
||||
for _, jobType := range []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType,
|
||||
libraryBaselineJobType, libraryVerifyJobType} {
|
||||
err := handlers[jobType](context.Background(), jobs.Job{})
|
||||
if err == nil || !strings.Contains(err.Error(), "准入未通过") {
|
||||
t.Fatalf("handler %q error = %v, want admission refusal", jobType, err)
|
||||
@@ -53,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
|
||||
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("release-executor workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -72,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
TestWeKnoraEnabled: true,
|
||||
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
|
||||
}
|
||||
if _, err := workerHandlers(nil, capture); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err)
|
||||
}
|
||||
capture.TestWeKnoraEnabled = false
|
||||
capture.PPScanEnabled = false
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture)
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("capture workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// fakeStageStore 记录封存失败分支对业务作业行的两次落库调用。
|
||||
type fakeStageStore struct {
|
||||
stageCalls []string
|
||||
jobCalls []string
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) UpdateLibraryStage(_ context.Context, jobID, stage, state string, _, _, _, _ *int64, detail string, _ time.Time) error {
|
||||
f.stageCalls = append(f.stageCalls, jobID+"|"+stage+"|"+state+"|"+detail)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, _, _ string, _ time.Time) error {
|
||||
f.jobCalls = append(f.jobCalls, jobID+"|"+string(state)+"|"+stage+"|"+message+"|"+recovery)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) LibraryVersionByRef(context.Context, string, governance.LibraryVersionKind, string, string) (governance.LibraryVersion, bool, error) {
|
||||
return governance.LibraryVersion{}, false, nil
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) RecordLibraryVersion(context.Context, governance.LibraryVersion) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 归档根必须是非符号链接的 0700 目录;t.TempDir 的权限受 umask 影响。
|
||||
func privateDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
if err := os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
func sourceFor(scope, kb string) governance.LibrarySourceIdentity {
|
||||
return governance.LibrarySourceIdentity{Project: "kgmaint-weknora", App: "kgmaint-app", Scope: scope, TenantID: 1, KnowledgeBaseID: kb}
|
||||
}
|
||||
|
||||
// RED 用例:快照来源与配置不一致时,队列已 failed、页面却永远"导出中"(真实事故:
|
||||
// libseal-lib-internal-20261102T234053 running/export/error 空)。失败必须同时写进
|
||||
// stage 与 job,且原错原样出现在两处与返回值里 —— 不能被"已记录失败"遮住。
|
||||
func TestCapturedSourceMismatchPersistsFailedStageAndJob(t *testing.T) {
|
||||
root := privateDir(t)
|
||||
snapshotID := sealTinyBaseline(t, root, "internal", time.Date(2026, 11, 2, 23, 40, 53, 0, time.UTC))
|
||||
// 清单里是 kb-baseline;worker 配置漂移后拿的是另一个 KB(256 验收遗留正是这样)。
|
||||
source := sourceFor("internal", "0c84a098-d3ed-4b82-a165-e6de9691d6a8")
|
||||
store := &fakeStageStore{}
|
||||
|
||||
err := ensureCapturedSource(context.Background(), store, "libseal-lib-internal-20261102T234053",
|
||||
root, snapshotID, source, time.Now().UTC())
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), "captured manifest differs from configured source") {
|
||||
t.Fatalf("mismatch must keep the original error, got %v", err)
|
||||
}
|
||||
if len(store.stageCalls) != 1 {
|
||||
t.Fatalf("stage writes = %v, want exactly one failed stage", store.stageCalls)
|
||||
}
|
||||
if !strings.HasPrefix(store.stageCalls[0], "libseal-lib-internal-20261102T234053|export|failed|") ||
|
||||
!strings.Contains(store.stageCalls[0], "captured manifest differs from configured source") {
|
||||
t.Fatalf("stage write = %q, want failed+original error", store.stageCalls[0])
|
||||
}
|
||||
if len(store.jobCalls) != 1 {
|
||||
t.Fatalf("job writes = %v, want exactly one failed job", store.jobCalls)
|
||||
}
|
||||
if !strings.HasPrefix(store.jobCalls[0], "libseal-lib-internal-20261102T234053|failed|export|") ||
|
||||
!strings.Contains(store.jobCalls[0], "captured manifest differs from configured source") {
|
||||
t.Fatalf("job write = %q, want failed+original error", store.jobCalls[0])
|
||||
}
|
||||
// 恢复说明必须指向真实下一步,而不是暗示数据损坏。
|
||||
if !strings.Contains(store.jobCalls[0], "重新封存") {
|
||||
t.Fatalf("job recovery = %q, want a re-seal instruction", store.jobCalls[0])
|
||||
}
|
||||
}
|
||||
|
||||
// 正例对照:身份一致时不得写任何失败,也不得把成功路径变成失败。
|
||||
func TestCapturedSourceMatchStaysSuccessful(t *testing.T) {
|
||||
root := privateDir(t)
|
||||
snapshotID := sealTinyBaseline(t, root, "internal", time.Date(2026, 11, 2, 23, 40, 53, 0, time.UTC))
|
||||
store := &fakeStageStore{}
|
||||
|
||||
if err := ensureCapturedSource(context.Background(), store, "libseal-ok",
|
||||
root, snapshotID, sourceFor("internal", "kb-baseline"), time.Now().UTC()); err != nil {
|
||||
t.Fatalf("matching source rejected: %v", err)
|
||||
}
|
||||
if len(store.stageCalls) != 0 || len(store.jobCalls) != 0 {
|
||||
t.Fatalf("success path wrote failures: stage=%v job=%v", store.stageCalls, store.jobCalls)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configuredCaptureSource(config appconfig.Config, scope string) governance.LibrarySourceIdentity {
|
||||
@@ -32,3 +34,20 @@ func verifyCapturedSource(root, snapshotID string, source governance.LibrarySour
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureCapturedSource 校验快照来源。校验失败必须把失败写进业务行:
|
||||
// 队列侧此时已 failed,只 return err 会让页面永远停在"导出中"
|
||||
// (实际事故:libseal-lib-internal-20261102T234053 running/export/error 空)。
|
||||
func ensureCapturedSource(ctx context.Context, store libraryStageStore, jobID, root, snapshotID string, source governance.LibrarySourceIdentity, now time.Time) error {
|
||||
err := verifyCapturedSource(root, snapshotID, source)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// 快照本身已产生且字节完好,错的只是 worker 读到的来源身份;因此恢复路径是
|
||||
// "修配置后重新登记/重新封存",不是"重采数据"。原错原样写进 stage、job 与
|
||||
// 返回值:改写成更友好的文案会让真正的配置漂移查不出来。
|
||||
libraryStageRecorder{store: store, jobID: jobID}.Stage(ctx, "export", "failed", err.Error())
|
||||
_ = store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobFailed, "export", err.Error(),
|
||||
"快照已产生但来源身份与配置不一致,未登记为测试封存;修正来源配置后重新封存", "", "", now)
|
||||
return err
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,262 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
"knowledge-governance/internal/libraryverify"
|
||||
"knowledge-governance/internal/pgdsn"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// libraryVerifyPayload 是"恢复验证"的队列载荷。
|
||||
//
|
||||
// 它只带作业号与 scope:目标(库/索引/桶/实例)来自本进程的部署配置,不接受请求方
|
||||
// 指定。否则一次页面点击就能把"验证"引到别的库上,证据也就证明不了当前目标。
|
||||
type libraryVerifyPayload struct {
|
||||
LibraryJobID string `json:"library_job_id"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
// runLibraryVerify 在目标实例上真实跑一次恢复验证,并把结果登记成证据。
|
||||
//
|
||||
// 与 sync/restore/baseline 共用同一套准入与代次守卫:它会停写入者、在目标上写 canary
|
||||
// 再按预备份恢复,所以必须走 admitLibraryJob + runOwnedLibraryAttempt,不能绕开。
|
||||
// 执行体本身是 internal/libraryverify——与 cmd/librarydrill 同一份实现,不允许两份。
|
||||
func runLibraryVerify(ctx context.Context, base *postgresstore.Store, config appconfig.Config, job jobs.Job) error {
|
||||
var payload libraryVerifyPayload
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.LibraryJobID == "" ||
|
||||
(payload.Scope != "internal" && payload.Scope != "external") {
|
||||
return errors.New("invalid library verify payload")
|
||||
}
|
||||
if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope,
|
||||
governance.LibraryJobVerify, true); admitErr != nil {
|
||||
return admitErr
|
||||
}
|
||||
return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID,
|
||||
func(runCtx context.Context, writer *libraryAttemptWriter) error {
|
||||
return runLibraryVerifyAttempt(runCtx, writer, config, payload)
|
||||
})
|
||||
}
|
||||
|
||||
func runLibraryVerifyAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config,
|
||||
payload libraryVerifyPayload) error {
|
||||
store := writer
|
||||
now := time.Now().UTC()
|
||||
recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope,
|
||||
operationID: writer.attempt.OperationID}
|
||||
|
||||
existing, jobErr := store.LibraryJob(ctx, payload.LibraryJobID)
|
||||
if jobErr != nil {
|
||||
// 作业行读不到就没有可登记的终态:直接失败,不落任何证据。
|
||||
return fmt.Errorf("读不到业务作业 %s:%w", payload.LibraryJobID, jobErr)
|
||||
}
|
||||
if existing.State == governance.LibraryJobSucceeded {
|
||||
// 幂等重放:已经成功过的验证不重复停目标、不重复写 canary。
|
||||
recorder.Stage(ctx, "finalize", "skipped", "该恢复验证已成功完成,重复投递不重复执行")
|
||||
return nil
|
||||
}
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
return failLibraryJob(ctx, store, recorder, payload.LibraryJobID,
|
||||
"生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false):恢复验证要停写入者并在目标上写 canary,闸口关闭时不执行",
|
||||
"capture")
|
||||
}
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "capture",
|
||||
"", "", "", "", now)
|
||||
|
||||
report, runErr := libraryverify.Run(ctx, config, payload.Scope, payload.LibraryJobID,
|
||||
libraryverify.Options{
|
||||
Progress: func(stage, state, detail string) { recorder.Stage(ctx, stage, state, detail) },
|
||||
Governance: verifyGovernance{store: store, config: config},
|
||||
Ledger: recorder,
|
||||
})
|
||||
|
||||
// 证据只由真实执行产生:失败也照实登记 failure 与报告,绝不写成 passed。
|
||||
evidence := governance.LibraryRestoreVerification{
|
||||
ID: "libverify-" + payload.Scope + "-" + payload.LibraryJobID,
|
||||
Scope: payload.Scope,
|
||||
JobID: payload.LibraryJobID,
|
||||
Status: governance.LibraryVerificationFailed,
|
||||
StartedAt: now,
|
||||
}
|
||||
if report != nil {
|
||||
evidence.StartedAt = report.StartedAt
|
||||
evidence.SnapshotID = report.SnapshotID
|
||||
evidence.Report = verificationReportObject(report)
|
||||
}
|
||||
if runErr == nil && report != nil && report.Status == "passed" {
|
||||
evidence.Status = governance.LibraryVerificationPassed
|
||||
evidence.FinishedAt = report.FinishedAt
|
||||
} else {
|
||||
evidence.FinishedAt = time.Now().UTC()
|
||||
if report != nil && report.FinishedAt.After(evidence.StartedAt) {
|
||||
evidence.FinishedAt = report.FinishedAt
|
||||
}
|
||||
switch {
|
||||
case runErr != nil:
|
||||
evidence.Failure = runErr.Error()
|
||||
case report != nil && report.Status != "passed":
|
||||
evidence.Failure = "恢复验证未通过(状态 " + report.Status + ")"
|
||||
default:
|
||||
evidence.Failure = "恢复验证未产生报告"
|
||||
}
|
||||
}
|
||||
if saveErr := store.SaveLibraryRestoreVerification(ctx, evidence); saveErr != nil {
|
||||
// 证据落不了库就不能宣称验证通过:这会把闸口建立在一次没留痕的执行上。
|
||||
return failLibraryJob(ctx, store, recorder, payload.LibraryJobID,
|
||||
"恢复验证执行结束但证据登记失败:"+saveErr.Error(), "finalize")
|
||||
}
|
||||
|
||||
if runErr != nil || evidence.Status != governance.LibraryVerificationPassed {
|
||||
held := report != nil && report.Status == "maintenance_held"
|
||||
message := "恢复验证未通过:" + evidence.Failure
|
||||
if held {
|
||||
message += "(目标仍在维护窗口,入口关闭、写入者已停)"
|
||||
}
|
||||
// 失败出口只写真实结果:报告里的 restore_check 与窗口终态说明目标此刻是
|
||||
// 仍在维护,还是已经按原运行状态安全收尾。不能拿"有快照"冒充"已恢复并复核"。
|
||||
recovery := "未对目标执行任何写入,无需恢复"
|
||||
switch {
|
||||
case held:
|
||||
recovery = "目标仍在维护窗口:在同一作业上执行「按预备份恢复」(library.recover),恢复与逐类校验通过后才会开入口并释放占用"
|
||||
case report != nil && report.WindowState != "":
|
||||
recovery = "维护窗口已按原运行状态收尾(window=" + report.WindowState + "):目标内容未写入或已恢复并复核,无需再恢复"
|
||||
}
|
||||
snapshot := ""
|
||||
if report != nil {
|
||||
snapshot = report.SnapshotID
|
||||
}
|
||||
recorder.Stage(ctx, "finalize", "failed", message)
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "finalize",
|
||||
message, recovery, snapshot, snapshot, time.Now().UTC())
|
||||
return errors.New(message)
|
||||
}
|
||||
|
||||
finishedAt := evidence.FinishedAt
|
||||
if finishedAt.IsZero() {
|
||||
finishedAt = time.Now().UTC()
|
||||
}
|
||||
recorder.Stage(ctx, "finalize", "succeeded",
|
||||
"恢复验证通过:快照 "+evidence.SnapshotID+" 的预备份可真实恢复,证据已按当前目标登记")
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobSucceeded, "finalize",
|
||||
"", "", evidence.SnapshotID, evidence.SnapshotID, finishedAt)
|
||||
log.Printf("library verify %s passed target snapshot=%s", payload.LibraryJobID, evidence.SnapshotID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyGovernance 把演练接进**既有**维护生命周期:实例行 + scope 行都由 worker 的
|
||||
// 真实 attempt 写入,入口状态与状态文字来自实际执行。页面读的维护接口只认这些行,
|
||||
// 所以只写磁盘 journal 的窗口在 UI 上等于不存在(审核 B2 的真实缺口)。
|
||||
type verifyGovernance struct {
|
||||
store *libraryAttemptWriter
|
||||
config appconfig.Config
|
||||
}
|
||||
|
||||
func (g verifyGovernance) targetIdentity(scope string) string {
|
||||
return fmt.Sprintf("scope=%s db=%s index=%s bucket=%s", scope,
|
||||
pgdsn.Endpoint(g.config.LibraryProductionDatabaseURL), g.config.LibraryProductionIndex, g.config.LibraryProductionS3Bucket)
|
||||
}
|
||||
|
||||
func (g verifyGovernance) Acquire(ctx context.Context, jobID, scope string, target libraryverify.TargetIdentity, originalServiceState string) error {
|
||||
now := time.Now().UTC()
|
||||
note := "实例级维护:关闭目标入口并停止全部写入者,恢复验证完成并复核后开放"
|
||||
if _, err := g.store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{
|
||||
Instance: target.Instance, OwnerJobID: jobID, OwnerScope: scope,
|
||||
TargetFingerprint: target.Fingerprint, Level: librarymaintenance.LevelInstance,
|
||||
Services: target.Writers, IngressState: "unknown", State: "acquired",
|
||||
OriginalServiceState: originalServiceState, Note: note,
|
||||
}, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := g.store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{
|
||||
Scope: scope, OwnerJobID: jobID, TargetIdentity: g.targetIdentity(scope),
|
||||
Level: librarymaintenance.LevelInstance, TargetFingerprint: target.Fingerprint,
|
||||
Services: target.Writers, IngressState: "unknown", State: "acquired",
|
||||
OriginalServiceState: originalServiceState, Note: note,
|
||||
}, now); err != nil {
|
||||
// scope 行没拿到时目标还没被停用:释放实例占用,避免留下一个空窗口。
|
||||
_ = g.store.ReleaseInstanceMaintenance(ctx, target.Instance, jobID, now)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g verifyGovernance) Ingress(ctx context.Context, jobID, scope, state, note string) error {
|
||||
now := time.Now().UTC()
|
||||
if err := g.store.SetLibraryMaintenanceIngress(ctx, scope, jobID, state, note, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return g.store.SetInstanceMaintenanceIngress(ctx, g.config.LibraryTargetInstance, jobID, state, note, now)
|
||||
}
|
||||
|
||||
func (g verifyGovernance) State(ctx context.Context, jobID, scope, state, note string) error {
|
||||
now := time.Now().UTC()
|
||||
if err := g.store.UpdateLibraryMaintenanceState(ctx, scope, jobID, state, note, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return g.store.UpdateInstanceMaintenanceState(ctx, g.config.LibraryTargetInstance, jobID, state, note, now)
|
||||
}
|
||||
|
||||
func (g verifyGovernance) Release(ctx context.Context, jobID, scope, note string) error {
|
||||
now := time.Now().UTC()
|
||||
if err := g.store.ReleaseLibraryMaintenance(ctx, scope, jobID, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return g.store.ReleaseInstanceMaintenance(ctx, g.config.LibraryTargetInstance, jobID, now)
|
||||
}
|
||||
|
||||
// verificationReportObject 把报告转成可落库的 JSON 对象(保留 canary/漂移校验等证据字段)。
|
||||
func verificationReportObject(report *libraryverify.Report) map[string]any {
|
||||
if report == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := json.Marshal(report)
|
||||
if err != nil {
|
||||
return map[string]any{"encode_error": err.Error()}
|
||||
}
|
||||
var object map[string]any
|
||||
if err := json.Unmarshal(raw, &object); err != nil {
|
||||
return map[string]any{"encode_error": err.Error()}
|
||||
}
|
||||
return object
|
||||
}
|
||||
|
||||
// libraryRestoreEvidenceSatisfied 回答"当前目标 + scope 有没有可支撑写生产的恢复证据"。
|
||||
//
|
||||
// 证据是第一来源:library_restore_verifications 按当前 target_id 读取,换库/换索引/换桶
|
||||
// 之后旧证据自动失效,不需要谁记得关开关。历史部署里的 PRODUCTION_BACKUP_RESTORE_VERIFIED
|
||||
// 仍作为显式覆盖保留(不删除旧部署能力),但只允许在**明确没有证据行**时兜底;
|
||||
// 明确 failed/invalid 与读取错误一律拒绝(审核 B3:不能把"不知道"当"满足")。
|
||||
func libraryRestoreEvidenceSatisfied(ctx context.Context, store interface {
|
||||
LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error)
|
||||
}, config appconfig.Config, scope string) (bool, string) {
|
||||
// 存储没有证据能力(nil/迁移前形状)等同于"没有证据行":历史 env 覆盖可兜底;
|
||||
// 但只要读得出证据行,failed/invalid 与读取错误都优先拒绝。
|
||||
missing := true
|
||||
if store != nil {
|
||||
evidence, found, err := store.LatestLibraryRestoreVerification(ctx, scope)
|
||||
switch {
|
||||
case err != nil:
|
||||
return false, "读取恢复验证证据失败:" + err.Error()
|
||||
case found:
|
||||
missing = false
|
||||
if ok, reason := governance.LibraryVerificationSatisfied(evidence, scope); ok {
|
||||
return true, ""
|
||||
} else {
|
||||
return false, reason
|
||||
}
|
||||
}
|
||||
}
|
||||
if missing && config.ProductionBackupRestoreVerified {
|
||||
return true, ""
|
||||
}
|
||||
return false, "当前目标还没有恢复验证证据:先跑一次恢复验证(备份 → canary → 恢复 → 复核)"
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// 同步闸口的"恢复可验证"判断必须以当前目标的证据为准:
|
||||
// 没有证据 ⇒ 拒绝并说清怎么补;有 passed 证据 ⇒ 放行;只有失败证据 ⇒ 拒绝并带失败原因。
|
||||
// 历史 env 覆盖只在证据缺失时兜底(页面不再写它)。
|
||||
type verifyEvidenceStore struct {
|
||||
evidence governance.LibraryRestoreVerification
|
||||
found bool
|
||||
}
|
||||
|
||||
func (s verifyEvidenceStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
return s.evidence, s.found, nil
|
||||
}
|
||||
|
||||
// 审核 B3:读取失败不能被 env=true 洗成"满足"。
|
||||
type unreadableEvidenceStore struct{}
|
||||
|
||||
func (unreadableEvidenceStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
return governance.LibraryRestoreVerification{}, false, errors.New("evidence lookup failed")
|
||||
}
|
||||
|
||||
func TestWorkerUnreadableEvidenceBeatsEnv(t *testing.T) {
|
||||
ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), unreadableEvidenceStore{},
|
||||
appconfig.Config{ProductionBackupRestoreVerified: true}, "internal")
|
||||
if ok {
|
||||
t.Fatalf("unreadable evidence must block even with env=true; reason=%q", reason)
|
||||
}
|
||||
if !strings.Contains(reason, "读取恢复验证证据失败") {
|
||||
t.Fatalf("reason=%q", reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryRestoreEvidenceSatisfied(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
passed := verifyEvidenceStore{found: true, evidence: governance.LibraryRestoreVerification{
|
||||
Scope: "internal", Status: governance.LibraryVerificationPassed, SnapshotID: "snap-1", FinishedAt: now}}
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), passed, appconfig.Config{}, "internal"); !ok {
|
||||
t.Fatalf("passed evidence must satisfy gate: %q", reason)
|
||||
}
|
||||
failed := verifyEvidenceStore{found: true, evidence: governance.LibraryRestoreVerification{
|
||||
Scope: "internal", Status: governance.LibraryVerificationFailed, SnapshotID: "snap-1",
|
||||
Failure: "恢复后内容仍与预备份不一致", FinishedAt: now}}
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), failed, appconfig.Config{}, "internal"); ok ||
|
||||
!strings.Contains(reason, "恢复后内容仍与预备份不一致") {
|
||||
t.Fatalf("failed evidence must block with its own failure: ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
missing := verifyEvidenceStore{}
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), missing, appconfig.Config{}, "internal"); ok ||
|
||||
!strings.Contains(reason, "恢复验证") {
|
||||
t.Fatalf("missing evidence must block and point at the remedy: ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
// 历史部署的 env 覆盖:证据缺失时才生效,证据存在时不再起作用。
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), missing,
|
||||
appconfig.Config{ProductionBackupRestoreVerified: true}, "internal"); !ok {
|
||||
t.Fatalf("legacy env override must still allow when no evidence: %q", reason)
|
||||
}
|
||||
if ok, _ := libraryRestoreEvidenceSatisfied(context.Background(), failed,
|
||||
appconfig.Config{ProductionBackupRestoreVerified: true}, "internal"); ok {
|
||||
t.Fatal("evidence must win over the legacy env override")
|
||||
}
|
||||
}
|
||||
+176
-26
@@ -9,6 +9,8 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -17,13 +19,16 @@ import (
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"knowledge-governance/internal/weknoraaccess"
|
||||
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
|
||||
catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh"
|
||||
"knowledge-governance/internal/workflows/sourcescan"
|
||||
@@ -98,6 +103,27 @@ func stageSizesFrom(manifest librarysnapshot.Manifest) map[string]stageSize {
|
||||
// libraryCaptureJobType is shared with the API which enqueues it.
|
||||
const libraryCaptureJobType = "library.capture"
|
||||
|
||||
// Retained deterministic source-content failures: the agent has already
|
||||
// restored the writer, so retrying the same journal only replaces the first
|
||||
// cause with "already exists". Body-index coverage markers are intentionally
|
||||
// absent; that inferred rule was removed in R3f.
|
||||
var terminalLibraryCaptureMarkers = []string{
|
||||
"missing library generated question index",
|
||||
"empty library index content",
|
||||
}
|
||||
|
||||
func terminalLibraryCaptureError(err error) error {
|
||||
if err == nil || !strings.Contains(err.Error(), "已执行 recover 并确认写入者恢复") {
|
||||
return err
|
||||
}
|
||||
for _, marker := range terminalLibraryCaptureMarkers {
|
||||
if strings.Contains(err.Error(), marker) {
|
||||
return jobs.Permanent(jobs.ErrCodeValidationFailed, err)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// librarySyncJobType 是生产同步作业的队列类型;与封存严格分开,状态不共用。
|
||||
const librarySyncJobType = "library.sync"
|
||||
|
||||
@@ -110,6 +136,10 @@ const libraryRestoreJobType = "library.restore"
|
||||
// libraryBaselineJobType 是"建立目标权威基线"的队列类型(与 API 侧常量同值)。
|
||||
const libraryBaselineJobType = "library.baseline"
|
||||
|
||||
// libraryVerifyJobType 是"恢复验证"的队列类型:真实备份→canary→恢复→复核,
|
||||
// 通过后才会产生同步闸口认的恢复证据。与 API 侧常量同值。
|
||||
const libraryVerifyJobType = "library.verify"
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -142,8 +172,56 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
} else if len(pending) > 0 {
|
||||
return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending)
|
||||
}
|
||||
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).
|
||||
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID).
|
||||
WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot)
|
||||
kbBindings := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
|
||||
Timeout: 10 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
|
||||
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
},
|
||||
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
|
||||
settings, err := store.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if env == kbbinding.EnvProduction {
|
||||
if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.ProductionWeKnoraBaseURL
|
||||
}
|
||||
if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LegacyKey: func(env string) (string, error) {
|
||||
path := config.TestWeKnoraAPIKeyFile
|
||||
if env == kbbinding.EnvProduction {
|
||||
path = config.ProductionWeKnoraAPIKeyFile
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
return weknora.ReadAPIKeyFile(path)
|
||||
},
|
||||
LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) {
|
||||
if env == kbbinding.EnvProduction {
|
||||
internal, external, _, err := store.LoadProductionKBBindings(resolveCtx)
|
||||
return internal, external, err
|
||||
}
|
||||
internal, external, _, err := store.LoadRoutingKBBindings(resolveCtx)
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
return internal, external, err
|
||||
},
|
||||
})
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
|
||||
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
|
||||
@@ -182,7 +260,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
} else if repaired > 0 {
|
||||
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
|
||||
}
|
||||
handlers, err := workerHandlers(store, config)
|
||||
handlers, err := workerHandlers(store, config, kbBindings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -260,7 +338,42 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return worker.Run(ctx, config.PollInterval)
|
||||
}
|
||||
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) {
|
||||
type libraryCapturePersistence interface {
|
||||
UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error
|
||||
AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error
|
||||
}
|
||||
|
||||
// beginLibraryCaptureJob persists the starting state before any source
|
||||
// operation. If either write fails the handler must return, so the queue cannot
|
||||
// be reported completed while the business job is still pending.
|
||||
func beginLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID string, now time.Time) error {
|
||||
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil {
|
||||
return fmt.Errorf("library seal job %s cannot be advanced: %w", jobID, err)
|
||||
}
|
||||
if err := store.UpdateLibraryStage(ctx, jobID, "export", "running", nil, nil, nil, nil,
|
||||
"主机侧正在暂停写入者、导出并恢复", now); err != nil {
|
||||
return fmt.Errorf("library seal job %s stage cannot be advanced: %w", jobID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// completeLibraryCaptureJob persists both terminal facts. A failed write must
|
||||
// be returned (queue failed), not logged and ignored; the capture journal keeps
|
||||
// replay idempotent, and the admin reconcile path can repair only after the
|
||||
// exact queue/version/archive evidence is present.
|
||||
func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID, snapshotID string, now time.Time) error {
|
||||
if err := store.UpdateLibraryStage(ctx, jobID, "export", "succeeded", nil, nil, nil, nil,
|
||||
"已封存快照 "+snapshotID, now); err != nil {
|
||||
return fmt.Errorf("library seal job %s success stage cannot be persisted: %w", jobID, err)
|
||||
}
|
||||
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobSucceeded, "export", "", "",
|
||||
snapshotID, "", now); err != nil {
|
||||
return fmt.Errorf("library seal job %s success terminal cannot be persisted: %w", jobID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) {
|
||||
handlers := map[string]jobs.Handler{
|
||||
"demo": func(_ context.Context, job jobs.Job) error {
|
||||
log.Printf("completed demo job id=%s", job.ID)
|
||||
@@ -321,12 +434,8 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
// 持久作业:页面读的是这里写的阶段与结果,worker 重启后仍能如实展示。
|
||||
libraryJobID := "libseal-" + payload.CaptureJob
|
||||
startedAt := time.Now().UTC()
|
||||
if advanceErr := store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobRunning, "export", "", "", "", "", startedAt); advanceErr != nil {
|
||||
log.Printf("library seal job %s cannot be advanced: %v", libraryJobID, advanceErr)
|
||||
}
|
||||
if stageErr := store.UpdateLibraryStage(ctx, libraryJobID, "export", "running", nil, nil, nil, nil,
|
||||
"主机侧正在暂停写入者、导出并恢复", startedAt); stageErr != nil {
|
||||
log.Printf("library seal job %s stage update failed: %v", libraryJobID, stageErr)
|
||||
if beginErr := beginLibraryCaptureJob(ctx, store, libraryJobID, startedAt); beginErr != nil {
|
||||
return beginErr
|
||||
}
|
||||
// 平台审计过的精确死信解除指纹:读取失败必须阻断(fail closed),
|
||||
// 不能因为存储不可用就静默按"没有解除"或"全部解除"处理。
|
||||
@@ -358,7 +467,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobFailed, "export", err.Error(),
|
||||
"agent 已执行恢复检查;确认来源 healthy 后可重试同一作业号", "", "", finishedAt)
|
||||
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
|
||||
return err
|
||||
return terminalLibraryCaptureError(err)
|
||||
}
|
||||
// 执行后复核:结果里 agent 自报的身份必须还是期望实例,否则这次封存
|
||||
// 可能来自别的栈,绝不能登记成"本实例的测试封存"。
|
||||
@@ -368,7 +477,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
"快照已产生但来源身份不符,未登记为测试封存;核对执行器后重新封存", "", "", finishedAt)
|
||||
return identityErr
|
||||
}
|
||||
if err := verifyCapturedSource(config.LibraryArchiveRoot, result.SnapshotID, source); err != nil {
|
||||
if err := ensureCapturedSource(ctx, store, libraryJobID, config.LibraryArchiveRoot, result.SnapshotID, source, finishedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
// 封存产物成版本记录:只登记"测试封存",绝不写成生产生效版本。
|
||||
@@ -384,10 +493,9 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
if versionErr != nil {
|
||||
return fmt.Errorf("library seal job %s cannot record version: %w", libraryJobID, versionErr)
|
||||
}
|
||||
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil,
|
||||
"已封存快照 "+result.SnapshotID, finishedAt)
|
||||
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobSucceeded, "export", "", "",
|
||||
result.SnapshotID, "", finishedAt)
|
||||
if completeErr := completeLibraryCaptureJob(ctx, store, libraryJobID, result.SnapshotID, finishedAt); completeErr != nil {
|
||||
return completeErr
|
||||
}
|
||||
log.Printf("library capture completed scope=%s capture_job=%s snapshot=%s replay=%v requested_by=%s",
|
||||
payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy)
|
||||
return nil
|
||||
@@ -467,19 +575,30 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
return handlers, nil
|
||||
}
|
||||
apiKey, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", err)
|
||||
// 启动只验证“有一条可用凭据”:旧部署是文件,新部署可以是加密存储里的连接。
|
||||
// 两者都没有时不再静默启动,仍像以前一样拒绝;具体值由 resolver 每次重读。
|
||||
storageReady := kbBindings != nil && kbBindings.StorageReady()
|
||||
if _, fileErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); fileErr != nil && !storageReady {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", fileErr)
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: config.TestWeKnoraBaseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create test WeKnora client: %w", err)
|
||||
// 与 API 探测共用同一有效目标:加密存储里的连接优先、旧部署文件/端点兜底;
|
||||
// 当前持久化绑定优先、env 兜底。
|
||||
remoteResolver := readiness.Resolver{
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, bindingErr
|
||||
},
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
if kbBindings == nil {
|
||||
key, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
|
||||
return config.TestWeKnoraBaseURL, key, err
|
||||
}
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
}
|
||||
client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}
|
||||
upload, err := testweknora.NewUploadHandler(testweknora.UploadHandlerConfig{
|
||||
Store: store,
|
||||
Client: client,
|
||||
@@ -495,6 +614,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
Client: client,
|
||||
PollDelay: config.TestWeKnoraPollInitial,
|
||||
StallAfter: config.TestWeKnoraStalledAfter,
|
||||
// 页面保存的停滞阈值在这里生效;每 60 秒重读一次活动配置,
|
||||
// 读失败保留上一次值,再失败才回落到启动参数。
|
||||
StallAfterSource: func() time.Duration {
|
||||
return activeStalledAfter(context.Background(), store, config.TestWeKnoraStalledAfter)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create test poll handler: %w", err)
|
||||
@@ -526,3 +650,29 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
handlers["test.remove"] = remove.Handle
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
// activeStalledAfter 读取活动 UI 配置里的解析停滞阈值(带 60 秒缓存)。
|
||||
// 页面保存后无需重启 worker 即可生效;“保存即生效”不是文案,而是这里的读取。
|
||||
var stalledAfterCache struct {
|
||||
mu sync.Mutex
|
||||
value time.Duration
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
func activeStalledAfter(ctx context.Context, store *postgresstore.Store, fallback time.Duration) time.Duration {
|
||||
stalledAfterCache.mu.Lock()
|
||||
defer stalledAfterCache.mu.Unlock()
|
||||
if time.Since(stalledAfterCache.fetchedAt) < time.Minute && stalledAfterCache.value > 0 {
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
settings, err := store.GetActiveUISettings(ctx)
|
||||
if err != nil || settings.StalledAfterSeconds <= 0 {
|
||||
if stalledAfterCache.value > 0 {
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
stalledAfterCache.value = time.Duration(settings.StalledAfterSeconds) * time.Second
|
||||
stalledAfterCache.fetchedAt = time.Now()
|
||||
return stalledAfterCache.value
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) {
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{})
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
PPScanLedgerPath: filepath.Join(root, "state.jsonl"),
|
||||
PPScanManifestPath: filepath.Join(root, "manifest.json"),
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
|
||||
func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) {
|
||||
config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"}
|
||||
_, err := workerHandlers(nil, config)
|
||||
_, err := workerHandlers(nil, config, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) {
|
||||
TestWeKnoraMaxUploadBytes: 1024,
|
||||
TestAcceptancePolicyVersion: "structural-v1",
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -16,9 +16,17 @@ services:
|
||||
BACKUP_HOST_TARGET: weknora-test
|
||||
BACKUP_HOST_SCRIPT_DIR: /opt/weknora-test
|
||||
BACKUP_HOST_ROOT: /srv/kb-backups
|
||||
# 只读盘点(批次/子库路径/实测容量)与上面的 SSH 计划读回独立。
|
||||
# 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开:
|
||||
# 宿主采集器原子写 metadata.json,API 只读挂载输出目录(不挂备份目录):
|
||||
# BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
|
||||
# BACKUP_HOST_METADATA_MAX_AGE: 15m
|
||||
# BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
|
||||
# BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
|
||||
volumes:
|
||||
- ./secrets/release-sim:/run/release-secrets:ro
|
||||
- ./secrets/backup-host:/run/backup-host:ro
|
||||
# - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
|
||||
|
||||
release-worker:
|
||||
environment:
|
||||
|
||||
@@ -57,6 +57,12 @@ services:
|
||||
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
|
||||
# Mount this independent master-key file read-only using the deployment overlay.
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
||||
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
|
||||
# P10 readiness probe reads the routing KB with the same scoped key.
|
||||
|
||||
+6
-1
@@ -18,4 +18,9 @@
|
||||
|
||||
1. 跑 `make verify`(本地全绿不等于远端跑通,需要一次真实 run 的证据)。
|
||||
2. 把**使用者可见**的变化写成 `CHANGELOG.md` 的 `[Unreleased]` 条目(按四类,别写过程)。
|
||||
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
|
||||
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
|
||||
## 资源首次复用的归属审计(后续)
|
||||
|
||||
- 当前首次复用只依赖“目标行逐列一致 + 对象字节一致”,不再要求本目标历史成功同步/预备份来源。
|
||||
- 后续可补:资源首次写入者/首次绑定 KB、跨 KB 引用计数、孤儿资源与同 tenant 共享资源的可审计归属视图;
|
||||
不以此重新阻断正常的同内容首次复用。
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# 知识治理候选和批次验收
|
||||
|
||||
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 发起候选
|
||||
|
||||
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
||||
|
||||
````markdown
|
||||
```kg-release-v1
|
||||
{"task":"<发布任务 UUID>","base":"<当前主站 SHA>","sha":"<候选 SHA>","items":[{"task":"<业务任务 UUID>","pr":123}],"extra":[]}
|
||||
```
|
||||
````
|
||||
|
||||
2. Agent 执行 `candidate_coordinator.py prepare <发布任务 UUID>`。Gitea 核对候选 SHA 的 CI、每个 PR 的落地提交和完整主干范围。需准备候选时,独立 Runner 通过回环入口调度本机执行器。执行器复查发布负责人评论、Gitea 作业证明和当前主站 SHA 后,从准确提交构建镜像并封存。
|
||||
3. 执行器在独立验收数据库上启动同份归档,核验 API 提交、三个运行镜像、迁移账本、Web 入口及归档摘要。在发布任务和业务任务回填候选版本与地址。对「待测试」业务任务,由执行器转「测试中」。本地候选地址绑定回环,验收 Agent 应和执行器同机,或使用经工程侧验证的私有转发。
|
||||
4. `candidate_coordinator.py status <发布任务 UUID>` 读取候选回执或对应 Gitea 运行链接。遇到调度结果不明,先从 Gitea 读回运行再决定恢复路径。
|
||||
|
||||
## 登记验收
|
||||
|
||||
业务验收报告分别放在原业务任务,批次共享功能回归报告放在发布任务。保持测试角色原有输出,使用获授权的验收人或测试 Agent 在对应任务评论追加以下结构化结论。报告应保留用例明细和原始证据链接。该段的 `required` 是本轮登记的必测用例数。
|
||||
|
||||
````markdown
|
||||
```kg-qa-v1
|
||||
{"sha":"<完整提交 SHA>","bundle":"<归档清单 SHA256>","url":"<候选地址>","verdict":"passed","required":3,"passed":3,"failed":0,"blocked":0}
|
||||
```
|
||||
````
|
||||
|
||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||
|
||||
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
- 版本管理机使用 Python 3.11 及以上、Docker Compose、HiFox CLI 和已有 Gitea 凭据。候选执行器通过 `candidate_worker.py <仓库工作树> <访问文件>` 绑定 `127.0.0.1:38984`,仓库工作树允许读取 `origin/main`。执行器通过现有 Gitea 凭据读取作业与日志。运行账户需能以 `weknora-test` 执行只读版本检查。
|
||||
- 为候选执行器单独配置 `kg-candidate` Runner。作业使用同机回环网络,通过仓库 Secrets 的 `KG_CANDIDATE_ACCESS` 访问执行器。访问文件由执行器用户持有,内容为独立 64 位十六进制随机凭据。候选作业使用的容器须无宿主 Docker socket 和生产密钥挂载。
|
||||
- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。`qa.pgpass` 可包含同一端点的应用库和集成测试库条目,候选只读取 `qa.json` 指定的库和角色。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。
|
||||
- 候选执行器采用单验收槽。新批次启动前由运维确认前一批验收结束,按上一批 `ready.json` 中的容器身份停止其 Compose 项目,归档原有配置和回执后释放槽位。保留已验收的归档及审批记录。
|
||||
|
||||
## 演练和当前环境
|
||||
|
||||
`prepare-candidate.yml` 的 `verify` 模式校验 Gitea 范围与 CI。可在评审分支验证。`prepare` 模式只接受 `main` 的调度。`candidate_release.py build` 和 `candidate_runtime.py <bundle>` 可在隔离开发机演练打包及冒烟。后者使用临时 Docker 数据库,退出后停止演练容器。
|
||||
|
||||
候选提交必须位于 `main` 的第一父链,并包含主站实际运行的提交。若现场版本从独立分支发布,先通过保留提交历史的合并将现场基线纳入 `main`。现场提交本身可以位于第二父链。候选计划须覆盖 `git rev-list --first-parent <现场 SHA>..<候选 SHA>` 的每一项,包括基线合并提交和已确认随批发布的工程提交。主站数据库仅用于正式应用,业务候选使用专用 QA 库。
|
||||
@@ -0,0 +1,131 @@
|
||||
# 知识治理平台开发与测试
|
||||
|
||||
以下命令从仓库根目录运行。日常开发可在 Ubuntu 宿主进行,指定提交的回归在 `hifox-qa` 的独立检出中运行。部署到阿里云测试服后的验收按 [操作 Runbook](OPERATIONS_RUNBOOK.md) 和 [用户流程验收](USER_FLOWS_ACCEPTANCE.md) 执行。
|
||||
|
||||
## QA 虚拟机一键回归
|
||||
|
||||
在 `hifox-qa` 检出提测提交后,运行下列入口。将 SHA 占位值换成提测记录里的完整提交 SHA。
|
||||
|
||||
```bash
|
||||
make qa-doctor
|
||||
KG_QA_SHA='<完整提交 SHA>' make qa
|
||||
```
|
||||
|
||||
`make qa-doctor` 检查工具链、HiFox 机器在线状态、OMP 模型调用、测试库身份和已安装的迁移。`make qa` 安装锁定依赖,在专用测试库上通过 API 初始化和迁移,随后核对完整迁移序列、API 就绪状态、Web 首页及 Vite 健康代理。通过后执行 Go 和 Vitest 测试,结束时关闭本次启动的服务。每次运行的服务日志保存在 `~/.local/state/knowledge-governance/qa/`。需要提交前完整门禁时执行 `make verify`。
|
||||
|
||||
初次配置由负责人在 QA 虚拟机准备 `~/.config/knowledge-governance/`。以下示例使用虚构的 RDS 主机名。
|
||||
|
||||
| 文件 | 内容 |
|
||||
| --- | --- |
|
||||
| `qa.json` | 当前用户所有、权限 `0600`,字段 `host`、`port`、`database`、`user` |
|
||||
| `qa.pgpass` | 当前用户所有、权限 `0600`,填写与 `qa.json` 匹配的口令条目 |
|
||||
| `rds-ca.pem` | 对应实例的 CA 证书,用于校验 RDS 主机名 |
|
||||
|
||||
```json
|
||||
{"host":"rds.example.test","port":5432,"database":"kg_qa_app","user":"kg_qa_app"}
|
||||
```
|
||||
|
||||
专用非生产 RDS 库和角色以 `kg_qa_` 开头,权限和网络准备见第 2 节。首次运行接受空库,后续运行接受与当前提交兼容的迁移序列。缺库、认证失败、迁移不兼容和端口冲突均会使命令非零退出。浏览器业务 E2E 和专用集成库的 Go 测试按第 4 节执行。
|
||||
|
||||
## 1. 检出代码与安装依赖
|
||||
|
||||
准备 Git、Make、Python 3、Go 1.26(含同一工具链的 `gofmt`)、Node.js 22 和 npm。数据库检查另需 PostgreSQL 客户端 `psql`。首次安装依赖需要能访问 Go 和 npm 的依赖源。
|
||||
|
||||
```bash
|
||||
# QA 在独立克隆中拉取提测分支,使用提测记录里的完整提交 SHA
|
||||
export KG_TARGET_BRANCH='<提测分支名>' KG_TARGET_SHA='<完整提交 SHA>'
|
||||
git fetch origin "$KG_TARGET_BRANCH" && git switch --detach "$KG_TARGET_SHA" &&
|
||||
test "$(git rev-parse HEAD)" = "$KG_TARGET_SHA" && test -z "$(git status --porcelain)"
|
||||
# 上面的命令链若失败,先解决检出或工作区问题再继续
|
||||
|
||||
# 检查当前 shell 的工具链,非交互任务也应设置相同的 PATH
|
||||
export PATH="$(go env GOROOT)/bin:$PATH"
|
||||
go version
|
||||
command -v gofmt
|
||||
node --version
|
||||
npm --version
|
||||
python3 --version
|
||||
make deps-install
|
||||
```
|
||||
|
||||
`make deps-install` 通过 `go mod download` 和 `npm ci` 安装依赖。Go 依赖由 `go.mod` / `go.sum` 约束,前端由 `web/package-lock.json` 锁定。依赖安装失败时先检查工具链、依赖源和锁文件,避免临时改写清单来绕过问题。
|
||||
|
||||
## 2. 准备开发和测试数据库
|
||||
|
||||
无库检查可直接跳到第 4 节。启动 API 或执行真库测试前,由数据库管理员在**非生产 PostgreSQL RDS** 上预建专用空库和登录角色。建议分配 `kg_qa_app` 给应用冒烟,`kg_qa_it` 给 Go 集成测试,各用独立角色。开发宿主另用开发专用库,避免与 QA 共享数据。库未分配时先申请,启动流程以库已存在为前提。
|
||||
|
||||
| 用途 | 所需权限 | 数据初始化 |
|
||||
| --- | --- | --- |
|
||||
| 应用启动与 UI 冒烟 | `CONNECT`,以及目标 schema 内的 `USAGE`、`CREATE` 和对应用对象的读写权限。迁移角色须能修改自己创建的对象。 | 首次 API 启动执行仓库内嵌迁移。用户表为空时创建初始管理员,首次登录必须修改密码。初始口令通过测试环境负责人交接。 |
|
||||
| Go PostgreSQL 集成测试 | `CONNECT` 和目标测试库的 `CREATE` 权限,用于建立各用例自己的 schema。 | 用例创建隔离 schema、执行迁移、写入测试数据并清理。相同测试不要并发指向同一个库,避免固定 schema 名冲突。 |
|
||||
|
||||
两类角色均只授予对应非生产库所需的权限。使用空库和合成数据。密码由操作者在目标机配置到权限为 `0600` 的 PostgreSQL passfile,条目按 `host:port:database:user:password` 填写。使用 RDS CA 校验证书。以下命令先读回实际数据库、角色与 TLS 状态,核对三者再启动 API 或运行真库测试。
|
||||
|
||||
```bash
|
||||
# 用获准的 RDS 主机名、端口、库名、角色和文件路径替换示例值
|
||||
export PGHOST='<非生产 RDS 主机名>' PGPORT=5432
|
||||
export PGDATABASE=kg_qa_app PGUSER=kg_qa_app
|
||||
export PGPASSFILE="$HOME/.config/knowledge-governance/qa.pgpass"
|
||||
export PGSSLROOTCERT="$HOME/.config/knowledge-governance/rds-ca.pem"
|
||||
export PGSSLMODE=verify-full PGCONNECT_TIMEOUT=5
|
||||
psql -X -v ON_ERROR_STOP=1 -c \
|
||||
'SELECT current_database(), current_user, ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid();'
|
||||
```
|
||||
|
||||
如果是云厂商提供的私网地址,先确认执行机通过获准的网络路径可访问 RDS。库名、角色、TLS、连接权限或迁移权限有问题时,先交由环境负责人核对配置。实例上已有数据的库不能当作空库初始化。
|
||||
|
||||
## 3. 启动后端和前端
|
||||
|
||||
**终端 A,启动 API。** 在干净 shell 中执行第 2 节的应用库配置和连通性检查。使用独立测试配置,不加载现网 `.env`。
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5"
|
||||
export APP_ADDR=127.0.0.1:8088
|
||||
export TEST_WEKNORA_ENABLED=false PP_SCAN_ENABLED=false
|
||||
export RELEASE_WORKER_ENABLED=false PRODUCTION_RELEASE_REQUESTS_ENABLED=false
|
||||
export DOBOTAI_OPS_READ_ENABLED=false DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
|
||||
go run ./cmd/api
|
||||
```
|
||||
|
||||
API 会在监听前连接 PostgreSQL、应用迁移并初始化管理员。Web 页面和同步 API 联调只需运行 API 与 Vite。需要验证后台队列时,另用相同的隔离应用库配置启动普通 worker(`go run ./cmd/worker`)。涉及取件或来源刷新的任务还依赖容器内 `/app/scripts` 及获准的来源接线,按部署说明准备。发布 worker 无需启动。
|
||||
|
||||
Vite 通过 `localhost:8088` 转发 `/api` 和健康检查。如果 `8088` 已被其他部署占用,使用端口空闲的 QA 虚拟机运行本节。仅改前端时,可复用一个获准联调的测试 API,但需要先确认 `localhost:8088/health` 可达,并核对该地址指向的环境。
|
||||
|
||||
**终端 B,启动 Web。**
|
||||
|
||||
```bash
|
||||
npm --prefix web run dev -- --host 127.0.0.1 --port 5173 --strictPort
|
||||
```
|
||||
|
||||
在运行服务的机器打开 `http://127.0.0.1:5173/`。另开终端检查 API 与前端代理,再复查迁移记录。最后一条命令需要第 2 节的应用库配置。
|
||||
|
||||
```bash
|
||||
curl --fail --silent --show-error http://127.0.0.1:8088/health
|
||||
curl --fail --silent --show-error http://127.0.0.1:5173/health
|
||||
psql -X -v ON_ERROR_STOP=1 -c \
|
||||
'SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;'
|
||||
```
|
||||
|
||||
空库首次启动后,用专用测试账号登录,按当次验收标准验证页面及接口。联调结束在两个终端按 `Ctrl+C` 停服务,数据库由环境管理员按测试数据保留规则管理。
|
||||
|
||||
## 4. 选择测试命令
|
||||
|
||||
| 目的 | 命令 |
|
||||
| --- | --- |
|
||||
| 查看检查及适用范围 | `make list` |
|
||||
| 后端包测试 | `make tests-go` |
|
||||
| 单个 Go 包及相关子包 | `go test -count=1 ./internal/httpapi/...` |
|
||||
| 前端 Vitest 套件 | `make tests-web` |
|
||||
| 单个前端测试文件 | `npm --prefix web test -- src/App.test.tsx` |
|
||||
| 完整提交前检查,与 CI 共用入口 | `make verify` |
|
||||
|
||||
`make verify` 包含安装、格式、静态检查、构建、测试、版本和安全检查,并写出 `ci-report.json`。在未导入真库测试配置的 shell 中运行。若检出时用了 `--no-tags`,先执行 `git fetch --tags origin`,以便版本检查读取正式标签对应的提交。依赖安装与安全检查需要相应网络或缓存。允许跳过的外部依赖用例见 [test-scope.json](../scripts/test-scope.json),真库测试应单独执行并记录结果。
|
||||
|
||||
在应用冒烟之外验证真实 PostgreSQL 行为时,重新按第 2 节切换并核对 **集成测试库和角色**,然后执行目标用例。下面以 UI 设置版本切换用例为例。
|
||||
|
||||
```bash
|
||||
TEST_DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5" \
|
||||
go test -count=1 -v ./internal/platform/postgres -run '^TestUISettingsActivationRetiresPreviousRevisionIntegration$'
|
||||
```
|
||||
|
||||
检查输出出现目标用例的 `PASS`。用例被跳过或没有匹配时,应补齐配置或纠正用例名后重跑。前端 Vitest 负责组件与业务逻辑检查,浏览器 E2E 应单独执行并按 Feature 保存证据。提测记录至少包括完整提交 SHA、执行命令、退出码,以及失败用例的日志或浏览器截图。
|
||||
@@ -0,0 +1,44 @@
|
||||
# DWS 登录授权
|
||||
|
||||
管理员入口:系统设置 → 数据源配置 → 钉钉账号(DWS)。
|
||||
|
||||
- 未登录时点击“登录授权”,在弹窗中打开钉钉官方授权页,由本人选择账号与组织并确认。
|
||||
- 平台等待设备授权完成。成功后自动刷新账号、组织和续期凭证有效期,并检查知识库、钉盘目录访问。
|
||||
- “重新授权”采用同一流程;授权中可取消,失败或过期后可重新发起。
|
||||
- “检查连接”只列目录与读取登录元数据,不登记来源、不扫描已有来源、不发起入库或生产发布。
|
||||
- 登录成功与目录可用分开显示;部分范围无权限时保留其他已成功范围,并展示原因。
|
||||
|
||||
## 服务端接线
|
||||
|
||||
API 直接管理 `dws auth login --device --no-browser --format json` 子进程,不复用旧浏览器扫码侧车。
|
||||
CLI 负责官方 OAuth 协议、组织 CLI 权限校验及凭据加密持久化。平台只解析官方设备授权链接、用户授权码、有效期与状态;原始输出、access token、refresh token不进入接口或日志。
|
||||
|
||||
API 与 worker 必须使用相同 UID,以及同一组可写挂载:
|
||||
|
||||
| 配置 | 用途 |
|
||||
|---|---|
|
||||
| `DWS_BIN` | 固定版本的 DWS 程序 |
|
||||
| `DWS_CONFIG_DIR` | 共享的 DWS 状态目录 |
|
||||
| `DWS_HOME` | 共享 home,包含 `.local/share/dws-cli` 文件型密钥存储 |
|
||||
| `DWS_DISABLE_KEYCHAIN=1` | 容器使用文件型凭据存储 |
|
||||
|
||||
子进程 HOME 由 DWS_HOME 指定,只透传所需环境。禁止把认证状态复制成多份,避免轮换令牌互相失效。
|
||||
|
||||
## 接口与生命周期
|
||||
|
||||
- `POST /api/v1/dws-login`:立即返回 starting,后台生成设备授权;同一浏览器管理员会话重复请求复用在途授权。
|
||||
- `GET /api/v1/dws-login/{id}`:读取本人发起的授权。
|
||||
- `DELETE /api/v1/dws-login/{id}`:取消并等待旧 CLI 退出,清除授权链接与用户码。
|
||||
- 上述接口均为管理员专用;授权绑定管理员及其登录会话,另一会话无法读取或取消。
|
||||
- 创建和取消要求同源操作意图;响应禁止缓存。仅允许 `https://login.dingtalk.com/oauth2/device/verify.htm` 官方链接。
|
||||
- 每次只运行一个授权,防止覆盖共享状态。服务重启会结束在途授权;页面提示重新发起。
|
||||
- CLI 成功退出后必须再次读到有效本地凭据才显示登录成功;真实目录访问另行检查。
|
||||
|
||||
## 添加来源
|
||||
|
||||
添加来源向导与账号卡共用官方 DWS 授权;列举、校验、登记使用同一身份。来源登记不再自动回落旧扫码侧车。保存中授权失效时保留已成功项并恢复剩余项;换账号或组织后需重新确认范围。详细交互、认证审计与 PP 接线见 [数据源认证配置](SOURCE_AUTH_CONFIGURATION.md)。
|
||||
|
||||
## 验证边界
|
||||
|
||||
自动回归覆盖授权生成、成功后状态更新、目录访问失败与部分可用、取消与进程退出、过期、重试、跨管理员/会话隔离、同源限制、官方链接校验及元数据脱敏。
|
||||
真实本人授权需要管理员在钉钉官方页面确认;自动测试与生成真实授权链接不替代本人授权,也不证明其公司目录权限。
|
||||
@@ -3,14 +3,107 @@
|
||||
按"实际干活顺序"排列的**现在的**操作流程。标注:**【新】**本期新增(含本次会话与 `f4e1ecc/6496ee3/9155bd3` 的 dws 取件)|**【变】**既有流程本期有改动|**【既有】**未变,仍照旧走。
|
||||
逐条验收证据请看 `docs/USER_FLOWS_ACCEPTANCE.md`;细节规则看各自专题文档。
|
||||
|
||||
统一入口 **http://127.0.0.1:8088/**(测试栈,右侧面板可直接操作)。角色:管理员 / 文档工程师 / 只读。
|
||||
管理员配置连接和发布授权,文档工程师维护资料,只读成员查看进度。先确定要操作的环境,再按下面的接线与验收步骤进入业务流程。
|
||||
|
||||
云测试治理主站自身的应用升级见[主站应用 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 入口与反向代理
|
||||
|
||||
| 请求从哪里发出 | 地址或路径 | 实际目的地 |
|
||||
|---|---|---|
|
||||
| 已接入内网的运维电脑 | `http://100.85.111.121:8088/` | 云测试治理主站 |
|
||||
| 开发电脑的浏览器 | `http://127.0.0.1:28189/` | SSH 转发到测试机回环 `28189`,由候选 Web 提供静态资源 |
|
||||
| 测试候选 Nginx(host 网络) | `/api/`、`/health` | 测试机 `127.0.0.1:18099` 候选 API |
|
||||
| 同一候选 Nginx | `/api/v1/qa-ops/ai/` | 测试机 `127.0.0.1:18098` 现用治理 API,负责模型配置和连接验证 |
|
||||
| 标准 Compose Web(容器网络) | `/api/`、`/health` | Docker DNS 解析 `api:8080`。静态资源和 SPA 回退由同一 Web 提供 |
|
||||
|
||||
**在开发电脑恢复验收入口。** 前提是 SSH 别名 `weknora-test` 能登录测试机。先查远端服务,再查本机监听。本机端口空闲且远端正常时,在独立终端运行第三条命令,保留该终端。在另一终端执行最后一条并用浏览器打开同一地址。
|
||||
|
||||
```bash
|
||||
ssh weknora-test 'curl -fsS --max-time 5 http://127.0.0.1:28189/health'
|
||||
ss -ltn 'sport = :28189'
|
||||
ssh -NT -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 127.0.0.1:28189:127.0.0.1:28189 weknora-test
|
||||
curl -fsS --max-time 5 http://127.0.0.1:28189/health
|
||||
```
|
||||
|
||||
**为内网域名配置 HTTPS。** 在能访问测试主站的受信任反代机上配置证书、内部 DNS 和访问范围。以下片段放入已有 HTTPS `server`,完整保留 URI、Host 和会话 Cookie。上游应选治理 Web 入口,使 `/assets/`、`/api/`、`/health` 走同一域名。若该入口的内层代理也设置 `X-Forwarded-Proto`,联调时检查其保留受信任 TLS 终止层的协议值以及登录回调的实际 URL。
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_pass http://100.85.111.121:8088;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
```
|
||||
|
||||
在反代机执行 `nginx -t` 校验待应用配置。入口启用后,通过该域名验证登录、一次 `/api/` 请求和首页实际引用的 JS/CSS。`index.html` 应重新校验,带哈希的资源可长期缓存,缺失的 JS 返回 404。候选切换前后分别记录通用上游和 AI 专用上游。现场可在测试机用以下只读命令查看,容器名以当时部署为准。仓内同源配置见 [deploy/nginx.conf](../deploy/nginx.conf)。
|
||||
|
||||
```bash
|
||||
docker exec kg-test-storage-ui-6444814 nginx -T 2>&1 | grep -E 'listen .*28189|location /api/v1/qa-ops/ai/|set \$(api|health)_upstream|proxy_pass http://127[.]0[.]0[.]1:18098'
|
||||
docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage-ui-6444814 kg-accept-090-api
|
||||
```
|
||||
|
||||
**现场版本与回退。** 本次在测试机读到 Web 标签 `4b615abe534b`、API 标签 `341c3154ac91`。完整候选包的 `current` 链接位于 `/opt/knowledge-governance/acceptance/090/current`,单独切换的 Web 位于同级 `web-only/4b615abe534b/dist`,实际反代配置位于 `integration/28189.conf`。切换前记录这三处、容器标签与旧 Web 名称。静态页回退时恢复上次的 Web 资源和对应代理配置。完整候选回退按同批装配工具的 `deploy/accept-090/README.md` 执行。回退后用浏览器重新验证首页资源、模型连接和列库。数据库迁移另按备份与恢复方案处理。
|
||||
|
||||
本次已核实共享测试治理库到 `000082`。对内、对外独立启用的实现依赖 `000083`,待独立库联调或共享库迁移获准后,再验证单侧暂停、保存和刷新。生产 `070` 不在该套验收范围。
|
||||
|
||||
下文系统设置中的绑定、盘点和模型连接步骤适用于上表的测试候选版本。根据现场标签选择对应版本的代码和交付物。
|
||||
|
||||
## 接入外部平台
|
||||
|
||||
| 平台与用途 | 管理员或运维怎样接 | 接通的证据 |
|
||||
|---|---|---|
|
||||
| 钉钉知识库,取目录和文件 | 系统设置 → 数据源配置 → 钉钉授权。用 DWS 设备授权,以来源账号选择组织、空间和范围。API 与 worker 使用部署约定的 DWS 身份目录 | 登录后读回预期空间,选一个有权限的目录校验。登记来源、扫描完成和文件取件分别核验。[授权手册](DWS_LOGIN.md) |
|
||||
| AList,取工业或教育资料 | 按来源登记服务根地址和允许的目录。普通 worker 读取专用令牌文件。目录接口 `POST /api/fs/list` 使用 `X-Gateway-Token` | 在来源页扫描已知根目录,对照一个子目录和一份文件。下载遵循来源签名链接,凭据和签名 URL 仅留在受控运行环境。[目录与取件](SOURCE_CATALOG_LIVE_ROUTING_ACCEPTANCE.md) |
|
||||
| PP 资料门户 | 在数据源配置填写 HTTPS 根地址和来源账号,点「测试连接」后「保存并校验」。API 和 worker 共享 `PP_AUTH_STATE_FILE` 所在目录 | 真实登录并读取一条目录记录,刷新后核对生效配置。超时或限流时查看待验证状态。[认证、保存与扫描契约](SOURCE_AUTH_CONFIGURATION.md) |
|
||||
| WeKnora 测试 090,处理与验收 | 系统设置 → 知识库绑定 → 测试 090。当前测试 API 地址 `http://127.0.0.1:8092`,由治理服务器访问。输入该实例的专用 Key 或使用已配置凭据 | 「验证并读取知识库」能列出预期库。核对名称和 ID,为对内、对外选择不同的目标,保存后刷新读回 |
|
||||
| WeKnora 生产 090,列库与映射 | 在同页切到生产 090,使用下节的转发入口与生产专用 Key。新连接的安全存储由 `WEKNORA_BINDING_MASTER_KEY_FILE` 提供 | 读取生产目录并核对两个目标 ID,保存后重新进入生产页核实。执行发布另按 §5–6 授权 |
|
||||
| 问答 AI 模型 | 系统设置 → AI 模型连接,填写 OpenAI 兼容基础地址(含服务要求的 `/v1`)、模型名及专用 Key。API 与普通 worker 使用同一 `QA_AI_MASTER_KEY_FILE` | 点「测试连接」等待成功,需生效时再保存并刷新检查模型名。存储密钥、权限与 DNS 配置见 [README](../README.md#问答运营模型配置) |
|
||||
|
||||
**生产 090 的两段地址。** 生产机私网 IP 为 `172.29.151.11`,其 WeKnora API 对宿主回环发布 `127.0.0.1:18092`。测试治理机上已有 SSH 本地转发,治理 API 使用 host 网络,故页面的生产服务地址填写 **`http://127.0.0.1:18092`**。请求从治理 API 发出,经测试机的回环监听到生产机的回环 API。浏览器所在电脑的 `127.0.0.1:28189` 则用于打开治理页面。迁到 bridge 网络时要从新 API 容器重新验证上游可达性。
|
||||
|
||||
**直连反代(18093)与隧道(18092)二选一。** 若生产机已按前置要求提供
|
||||
`172.29.151.11:18093`(只放行测试机),页面就填 `http://172.29.151.11:18093`,并在
|
||||
部署侧设置 `WEKNORA_ALLOW_PRIVATE_HTTP=true` —— 它只放行 RFC1918/回环/链路本地
|
||||
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
|
||||
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
|
||||
|
||||
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
|
||||
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
|
||||
「同 ID 语义」,提示里会写明。
|
||||
|
||||
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
|
||||
|
||||
```bash
|
||||
ss -ltnp 'sport = :18092'
|
||||
curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'health %{http_code}\n' http://127.0.0.1:18092/health
|
||||
curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'catalog %{http_code}\n' http://127.0.0.1:18092/api/v1/knowledge-bases
|
||||
```
|
||||
|
||||
## 开发测试和现场验收
|
||||
|
||||
1. 在开发机运行 `make list` 查看门禁,`make verify` 做整套检查。以 `ci-report.json` 的 `commit_sha` 对照 `git rev-parse HEAD`,记录失败或跳过项。前端启动和组件测试见 [开发与 CI](../README.md#开发与-ci)。
|
||||
2. 针对后端改动,在独立测试逻辑库核对 `SELECT current_database(), max(version) FROM schema_migrations;` 与候选版本的迁移目录。云端多个候选可能共用治理 RDS。只改静态页面时单独切换 Web,保留原资源和代理配置供回滚。
|
||||
3. 在指定入口以真实账号分别验证。来源页读取一条已知记录,模型页测试到成功终态,知识库绑定在正确环境列库,保存后刷新核对。存储页按最近批次和子库目录分别与 `du -sB1 -- <目录>` 对账。记录入口、Web/API 提交、时间和结果。
|
||||
4. 候选备份页读取宿主采集的 `metadata.json`,API 只读挂载输出目录。「重新盘点」只重读文件。超过 `BACKUP_HOST_METADATA_MAX_AGE` 时,目录、占盘和预测转为未知。宿主重新采集后核对采集时间是否前进、批次是否恢复。测试现场使用按次采集、15 分钟有效期。采集命令和挂载契约见 [备份只读接口](STORAGE_BACKUP_READONLY_API.md)。
|
||||
|
||||
| 症状 | 第一步怎么查 | 如何判定 |
|
||||
|---|---|---|
|
||||
| 浏览器连接被拒 | 对照本机 `28189` 监听和测试机 `/health` | 远端正常、本机无监听时恢复本机 SSH 转发 |
|
||||
| 页面打开,某个 API 404 或 502 | 查浏览器请求路径、Nginx 生效上游及对应 API 版本 | 404 先查路由是否存在,502 先查上游是否可达。AI 页单独核对 `18098` |
|
||||
| 能探活,列库仍灰或返回 401 | 核对选中环境、凭据配置状态、容器运行 UID 与凭据文件可读性 | 用该环境的专用身份实际列库。检查过程只记录状态码和可读性 |
|
||||
| 历史可读,计划或配额显示未知 | 核对快照年龄、执行主机连接与配额字段 | 盘点、SSH 计划、配额分别验证。只有主机实际读回 cron 才能报告下一次执行时间 |
|
||||
|
||||
---
|
||||
|
||||
## 0. 开工前:环境与凭据自检
|
||||
| 项 | 怎么做 | 成功标志 |
|
||||
|---|---|---|
|
||||
| 测试/生产 WeKnora | 系统设置 → 服务配置 | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 测试/生产 WeKnora | 系统设置 → 知识库绑定(选择测试 090 / 生产 090) | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 钉钉取件凭据 **【新】** | 容器内 `HOME=/data/home dws auth status --readonly -f json` | `authenticated:true`、`refresh_token_valid:true`(**必须带 `HOME=/data/home`,否则误报未登录**) |
|
||||
| 备份主机接线 | 系统设置 → 存储与备份 | "目标主机 weknora-test · 已连接" |
|
||||
|
||||
@@ -80,9 +173,8 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
|
||||
|
||||
| 分区 | 谁 | 现在要管什么 |
|
||||
|---|---|---|
|
||||
| 服务配置 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) |
|
||||
| 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) |
|
||||
| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) |
|
||||
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
|
||||
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
|
||||
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
|
||||
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
|
||||
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
|
||||
|
||||
@@ -91,13 +91,17 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
||||
|
||||
- 页面:系统设置 → 存储与备份(管理员可改;保存 = 写入库并立刻下发;另有"重新下发当前设置"与"立即备份一次")。
|
||||
- 接口:`GET /api/v1/backup-schedule`(不探测主机,首屏快)、`GET …/host`(SSH 读回主机 cron 与最近一次结果)、
|
||||
`GET …/inventory`(宿主采集器快照读全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
|
||||
`PUT`(校验时间 `HH:MM` 与 1~365 天 / 0~24 月,非法值直接 400 且不落库不下发)、`POST …/apply`、`POST …/run`。
|
||||
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
||||
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
|
||||
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
|
||||
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
||||
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
||||
`scripts/collect_backup_metadata.py` 原子写 `metadata.json`,API 用
|
||||
`BACKUP_HOST_METADATA_PATH / BACKUP_HOST_READONLY_HOST_PATH` 只读快照,见
|
||||
`docs/STORAGE_BACKUP_READONLY_API.md`。
|
||||
- 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`,
|
||||
所以"最近一次备份"永远不会显示一份半成品。
|
||||
- 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# 云测试治理主站应用 CD
|
||||
|
||||
正式入口为 `http://100.85.111.121:8088/`。云端 Compose 项目为 `knowledge-governance-cloud-test`,工作目录 `/opt/knowledge-governance`,当前配置链为 `compose.json`,服务为 `api`、`web`、`worker`。Web 容器提供 `8088`,通过挂载的 nginx 配置代理 API 的 `127.0.0.1:18098`。应用 CD 与知识库内容发布各自保留原有授权流程。
|
||||
|
||||
## 建立验收产物
|
||||
|
||||
1. 从干净检出的完整提交构建一次 API、worker、web 镜像。构建调用方对三个镜像都注入 `org.opencontainers.image.revision=<完整 SHA>`。API 构建身份沿用 `scripts/version.py --identity` 输出,传给 Dockerfile 的版本、提交和构建时间参数。API 与 worker 各自记录镜像 ID,即使它们来自同一个 Dockerfile。
|
||||
2. 封存后用同一份归档部署到隔离验收环境。输出目录必须是新路径,父目录应已存在。三个 `--api/--web/--worker` 参数是本地镜像的完整 ID。
|
||||
|
||||
```bash
|
||||
python3 scripts/production_cd.py pack --sha "$SHA" --task "$TASK_UUID" \
|
||||
--api "$API_ID" --web "$WEB_ID" --worker "$WORKER_ID" --output "$BUNDLE_DIR"
|
||||
docker load -i "$BUNDLE_DIR/api.tar"
|
||||
docker load -i "$BUNDLE_DIR/web.tar"
|
||||
docker load -i "$BUNDLE_DIR/worker.tar"
|
||||
```
|
||||
|
||||
3. 用验收环境自身的 Compose 和数据库启动这些镜像。用下面的命令读回验收环境运行身份。此处三个服务参数是实际的**测试容器名**。在业务验收入口执行实际用例并将输出、结果与报告链接放在同一份验收记录里。
|
||||
|
||||
```bash
|
||||
python3 scripts/production_cd.py attest --sha "$SHA" --task "$TASK_UUID" \
|
||||
--api "$QA_API" --web "$QA_WEB" --worker "$QA_WORKER" --test-url "$QA_URL" --directory "$BUNDLE_DIR"
|
||||
BUNDLE_SHA=$(sha256sum "$BUNDLE_DIR/release.json" | cut -d' ' -f1)
|
||||
```
|
||||
|
||||
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
|
||||
5. HiFox 触发器在派发 Gitea 前自动通过执行机的 `weknora-test` SSH 通道交接四个文件,并用主站控制器校验。人工 Actions 入口仍须由运维提前将四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
|
||||
|
||||
## 在 HiFox 确认发布
|
||||
|
||||
验收、登记、上传归档都完成后,由发布人把原任务移入「待发布」。HiFox 的「知识治理|待发布自动执行 CD」把任务 UUID 交给专用发布 Agent,Agent 调用白名单内的 `scripts/hifox_release_trigger.py`。桥接脚本读取 HiFox 时间线,校验最近一次状态变更的操作者、状态、同任务验收报告及产物摘要,随后调度 Gitea `deploy-production@main`。Gitea 仍只开放 `workflow_dispatch`。目标控制器按完整输入校验 Gitea 运行,并在切换前复查 HiFox 状态和验收摘要。
|
||||
|
||||
相同状态事件复用已记录的 Gitea 运行。如果调度结果未知,核查对应 Gitea 运行与本机调度记录后再处理。旧任务已处于「待发布」时,在验收登记完成后重新进入该状态可发起新确认。
|
||||
|
||||
也可由发布人使用 Gitea Actions 中原有人工入口应急。分支选 `main`,使用 `action=deploy`、完整 `sha`、`bundle`、任务 UUID `task` 和 `confirm=deploy-production`,仅 HiFox Agent 填写 `approval_event` 和 `acceptance_digest`。
|
||||
|
||||
主站侧从 Gitea 读取运行、操作者和通过的校验作业,并验证输入摘要及工作流代码。候选代码可来自仓库内的任务分支,以实际验收 SHA 为准。切换前还核验必需 CI 状态、HiFox 验收记录、三份归档、线上源代码血缘及数据库迁移账本。切换复用 `scripts/deploy-api-web.sh`,仅更换三项 Compose `image`;保留原配置字节以备回滚。切换后自动读回三镜像、API 二进制 SHA、主站健康、API readiness 及实际提供的前端资源。HiFox 回写包含原始运行 URL、完整提交、摘要、镜像 ID 及核验证据。任务评论另含主站登录地址和已核验的运行版本,带 OCI 版本标签时显示其值,其余镜像显示完整提交。
|
||||
|
||||
目标机已有的 `schema_migrations` 必须与候选完全相同,API 与 worker 的库连接均须核对。应用会在启动时检查迁移。新增或改变的迁移先按独立流程审查、备份、执行并复验;CD 自身只读迁移账本。发布时运营方应保留 prior tag,保障用原 Compose 字节回滚。
|
||||
|
||||
## 失败恢复
|
||||
|
||||
- `rolled_back` 表示自动恢复了原 Compose、旧的镜像 ID、API SHA 与站点健康。`rollback_failed` 或 `cutover_started` 要求巡检现场、按回执恢复并复验。目标机互斥锁覆盖切换及回写。Gitea 的取消记录只能说明流水线结束,回滚以目标机回执和运行时读回为准。
|
||||
- `DEPLOYED_HIFOX_PENDING` 表示镜像切换和核验已经完成。以同一 `sha`、`bundle`、`task` 人工发起 `action=writeback`、`confirm=retry-writeback`。脚本先读原目标回执并复验仍在运行的版本,随后补写 HiFox,保留原部署链接。状态与 metadata 的当前值以 HiFox 读回为准。重复调用核对记录后结束。
|
||||
- 目标回执 `/opt/knowledge-governance/cd/receipts/<bundle>.json`,镜像切换前的 Compose 保存为同名 `.compose.backup`。SSH 超时或强制中断后,先读回执和当前运行态。已存在未决或失败回执时,重复部署被拒。保留原回执作为事故证据。
|
||||
|
||||
## 一次性配置与权限
|
||||
|
||||
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
|
||||
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
|
||||
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
|
||||
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py,cd_bundle_handoff.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
|
||||
@@ -3,7 +3,7 @@
|
||||
> 这份文档是**破坏性变化与数据迁移步骤的落脚点**:`CHANGELOG.md` 里以 `**破坏性**` 开头的条目
|
||||
> **必须**链接到本文(或本文的某个小节)。发布记录本身仍在 `CHANGELOG.md` —— 本文不维护第二份变更列表。
|
||||
>
|
||||
> 本仓 CI **只做 CI**:不打 tag、不发 Release、不部署。发布与部署都是**独立的人工审批动作**。
|
||||
> 常规 CI 负责检查、构建与静态预览。版本 tag 与 Release 由人批准后执行。主站应用部署使用独立的[人工确认 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
|
||||
## 一、正式发布(由人批准后执行)
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# 数据源认证配置
|
||||
|
||||
管理员入口:系统设置 → 数据源配置。PP 连接位于钉钉账号卡旁;添加来源向导使用同一组账号与配置。
|
||||
|
||||
## PP 连接
|
||||
|
||||
- API 地址填写 HTTPS 根地址;后台沿用 `/admin/login/token`、`/potal/file/back/page` 接口路径。`potal` 是上游真实路径,不能改写。
|
||||
- 账号允许修改。密码只显示已配置/未配置;点击“更新密码”录入新值。省略或留空保留既有密码,不回显原值。
|
||||
- “测试连接”使用当前表单,真实登录并读取一条目录记录;合法空目录也可通过。它不保存配置、不登记来源、不启动扫描。
|
||||
- “保存并校验”在后端重新检查本次提交。通过后切换生效;明确的认证拒绝、权限拒绝、接口不兼容阻止生效。
|
||||
- 超时、限流或服务临时故障可保存为待验证修改;缺少凭据可保存未完成配置。两者都不会替换当前生效配置;需要再次保存并校验,通过后才切换。
|
||||
- 草稿测试结果与当前生效配置状态分开;每次修改字段会使原草稿测试结果作废。检查失败时保留上次观测及时间,不能把网络失败当成退出登录。
|
||||
- 后续目录扫描和远程取件读取同一生效配置;验证过的本地文件仍按既有内容校验逻辑复用。配置保存不恢复暂停的计划、不触发入库或发布。
|
||||
|
||||
## PP 服务端接线
|
||||
|
||||
| 参数 | 默认与用途 |
|
||||
|---|---|
|
||||
| `PP_AUTH_STATE_FILE` | `/data/source-auth/pp/settings.json`;API 和 worker 必须读同一份原子配置文件 |
|
||||
| `PP_AUTH_PYTHON` | `/usr/bin/python3`;API 连接检查使用的解释器 |
|
||||
| `PP_AUTH_CHECK_SCRIPT` | `/app/scripts/pp_client.py`;与扫描、取件共享的只读协议实现 |
|
||||
| `PP_LEGACY_CREDENTIALS_FILE` | 可选,只用于首次迁移;有效状态文件存在后不再回落旧文件 |
|
||||
|
||||
配置目录及状态文件分别使用 0700 和 0600。API/worker 使用相同 UID,将宿主凭据目录挂载为共享目录,不能绑定单个文件:单文件 bind mount 会在原子 rename 后继续指向旧 inode。迁移时从目标机既有凭据文件直接读取,禁止通过聊天、命令行参数或仓库传递密码。
|
||||
|
||||
状态文件持有生效配置、待验证修改、最近检查及认证审计,包含密码,因此必须按密钥文件保护,不能进普通配置备份、版本记录或日志。更新使用跨进程文件锁、临时文件、fsync 和原子 rename。配置修订采用乐观并发控制;旧请求不能覆盖新修订。worker 的迟到检查只能更新自身生效配置 ID 对应的观测。
|
||||
|
||||
PP 检查子进程只从 stdin 接收本次凭据,stdout 只返回白名单检查结论。GET 接口仅返回配置元数据和是否存在密码;密码输入字段只可写。
|
||||
|
||||
| 接口 | 用途 |
|
||||
|---|---|
|
||||
| `GET /api/v1/pp-connection` | 管理员读取安全元数据、待验证修改与检查状态 |
|
||||
| `POST /api/v1/pp-connection/test` | 测试当前草稿,不激活 |
|
||||
| `PUT /api/v1/pp-connection` | 校验并保存;携带当前 `revision` |
|
||||
|
||||
使用已保存的待验证密码继续校验时携带 `pending_id`,避免空密码误用旧生效密码。修改请求验证管理员、同源操作意图和输入大小;响应禁止缓存。
|
||||
|
||||
## 钉钉添加向导
|
||||
|
||||
保留 类型 → 授权 → 范围 → 校验 → 保存 五步;授权步骤复用钉钉账号卡的官方 DWS 设备授权流程。
|
||||
|
||||
- 可见范围、校验和登记都使用共享 DWS 身份;登记不再自动回落旧扫码侧车。DWS 无法定位的历史空间返回明确原因。
|
||||
- `POST /api/v1/dingtalk-spaces/validate` 真实读取并检查所选空间。失败、权限不足、部分范围不完整与合法空列表分别展示。
|
||||
- 已接入空间按稳定空间身份标记,历史连接也从其存储的空间标识识别,不靠名称去重。
|
||||
- 保存中授权失效:保留已成功项及待处理项,在向导内重新授权;同账号恢复后继续剩余项,复用操作标识,首次扫描按连接身份去重。
|
||||
- 取消或失败后保留选择并停止自动提交;再次恢复失败不循环弹授权。
|
||||
- 授权后换账号/组织:重新加载范围并清除旧选择,要求重新确认。客户端提交身份指纹,后端在列举前后确认身份,变化时拒绝登记。
|
||||
- 只有已点击保存的操作才会在重新授权后继续登记;账号登录、刷新和连接检查本身不创建来源或扫描任务。
|
||||
- 登记成功和首次扫描入队分别反馈,不能用登记成功冒充扫描已运行。
|
||||
|
||||
其他历史入口若仍调用旧扫码侧车,保留其原行为;本功能不删除整个侧车服务。
|
||||
|
||||
## 审计与验证
|
||||
|
||||
PP 配置/密码更新、连接检查及 DWS 授权结果,复用现有数据源操作审计页面。凭据事件与配置在同一文件内原子提交,并与数据库原有事件按时间合并分页;不把密码写入 SQL。DWS 终态审计按授权 ID 与状态去重,轮询不刷记录。
|
||||
|
||||
回归覆盖真实协议请求、空目录、认证拒绝、权限与限流、密码保留/替换、待验证密码重校验、并发修订冲突、响应脱敏、同源及角色限制、无意外任务、审计分页、DWS 部分成功恢复与换账号保护。协议与消费者测试使用隔离的本机 HTTP 服务;运行环境可用性需另行通过真实页面检查,不能用这些用例替代。
|
||||
@@ -0,0 +1,228 @@
|
||||
# 存储与备份:宿主元数据采集器、只读接口与 28189 接线
|
||||
|
||||
「备份记录 / 整盘占用」不遍历备份目录。备份目录通常是 `root:root 0700`,API 容器
|
||||
用户 `uid 1000` 进不去;容器里遍历只会得到 permission denied 的部分字节。真实闭环是:
|
||||
|
||||
1. 备份主机上由**有读权限的宿主进程**运行 `scripts/collect_backup_metadata.py` 单次采集;
|
||||
只做 `stat`/`du` 元数据和读 `MANIFEST.json`,不读数据库内容文件。
|
||||
2. 采集器用同目录临时文件 + `fsync` + `os.replace` **原子写出** `metadata.json`。
|
||||
3. API 只读挂载这个 JSON,校验 schema、批次/子库路径、主机根、时效、完整性。
|
||||
4. 快照陈旧/缺失/不完整时,批次字节为 `null`,页面显示未知,不画容量图、不做可写预测。
|
||||
|
||||
主机 cron 计划读回仍是原来的 SSH 通道(`/host`),与快照完全独立;API 不借用 SSH
|
||||
读文件,也不获得备份目录的容器权限。
|
||||
|
||||
## 1. 采集器(宿主运行)
|
||||
|
||||
脚本:`scripts/collect_backup_metadata.py`(Python 3 标准库,无第三方依赖)
|
||||
|
||||
```sh
|
||||
python3 collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical
|
||||
```
|
||||
|
||||
- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
|
||||
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
|
||||
**不打开任何 `.dat/.gz` 数据文件**。
|
||||
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
||||
- 口径与 `du -sB1` 对齐:目录自身块计入;遍历整棵子树而非只求和文件;
|
||||
常规文件硬链接按 `(st_dev, st_ino)` 只算一次;**每个子库与整批各自独立测量**,
|
||||
所以单库字节与该子库自己的 `du` 一致、整批与整批 `du` 一致(不会把整批去重结果
|
||||
摊回单库)。
|
||||
- `MANIFEST.json` 只接受批次目录内的常规非符号链接文件;`lstat` + `O_NOFOLLOW`
|
||||
打开,符号链接/非普通文件一律 `invalid`,不会被跟随到别处。
|
||||
- 权限失败会写入 `batch.errors` 并把 `actual_bytes/apparent_bytes/file_count` 置 `null`;
|
||||
绝不把已数到的部分字节当占盘。
|
||||
|
||||
建议由宿主定时器每 5 分钟跑一次(root 或备份目录所有者;不改任何备份权限):
|
||||
|
||||
```cron
|
||||
*/5 * * * * /usr/bin/python3 /opt/knowledge-governance/collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical \
|
||||
>> /var/log/knowledge-governance-backup-metadata.log 2>&1
|
||||
```
|
||||
|
||||
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
||||
|
||||
### 快照 schema(version 1)
|
||||
|
||||
关键字段:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `schema_version` | `1`;API 不认识就整块拒绝 |
|
||||
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
||||
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
||||
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
|
||||
| `complete` | 全局完整;权限失败/截断/有错误时为 false |
|
||||
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
||||
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
||||
| `batches[].actual_bytes` | `st_blocks×512` 实际分配,仅完整批有值 |
|
||||
| `batches[].databases[].path` | 子库完整宿主路径,必须等于 `<batch>/<name>.dir` |
|
||||
| `batches[].manifest_state` | `ok` / `missing` / `invalid`(清单是元数据,不影响权限统计) |
|
||||
|
||||
## 2. 接口契约
|
||||
|
||||
`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西)
|
||||
|
||||
始终 200 + `data`;未接线/快照缺失/陈旧/不完整/路径不一致都写在字段里。
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"wired": true,
|
||||
"metadata": {
|
||||
"configured": true, "present": true, "valid": true,
|
||||
"fresh": true, "complete": true,
|
||||
"path": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"collected_at": "2026-11-20T01:00:00Z",
|
||||
"age_seconds": 10, "max_age_seconds": 900,
|
||||
"schema_version": 1, "generation": "20261120T010000Z-abc123",
|
||||
"host": "weknora-test", "collector_version": "backup-metadata/1",
|
||||
"error": ""
|
||||
},
|
||||
"root": "/srv/kb-backups/rds-logical",
|
||||
"host_root": "/srv/kb-backups/rds-logical",
|
||||
"source": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"measurement": "host_collector",
|
||||
"mount": {
|
||||
"mount_verified": true, "read_only": false,
|
||||
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
||||
"evidence": "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录"
|
||||
},
|
||||
"capacity": {
|
||||
"measured": true, "total_bytes": 1000, "free_bytes": 400,
|
||||
"available_bytes": 350, "used_bytes": 600
|
||||
},
|
||||
"batches": [{
|
||||
"stamp": "20261118T193001Z",
|
||||
"path": "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
"host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
"manifest_state": "ok",
|
||||
"actual_bytes": 4096, "apparent_bytes": 300, "file_count": 3,
|
||||
"sizes_complete": true,
|
||||
"databases": [{
|
||||
"name": "weknora_v090prod",
|
||||
"path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
"host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
"present": true, "failed": false, "in_manifest": true,
|
||||
"actual_bytes": 4096, "apparent_bytes": 250, "file_count": 2
|
||||
}]
|
||||
}],
|
||||
"totals": {
|
||||
"batch_count": 8, "database_count": 0,
|
||||
"actual_bytes": 12000000000, "apparent_bytes": 11141651752,
|
||||
"latest_stamp": "20261118T193001Z", "latest_actual_bytes": 1500000000,
|
||||
"complete": true
|
||||
},
|
||||
"incomplete_count": 0, "skipped": [], "truncated": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 示例中的容量/字节只说明字段形状,**不是现场读数**;候选现场已核实的事实只有:
|
||||
> 8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。单库 `696320` 是现场核对值,
|
||||
> 代码与测试都不写死。
|
||||
|
||||
### 语义与页面行为
|
||||
|
||||
| 条件 | API | 页面 |
|
||||
| --- | --- | --- |
|
||||
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
||||
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
||||
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
|
||||
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
|
||||
| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
|
||||
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
||||
|
||||
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
||||
`<batch>/<name>.dir`;重复、分隔符、`..`、`.incomplete` 一律拒绝。
|
||||
|
||||
## 3. 28189 候选 API 的最小接线
|
||||
|
||||
API 只挂**采集器输出目录**,不挂备份目录:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
|
||||
BACKUP_HOST_METADATA_MAX_AGE: 15m
|
||||
BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
|
||||
BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
|
||||
volumes:
|
||||
- /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
|
||||
```
|
||||
|
||||
- `BACKUP_HOST_METADATA_PATH` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
|
||||
(用 target + host path 拼)。缺任一拒绝启动,避免“看起来接线”或复制猜的路径。
|
||||
- 只挂元数据目录,`uid 1000` 只需要读 `metadata.json`,**不需要**进入 root:root 0700 的备份目录。
|
||||
- 采集器由宿主 root/备份所有者运行;不新增 API SSH 权限,不改备份目录权限。
|
||||
- 主机 cron 计划仍走 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;与快照独立。
|
||||
|
||||
### 部署后核验
|
||||
|
||||
宿主:
|
||||
|
||||
```sh
|
||||
ls -l /var/lib/knowledge-governance/backup-metadata/metadata.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d=json.load(open('/var/lib/knowledge-governance/backup-metadata/metadata.json'))
|
||||
print(d['schema_version'], d['collected_at'], d['complete'], d['root'], len(d['batches']))
|
||||
print(d['batches'][0]['stamp'], [x['name'] for x in d['batches'][0]['databases']][:5])
|
||||
PY
|
||||
```
|
||||
|
||||
API 容器:
|
||||
|
||||
```sh
|
||||
cat /var/lib/knowledge-governance/backup-host/metadata.json >/dev/null && echo readable
|
||||
curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
||||
```
|
||||
|
||||
字段核对(以现场为准,示例值不写死):
|
||||
|
||||
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
|
||||
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
|
||||
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
||||
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
|
||||
- `capacity.measured=true` 且与宿主 `df -B1 /srv/kb-backups` 一致。
|
||||
- 若 `complete=false`:先看 `metadata.error` 里的 permission/遍历错误;**不要**用
|
||||
`latest_actual_bytes` 或部分 `databases[].actual_bytes` 做容量判断(它们应为 null)。
|
||||
|
||||
## 4. 与主机计划读回的关系
|
||||
|
||||
- `/host`:SSH 读 cron/脚本/计划 + MANIFEST 最近一次摘要。
|
||||
- `/inventory`:宿主快照读全部批次、子库路径、实际占盘、容量。
|
||||
|
||||
前端分别加载:快照不可用时计划区仍可显示;SSH 连不上时历史区仍可用快照。历史与子库
|
||||
路径以快照为准,SSH 的“最近一次”只作历史参考。
|
||||
|
||||
## 5. 现有写路径(本次未改)
|
||||
|
||||
| 路径 | 写什么 | 权限 |
|
||||
| --- | --- | --- |
|
||||
| `PUT /api/v1/backup-schedule` | 计划写库;`apply=true` 时 SSH 下发 cron | 管理员 |
|
||||
| `POST /api/v1/backup-schedule/apply` | SSH 重写主机 cron/计划参数 | 管理员 |
|
||||
| `POST /api/v1/backup-schedule/run` | 在主机执行 `logical-backup.sh`(写备份目录/RDS dump) | 管理员 |
|
||||
| `BackupScheduleStore.SaveBackupSchedule` | 计划落库 | 服务内部 |
|
||||
| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 |
|
||||
| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 |
|
||||
|
||||
本接口与采集器没有写备份目录、删批次、改 cron 的代码路径。
|
||||
|
||||
## 6. 还需单独确认的后端写能力
|
||||
|
||||
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
|
||||
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
||||
3. 备份目录迁移/切换。
|
||||
4. 单库备份/单库恢复(现有 run 是整批)。
|
||||
5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。
|
||||
6. MANIFEST 修复/重建。
|
||||
7. 采集器安装/权限变更自动化(属部署与主机权限,必须人工批准)。
|
||||
8. 写操作角色细分(目前统一管理员)。
|
||||
@@ -255,20 +255,25 @@
|
||||
|
||||
## D. 系统设置
|
||||
|
||||
### D1 服务配置(测试 / 生产端点与 ID)
|
||||
- 入口:**系统设置 → 服务配置**(管理员)
|
||||
- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读
|
||||
- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试)
|
||||
### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库)
|
||||
- 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读)
|
||||
- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库;**两个方向都必须选择**)→ **保存该环境绑定**
|
||||
- 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库
|
||||
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
|
||||
- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
|
||||
- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
|
||||
- 单次任务连接:`TestBeginTaskPinsOneResolvedConnectionForAllCalls`;`TestPollUsesOneVerifiedConnectionForAllCalls`、`TestValidateUsesOneVerifiedConnectionForAllCalls`、`TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack`、`TestUploadUsesOneVerifiedConnectionForWrite`、`TestUploadRecoveryUsesTheSameVerifiedConnection`
|
||||
- 状态:✅ 本地验证(未做业务验收)
|
||||
|
||||
### D2 测试知识库绑定(对内 / 对外)
|
||||
- 入口:**系统设置 → 测试知识库绑定** → 选库 → 保存绑定
|
||||
- 期望:保存立即生效并重排"还没上传"的待入库项;对内 ≠ 对外
|
||||
- 状态:✅ 本期实测
|
||||
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
|
||||
- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断**
|
||||
- 期望:保留入库目标/封存源一致性对照与重新读取;不再提供第二个保存入口(保存统一走 D1)
|
||||
- 状态:✅ 诊断展示保留
|
||||
|
||||
### D3 生产知识库绑定(源库 → 目标库)
|
||||
- 入口:**系统设置 → 生产知识库绑定** → 对内/对外各选一个生产库
|
||||
- 期望:发布写入被冻结到该项的 `target_knowledge_base_id`;未绑定时按同 ID 语义并在契约检查处失败关闭
|
||||
- 状态:✅(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044)
|
||||
### D3 生产知识库绑定(折叠诊断;整库目标只读)
|
||||
- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断**
|
||||
- 期望:整库发布实际目标来自部署配置、只读;生产 090 工作区的 D1 保存只写文档级语义(源库 → 目标库),不触发整库发布或生产写入
|
||||
- 状态:✅ 诊断展示保留(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044)
|
||||
|
||||
### D4 存储与备份(整库逻辑备份的定时)★本期新增
|
||||
- 入口:**系统设置 → 存储与备份**(管理员)
|
||||
|
||||
@@ -56,8 +56,16 @@ LIBRARY_TARGET_INGRESS_URL 入口地址(恢复后要能 200)
|
||||
LIBRARY_TARGET_INGRESS_SERVICE Compose 里的入口闸门服务名
|
||||
LIBRARY_TARGET_INGRESS_DRAIN_FILE 闸门写排空证据的宿主机文件
|
||||
LIBRARY_TARGET_REDIS_ADDR/_PASSWORD/_DB 后台队列(asynq)地址
|
||||
LIBRARY_TARGET_INGRESS_MODE gate(缺省)或 none;none 只给没有闸门的测试栈
|
||||
LIBRARY_NO_INGRESS_ACK mode=none 时必须逐字符等于 test-only
|
||||
LIBRARY_TARGET_HEALTH_URL mode=none 时的健康探针(恢复后必须 200)
|
||||
```
|
||||
|
||||
`none` 是显式降档,不是默认:整栈(如 0.9.0 测试栈)没有入口闸门时,`none` + 确认串
|
||||
才允许缺入口三项,窗口里不调用任何闸门动作,`gate` 证据位置写
|
||||
`{"mode":"none","reason":"stack has no ingress gate (test-only)"}`;恢复以
|
||||
`LIBRARY_TARGET_HEALTH_URL` 返回 200 为准。缺省 `gate` 的行为与文案不变。
|
||||
|
||||
另外 `-source-s3-endpoint <URL>` 用来覆盖"源对象存储的访问入口":容器里写的
|
||||
`MINIO_ENDPOINT` 往往是服务名(`langfuse-minio:9000`),封存跑在宿主机上时解析不到,
|
||||
资源导出会失败(`read library resource`)。覆盖只换入口,桶与对象键不变;`status`
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# v0.7.1 整库发布的数据契约与覆盖边界
|
||||
|
||||
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关的独占审核是测试夹具,不代表生产已隔离;B22 控制读取角色是真实 SELECT-only PG 角色。
|
||||
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关按限定 key 工作,不要求整桶独占审核;B22 控制读取角色是真实 SELECT-only PG 角色。
|
||||
|
||||
## 1. 源 schema、历史身份与准入
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
- 真实v071历史catalog镜像对照及UUID/自然键矩阵在r11执行,隔离结论与外部当前目录采样分开。A04已识别嵌套引用有有限支持,旧外部cursor仍不自动转换,不因内部结构正例而升级整项。
|
||||
- r8/r9进程恢复历史证据只在原发送协议、不可变计划/receipt及相应场景前提不变时复用。本轮对schema/引用准入有收紧,不能把历史执行日志称为当前源码正式进程全链重跑;完整当前隔离适配器回归单列。
|
||||
- clean-finalization unknown保持held是安全行为,但未满足全部自动收敛要求。若要求自动完成,需要能绑定原写入、完整内容和代次的充分服务端证据;相同干净正文、人工猜测归属或放宽共享规则均不可替代。
|
||||
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。生产独占/ACL网络凭据、网关OSS业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
|
||||
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。网关真实 OSS 业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
|
||||
|
||||
## 6. 目录与唯一键的有限支持矩阵
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# 目标库隔离 ID 映射
|
||||
|
||||
同一 WeKnora 实例里可以有多个知识库。同步把源快照写进目标库时,如果沿用源库的 UUID 主键,
|
||||
第二个目标库会与实例里已有库的行撞主键(真实证据:2 knowledges / 2 chunks / 23 wiki_pages /
|
||||
17 wiki_folders 已存在于旧库),写入前的跨范围检查会拒绝整次同步。关闭检查等于让两个库共享身份,
|
||||
删除/恢复/校验会互相误伤,因此身份必须在目标侧派生。
|
||||
|
||||
## 映射规则
|
||||
|
||||
```
|
||||
digest = sha256("knowledge-governance/target-identity/v1" || tenant || kb || table || source_id)
|
||||
target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 variant/version 位)
|
||||
```
|
||||
|
||||
这是**本产品自定义的稳定 ID 算法**(`target_id_mode=scoped-sha256-v1`),只保证确定性与目标隔离;
|
||||
它不是标准 RFC 4122 UUIDv5(UUIDv5 用 SHA-1 + 标准 namespace),不要按 UUIDv5 互操作。
|
||||
|
||||
- 只绑定**稳定目标身份**(目标 tenant、目标 KB)与源身份,表名参与命名空间;
|
||||
- 不绑定 job、时间、快照版本等瞬态值:同一目标重复同步/重试/跨版本得到同一 ID;
|
||||
- 不同目标 KB、不同表得到不同 ID;
|
||||
- 源归档字节不变,映射只存在于目标侧派生视图(写集合、写入行、索引文档、校验预期);
|
||||
- 计划把策略持久化为 `target_id_mode=scoped-sha256-v1`:新进程按该字段重建映射,旧计划/写前镜像
|
||||
没有该字段则按原 ID 回放,绝不二次映射。
|
||||
|
||||
## 参与映射的表与字段
|
||||
|
||||
| 表 | 身份 | 引用字段 |
|
||||
|---|---|---|
|
||||
| knowledges | id | — |
|
||||
| chunks | id | knowledge_id, tag_id, parent_chunk_id, pre_chunk_id, next_chunk_id, relation_chunks, indirect_relation_chunks, metadata(仅精确匹配) |
|
||||
| knowledge_tags | id | — |
|
||||
| knowledge_tag_relations | (knowledge_id, tag_id) | 两个分量分别映射 |
|
||||
| wiki_folders | id | parent_id |
|
||||
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
|
||||
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
|
||||
| resource_bindings | id | owner_id(按 owner_type) |
|
||||
| resources | **不映射** | resource_id 保持共享身份 |
|
||||
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
|
||||
|
||||
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
|
||||
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
|
||||
|
||||
## 一致性边界
|
||||
|
||||
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
|
||||
- 索引计划的目标文档 ID 与 `_source` 引用同步映射,before-image(目标写前镜像)保持原样;
|
||||
- 恢复重放写前镜像时映射关闭,避免把目标原始 ID 再映射一次;
|
||||
- 资源对象路径/location_hash 仍由既有资源改写逻辑处理,不因 ID 映射而变化。
|
||||
@@ -4,12 +4,14 @@
|
||||
|
||||
`cmd/object-gateway` 提供 `kg-object-gateway-v1`,只监听 loopback;外部接入需要另行审核的 TLS 终结与网络隔离。治理 PG 保存不可变计划、grant、intent、逐版本 receipt 和 attempt→grant delivery。部署迁移身份显式应用 `internal/objectgateway/schema.sql`;启动不自动迁移。运行身份只授必要 SELECT/INSERT 和 scope 行 UPDATE,不授 DDL/TRUNCATE/证据修改或业务库写权限。
|
||||
|
||||
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶只能有一个受审核 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。
|
||||
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶在本网关内只使用一个 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。这不要求整桶只有本网关一个写者:别的服务可以在同一桶的其它 key 上正常读写。
|
||||
|
||||
数据认证端点:`POST /v1/acquire`、`/v1/resolve`、`/v1/execute`、`/v1/reconcile`、`/v1/observe`,以及 `GET /v1/capabilities`。所有请求核验协议和 scope。`capabilities.automatic_grants` 必须为真,正式 stack 才接受自动授权能力;未接控制源、只读角色权限异常、协议不符或不可达均拒绝,无直写回退。
|
||||
|
||||
PG 行锁负责原子准入,不是远端存储 fence。intent 必须持久提交后才发送一次请求;连接死亡、租约过期不清除未知 intent。任何未终态 intent 均阻止 scope 换 epoch。重复 operation 只读回执或精确对账,不重发 PUT;暂时查不到版本仍 held。删除必须绑定已确认 create 的精确 VersionID,不删 latest、不生成删除标记。
|
||||
|
||||
同 key 竞争按 key 判定,不按桶判定:create 前已存在任何版本 → 回执 `rejected` 且不修改该对象;PUT 后除精确版本读回外还核对当前 latest,若并发写者已产生更新的当前版本,则只按精确 VersionID 撤回本次写入,保留对方版本并返回冲突;读不到当前版本时保持 held,不删除、不猜测。版本化存储的 PUT 不是原子 create-if-absent,因此“本 key 多数情况下归本计划”不是存储层保证。
|
||||
|
||||
不可变证据表拒绝 UPDATE/DELETE/TRUNCATE。Ready 核 fsync、synchronous_commit、full_page_writes、主库可写及必要表/触发器;管理员与迁移身份仍是可信边界,触发器不能抵御 DBA 的 DDL。
|
||||
|
||||
## 正式控制交付路径
|
||||
@@ -54,13 +56,13 @@ SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`libr
|
||||
- `OBJECT_GATEWAY_ARCHIVE_ROOT`:原持久计划所在归档绝对路径,部署只读挂载。
|
||||
- `OBJECT_GATEWAY_TARGET_ID`:与正式 worker `LibraryTargetIdentity()` 完全相同的逻辑目标身份;不能用另一个环境的值。
|
||||
- `OBJECT_GATEWAY_PROVIDER`、`OBJECT_GATEWAY_ENDPOINT`、`OBJECT_GATEWAY_BUCKET`、`OBJECT_GATEWAY_REGION`:精确存储身份。
|
||||
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:仅网关持有的对象写凭据。
|
||||
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:网关持有的对象凭据,需在目标桶 PUT/GET/按版本 DELETE/列举版本。沿用现有 AK 即可,不要求另建独立只读或独占写凭据。
|
||||
- `OBJECT_GATEWAY_DATA_TOKEN`、`OBJECT_GATEWAY_CONTROL_TOKEN`:不同且至少 32 字节;普通 worker 仅持有 data token。
|
||||
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:独立审核者的 Ed25519 签名隔离证据,绑定协议、scope、gateway ID、时间窗及 writer/policy/拒写/排空摘要。审核私钥不能交给 worker 或网关。
|
||||
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:**已退役**。旧部署残留的值被忽略,不参与启动、Ready、每次 Execute 或能力判断;不需要管理员签发整桶独占证明,也不会因过期文件拒绝发布。
|
||||
|
||||
秘密只经服务环境/私有文件注入,不进 argv、URL 或日志。所有调用端错误都使用固定原因码。
|
||||
|
||||
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,部署必须使用独立只读凭据。
|
||||
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,可继续使用现有凭据,不再要求独立只读 OSS AK。
|
||||
|
||||
## 已关闭的本仓旁路
|
||||
|
||||
@@ -70,24 +72,34 @@ SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`libr
|
||||
- `librarystack` 不再为缺网关的 MinIO/S3 返回直写 writer。
|
||||
- `libraryctl` capture 的 S3 构造与读取保留;未把读取当作写入口禁用。
|
||||
|
||||
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;部署权限才负责防止外部旧进程直接调用存储。
|
||||
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;共享桶不要求撤除其它写者,跨写者的同 key 竞争按冲突/held 处理。
|
||||
|
||||
## 实测与未完成边界
|
||||
|
||||
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证。隔离审计 authority/故障注入仍是测试设施,不是生产权限证明。
|
||||
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证,以及共享桶下“无整桶证明启动 + 其它 key 并发写入 + 同 key 既有对象拒绝”的真实 PG/MinIO 用例。历史隔离审计 authority/故障注入是当时的测试设施,不是当前部署前置。
|
||||
|
||||
正式 worker 隔离进程证据:真实 Docker 入口闸门/队列、只读 worker 对象身份、独立治理读取角色、网关与业务 PG/ES/MinIO;首次 PG 后和对象提交后两次 SIGKILL,同一原 job/operation/plan 的三代 attempt 完成发布,原对象发送 epoch 与回执不变。隔离构建标签 `kg_isolated_drill` 仅把真实租约缩短至4秒,并拒绝非 loopback 一次性 r8 库;正常构建仍为10分钟。维护上游是无业务凭据的独立 HTTP 夹具,不是运行中的 WeKnora;签名证据绑定本次真实拒写/排空材料,不代表生产独占审核。
|
||||
|
||||
已补独立 `library.recover` 正式worker链、恢复中再次SIGKILL、完整before-image/CAS/精确版本读回,以及来源/目标/原job/计划/operation/任意队列身份拒绝。ES故障代理只转发真实ES并丢弃已提交响应,未伪造服务响应。
|
||||
|
||||
尚未完成:clean-finalization unknown的充分归属与自动收敛;独立运行环境只读对象凭据、ACL/网络和全部writer排空;网关真实OSS端到端;原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署独占分列,不把生产变更授权当成本机开发授权的前置。
|
||||
尚未完成:clean-finalization unknown的充分归属与自动收敛;网关真实 OSS 端到端与真实部署验收(父执行);原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署分列。
|
||||
|
||||
维护隔离、独占审核与 grant 是独立前置。配置 true、健康 200、测试自签 authority 都不能代替已部署拒写/排空证据。目前未签发真实环境独占证明,未改生产权限或上游 WeKnora 源码/Schema。
|
||||
整桶独占审核、全部 writer 排空、独立只读对象凭据已不再是发布前置;维护窗口内停目标写入容器并读回确认即可更新。网关按 key 拒绝冲突、精确版本回滚,但不承诺无关写者同时修改同一 key 时仍能自动完成——那种情况会明确冲突或 held,需要人工按回执处理。未改生产权限或上游 WeKnora 源码/Schema。
|
||||
|
||||
## 维护式更新(已采用)
|
||||
|
||||
目标测试 KB 的更新走维护窗口,不再要求证明整桶只有一个写者:
|
||||
|
||||
1. 停目标测试 WeKnora 的写入应用容器(只停该服务,不停机器人、适配器、共享 PG/ES 或其它 KB 的服务),并由容器状态/健康读回确认已停止。这是本轮文档化的运维步骤;代码侧没有新增停容器实现。
|
||||
2. 用既有维护/预备份链记录本次目标 KB/对象范围:实例级维护窗口与写者停写证据由 `internal/libraryfreeze` + `internal/librarymaintenance` 采集,`libraryctl capture`(页面入口 `POST /api/v1/library/captures`)完成闸门排空→停写者→导出快照并保留 `post_stop_digest`;不把通用主机备份当作 KB 预备份的替代。
|
||||
3. 用原 plan、原 WriteSet 摘要和限定对象清单走既有 `ProductionLibraryTarget.Apply`(经正式 worker owned attempt 与网关 grant)更新资源;网关沿用现有 AK,不换凭据、不签独占证明。
|
||||
4. 启动原容器,健康检查与页面业务验收;失败走既有 `library.recover`/`RestoreDrill` 恢复链按原预备份回放并启动原服务,不无限留停机。
|
||||
5. 无关服务与无关 key 全程不需要停;同 key 若仍有外部写者,按上节的冲突/held 处理:双方版本都保留,由人按证据处置,不自动合并。
|
||||
|
||||
部署需变更的组件:`object-gateway`(本候选镜像)、`worker`(同提交镜像),以及两者 env 中移除/留空已退役的 `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`。`api`、`web` 无协议变更,可不同步。journal、治理 PG 只读 authority、archive 与 target identity 配置保持不变。
|
||||
|
||||
## 部署与回退(未执行)
|
||||
|
||||
未来测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准。每批先冻结主机、桶、全部角色/STS/预签名写入口、端口/网络规则、影响、维护窗口与回滚;当前没有执行这些外部变更。
|
||||
测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准;本候选未在任一主机执行停机、备份、更新或启动。r5 的已完成 OSS 测试授权不能重复使用。
|
||||
|
||||
先关新写准入→排空并对账旧请求→撤旧直写权限/切只读身份并实测拒写→独立审核→批准的新限定对象验收→父复核,才可切业务客户端。r5 的已完成 OSS 测试授权不能重复使用。
|
||||
|
||||
回退先关准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。权限/网络回退须另批。当前整模块 INCOMPLETE,禁止部署部分候选。
|
||||
按“停目标写入容器→读回确认→备份目标 KB 范围→更新资源→启动→健康/页面验收”执行;失败按原备份恢复并启动原服务。回退先关新写准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。当前整模块仍未完成真实 OSS 端到端与 clean-finalization 收敛,禁止把本候选当作完整生产就绪。
|
||||
|
||||
+125
-28
@@ -3,6 +3,7 @@ package appconfig
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -46,16 +47,22 @@ type Config struct {
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
TestWeKnoraAPIKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// WeKnoraAllowPrivateHTTP 放行同网段 http(生产 18093 反代);只接受
|
||||
// RFC1918/回环/链路本地,公网 http 仍拒绝。监控探活与列库共用同一判定。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
|
||||
TestAutoReviewPolicy string
|
||||
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
|
||||
@@ -64,6 +71,12 @@ type Config struct {
|
||||
BackupHostTarget string
|
||||
BackupHostScriptDir string
|
||||
BackupHostRoot string
|
||||
// BackupHostMetadataPath 是容器内挂载的宿主 metadata.json(单次采集器的原子快照)。
|
||||
// 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
|
||||
BackupHostMetadataPath string
|
||||
BackupHostMetadataMaxAge time.Duration
|
||||
BackupHostReadonlyHostPath string
|
||||
BackupHostReadonlySource string
|
||||
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
|
||||
// (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库,
|
||||
// 不接受任何调用方传入的 URL;本功能**不使用凭据**。
|
||||
@@ -129,6 +142,11 @@ type Config struct {
|
||||
// 入口闸门:关入口与排空在它身上做(被代理服务自己不排空)。
|
||||
LibraryTargetIngressService string
|
||||
LibraryTargetIngressDrainFile string
|
||||
// 入口形态:gate(默认)或 none。none 只给整栈没有入口闸门的测试环境用,
|
||||
// 必须同时给 LibraryTargetNoIngressAck,且证据等级降一档并如实记录。
|
||||
LibraryTargetIngressMode string
|
||||
LibraryTargetNoIngressAck string
|
||||
LibraryTargetHealthURL string
|
||||
// 后台静默检查:目标队列 + 目标库(HTTP 排空不等于后台任务排空)。
|
||||
LibraryTargetRedisAddr string
|
||||
LibraryTargetRedisPassword string
|
||||
@@ -175,6 +193,10 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer")
|
||||
}
|
||||
embeddingDimension := int(embeddingDimension64)
|
||||
metadataMaxAge, err := durationOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_METADATA_MAX_AGE")), 15*time.Minute)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
|
||||
}
|
||||
config := Config{
|
||||
DatabaseURL: getenv("DATABASE_URL"),
|
||||
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
|
||||
@@ -197,6 +219,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
|
||||
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")),
|
||||
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
|
||||
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
|
||||
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
|
||||
@@ -213,6 +236,10 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
|
||||
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
|
||||
BackupHostMetadataPath: strings.TrimSpace(getenv("BACKUP_HOST_METADATA_PATH")),
|
||||
BackupHostMetadataMaxAge: metadataMaxAge,
|
||||
BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
|
||||
BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
@@ -247,19 +274,23 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
|
||||
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
|
||||
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
|
||||
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
|
||||
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
|
||||
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
|
||||
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
|
||||
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
|
||||
LibraryEmbeddingDimension: embeddingDimension,
|
||||
LibraryCapacityBudgetBytes: capacityBudget,
|
||||
LibraryRetentionVersions: retentionVersions,
|
||||
LibraryRetentionDays: retentionDays,
|
||||
LibraryExecutorStatusMaxAge: 2 * time.Minute,
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
LibraryTargetIngressMode: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_MODE")),
|
||||
// 确认串不 Trim:必须逐字符相等,多一个空格都算没确认。
|
||||
LibraryTargetNoIngressAck: getenv("LIBRARY_NO_INGRESS_ACK"),
|
||||
LibraryTargetHealthURL: strings.TrimSpace(getenv("LIBRARY_TARGET_HEALTH_URL")),
|
||||
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
|
||||
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
|
||||
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
|
||||
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
|
||||
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
|
||||
LibraryEmbeddingDimension: embeddingDimension,
|
||||
LibraryCapacityBudgetBytes: capacityBudget,
|
||||
LibraryRetentionVersions: retentionVersions,
|
||||
LibraryRetentionDays: retentionDays,
|
||||
LibraryExecutorStatusMaxAge: 2 * time.Minute,
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
}
|
||||
if config.DatabaseURL == "" {
|
||||
return Config{}, errors.New("DATABASE_URL is required")
|
||||
@@ -334,6 +365,15 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
|
||||
}
|
||||
}
|
||||
if raw := getenv("WEKNORA_ALLOW_PRIVATE_HTTP"); raw != "" {
|
||||
config.WeKnoraAllowPrivateHTTP, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("WEKNORA_ALLOW_PRIVATE_HTTP: %w", err)
|
||||
}
|
||||
}
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
|
||||
config.PPScanEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
@@ -387,9 +427,35 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) {
|
||||
return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)")
|
||||
}
|
||||
// 入口形态:缺省 gate,行为与之前完全一致。none 只给整栈没有入口闸门的
|
||||
// 测试环境用,必须显式确认;确认串逐字符相等,多一个空格都算没确认。
|
||||
if config.LibraryTargetIngressMode == "" {
|
||||
config.LibraryTargetIngressMode = "gate"
|
||||
}
|
||||
switch config.LibraryTargetIngressMode {
|
||||
case "gate", "none":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 gate 或 none",
|
||||
config.LibraryTargetIngressMode)
|
||||
}
|
||||
noGate := config.LibraryTargetIngressMode == "none"
|
||||
if noGate && config.LibraryTargetNoIngressAck != "test-only" {
|
||||
return Config{}, errors.New("no-gate 维护必须显式确认:LIBRARY_NO_INGRESS_ACK 必须逐字符等于 test-only,拒绝启动")
|
||||
}
|
||||
if !noGate && config.LibraryTargetNoIngressAck != "" {
|
||||
return Config{}, errors.New("LIBRARY_NO_INGRESS_ACK 只在 LIBRARY_TARGET_INGRESS_MODE=none 下有效")
|
||||
}
|
||||
if config.LibraryTargetHealthURL != "" {
|
||||
parsed, err := url.Parse(config.LibraryTargetHealthURL)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") ||
|
||||
parsed.Host == "" || parsed.User != nil {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_HEALTH_URL 必须是 http(s) 地址且不带凭据")
|
||||
}
|
||||
}
|
||||
// 目标维护要么完整配置,要么完全不配;半配置会让窗口"看起来存在"却挡不住目标。
|
||||
targetSet := config.LibraryTargetInstance != "" || config.LibraryTargetProject != "" ||
|
||||
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != ""
|
||||
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != "" ||
|
||||
noGate || config.LibraryTargetHealthURL != ""
|
||||
if targetSet {
|
||||
missing := make([]string, 0, 4)
|
||||
if config.LibraryTargetInstance == "" {
|
||||
@@ -401,16 +467,21 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if len(config.LibraryTargetWriters) == 0 {
|
||||
missing = append(missing, "LIBRARY_TARGET_WRITERS")
|
||||
}
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
if noGate {
|
||||
// 没有闸门可声明:健康探针是唯一能证明"目标回来了"的必需项。
|
||||
if config.LibraryTargetHealthURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
|
||||
}
|
||||
} else if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetJournalRoot == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
if !noGate && config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
}
|
||||
if config.LibraryTargetIngressDrainFile == "" {
|
||||
if !noGate && config.LibraryTargetIngressDrainFile == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
|
||||
}
|
||||
if config.LibraryTargetRedisAddr == "" {
|
||||
@@ -419,13 +490,17 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if len(missing) > 0 {
|
||||
return Config{}, fmt.Errorf("目标维护配置不完整:缺少 %s", strings.Join(missing, "、"))
|
||||
}
|
||||
if noGate && (config.LibraryTargetIngressURL != "" || config.LibraryTargetIngressService != "" ||
|
||||
config.LibraryTargetIngressDrainFile != "") {
|
||||
return Config{}, errors.New("no-gate 维护不得同时配置入口地址/闸门服务/排空文件:要么有闸门,要么明确没有")
|
||||
}
|
||||
if !filepath.IsAbs(config.LibraryTargetJournalRoot) {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_JOURNAL_ROOT 必须是绝对路径")
|
||||
}
|
||||
if !filepath.IsAbs(config.LibraryTargetDockerSocket) {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_DOCKER_SOCKET 必须是绝对路径")
|
||||
}
|
||||
if !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
|
||||
if !noGate && !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_INGRESS_DRAIN_FILE 必须是绝对路径")
|
||||
}
|
||||
if len(config.LibraryTargetNonWriters) == 0 {
|
||||
@@ -466,6 +541,28 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
|
||||
}
|
||||
config.TestAutoReviewPolicy = string(normalizedPolicy)
|
||||
// 宿主采集器快照接线与生产发布开关无关:测试栈也要先读通历史批次。
|
||||
if config.BackupHostMetadataPath != "" && !filepath.IsAbs(config.BackupHostMetadataPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostMetadataPath != "" && config.BackupHostReadonlyHostPath == "" {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when metadata path is set")
|
||||
}
|
||||
if config.BackupHostMetadataPath == "" &&
|
||||
(config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_PATH is required when host path/source is set")
|
||||
}
|
||||
if config.BackupHostMetadataMaxAge <= 0 || config.BackupHostMetadataMaxAge > 24*time.Hour {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be between 1s and 24h")
|
||||
}
|
||||
for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
return Config{}, errors.New("backup inventory display path/source contains control characters")
|
||||
}
|
||||
}
|
||||
if config.ProductionReleaseRequestsEnabled {
|
||||
// 目标主机凭据要么都给要么都不给:只给一半会把"未接线"伪装成"已接线"。
|
||||
if (config.BackupHostSSHConfig == "") != (config.BackupHostTarget == "") {
|
||||
|
||||
@@ -53,6 +53,49 @@ func TestLoadUsesSafeDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadValidatesBackupInventoryMount(t *testing.T) {
|
||||
base := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
load := func(extra map[string]string) (Config, error) {
|
||||
values := map[string]string{}
|
||||
for key, value := range base {
|
||||
values[key] = value
|
||||
}
|
||||
for key, value := range extra {
|
||||
values[key] = value
|
||||
}
|
||||
return Load(func(key string) string { return values[key] })
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "relative/path"}); err == nil {
|
||||
t.Fatal("relative metadata path must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json"}); err == nil {
|
||||
t.Fatal("metadata path without host root must be rejected (paths must not be guessed)")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
|
||||
t.Fatal("host path without metadata path must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{
|
||||
"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_METADATA_MAX_AGE": "nope",
|
||||
}); err == nil {
|
||||
t.Fatal("invalid metadata max age must be rejected")
|
||||
}
|
||||
config, err := load(map[string]string{
|
||||
"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_METADATA_MAX_AGE": "5m",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("valid inventory snapshot config rejected: %v", err)
|
||||
}
|
||||
if config.BackupHostMetadataPath == "" || config.BackupHostReadonlyHostPath == "" ||
|
||||
config.BackupHostReadonlySource == "" || config.BackupHostMetadataMaxAge != 5*time.Minute {
|
||||
t.Fatalf("inventory snapshot fields lost: %#v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseURL(t *testing.T) {
|
||||
if _, err := Load(func(string) string { return "" }); err == nil {
|
||||
t.Fatal("Load() error = nil, want missing DATABASE_URL error")
|
||||
|
||||
@@ -73,12 +73,13 @@ func (r LibraryWorkerRole) LibraryJobKinds() []string {
|
||||
switch r {
|
||||
case LibraryWorkerRoleReleaseExecutor:
|
||||
return []string{string(governance.LibraryJobSync), string(governance.LibraryJobRestore),
|
||||
string(governance.LibraryJobRecover), string(governance.LibraryJobBaseline)}
|
||||
string(governance.LibraryJobRecover), string(governance.LibraryJobBaseline),
|
||||
string(governance.LibraryJobVerify)}
|
||||
case LibraryWorkerRoleCapture:
|
||||
return []string{string(governance.LibraryJobSeal)}
|
||||
default:
|
||||
return []string{string(governance.LibraryJobSeal), string(governance.LibraryJobSync),
|
||||
string(governance.LibraryJobRestore), string(governance.LibraryJobRecover),
|
||||
string(governance.LibraryJobBaseline)}
|
||||
string(governance.LibraryJobBaseline), string(governance.LibraryJobVerify)}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,13 +63,14 @@ func TestLoadRejectsUnknownLibraryWorkerRole(t *testing.T) {
|
||||
// 每个角色收拾哪些 kind、谁拥有 DDL,都必须互斥且覆盖完整。
|
||||
func TestLibraryWorkerRoleOwnershipMaps(t *testing.T) {
|
||||
release := LibraryWorkerRoleReleaseExecutor
|
||||
if got := release.LibraryJobKinds(); len(got) != 4 || got[0] != "sync" || got[1] != "restore" || got[2] != "recover" || got[3] != "baseline" {
|
||||
if got := release.LibraryJobKinds(); len(got) != 5 || got[0] != "sync" || got[1] != "restore" ||
|
||||
got[2] != "recover" || got[3] != "baseline" || got[4] != "verify" {
|
||||
t.Fatalf("release-executor kinds = %v", got)
|
||||
}
|
||||
if got := LibraryWorkerRoleCapture.LibraryJobKinds(); len(got) != 1 || got[0] != "seal" {
|
||||
t.Fatalf("capture kinds = %v", got)
|
||||
}
|
||||
if got := LibraryWorkerRoleFull.LibraryJobKinds(); len(got) != 5 {
|
||||
if got := LibraryWorkerRoleFull.LibraryJobKinds(); len(got) != 6 {
|
||||
t.Fatalf("full kinds = %v", got)
|
||||
}
|
||||
for _, role := range []LibraryWorkerRole{LibraryWorkerRoleFull, LibraryWorkerRoleCapture} {
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -127,12 +129,81 @@ func (r *Runner) runRemote(ctx context.Context, timeout time.Duration, remote st
|
||||
if ctx.Err() != nil {
|
||||
return text, fmt.Errorf("ssh %s 超时(%s)", r.config.Target, timeout)
|
||||
}
|
||||
// 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。
|
||||
return text, fmt.Errorf("ssh %s 执行失败: %s", r.config.Target, firstLines(text, 6))
|
||||
// 连接层失败与主机侧命令失败必须分开说:前者连脚本都没跑,
|
||||
// 任何"脚本缺失/计划未下发"都是把未观测当成事实。
|
||||
return text, hostFailure(r.config.Target, text)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// hostFailure 把 ssh 的非零退出分成两类:连不上,和连上了但远端命令失败。
|
||||
func hostFailure(target, text string) error {
|
||||
if connectionFailurePattern.MatchString(text) {
|
||||
return fmt.Errorf("目标主机 %s 不可达(%s);未执行任何主机侧脚本,脚本与计划状态未知",
|
||||
target, firstLines(text, 3))
|
||||
}
|
||||
// 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。
|
||||
return fmt.Errorf("已连上 %s,但主机侧命令失败: %s", target, firstLines(text, 6))
|
||||
}
|
||||
|
||||
// connectionFailurePattern 是 OpenSSH 客户端在"根本没建立连接"时打的原文。
|
||||
// 只有命中它才允许说"不可达";其余非零退出属于远端命令自己的失败。
|
||||
var connectionFailurePattern = regexp.MustCompile(`(?i)ssh: connect to host|Operation timed out|Connection timed out|Connection refused|Connection reset by peer|No route to host|Network is unreachable|Could not resolve hostname|Host key verification failed|Permission denied|Connection closed by`)
|
||||
|
||||
// Endpoint 读回挂载的 ssh 配置里本别名真实拨号的 host:port。
|
||||
// 页面必须能说清"现在连的是哪个地址"——只显示别名时,改错文件也看不出来。
|
||||
func (r *Runner) Endpoint() string {
|
||||
if r == nil || r.config.SSHConfig == "" || r.config.Target == "" {
|
||||
return ""
|
||||
}
|
||||
raw, err := os.ReadFile(r.config.SSHConfig)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
host, port := sshConfigEndpoint(string(raw), r.config.Target)
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
if port == "" {
|
||||
port = "22"
|
||||
}
|
||||
return net.JoinHostPort(host, port)
|
||||
}
|
||||
|
||||
// sshConfigEndpoint 解析 `Host <alias>` 段的 HostName/Port(首个匹配段生效)。
|
||||
// 只做"页面显示用"的最小解析,不替代 ssh 自己的配置语义。
|
||||
func sshConfigEndpoint(config, alias string) (string, string) {
|
||||
host, port := "", ""
|
||||
active := false
|
||||
for _, line := range strings.Split(config, "\n") {
|
||||
fields := strings.Fields(strings.TrimSpace(line))
|
||||
if len(fields) == 0 || strings.HasPrefix(fields[0], "#") {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(fields[0])
|
||||
if key == "host" {
|
||||
active = false
|
||||
for _, pattern := range fields[1:] {
|
||||
if pattern == alias {
|
||||
active = true
|
||||
break
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !active || len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
switch key {
|
||||
case "hostname":
|
||||
host = strings.Trim(fields[1], `"`)
|
||||
case "port":
|
||||
port = strings.Trim(fields[1], `"`)
|
||||
}
|
||||
}
|
||||
return host, port
|
||||
}
|
||||
|
||||
var scheduleAppliedPattern = regexp.MustCompile(
|
||||
`SCHEDULE_APPLIED enabled=(\d)(?: time=(\S+))?(?: days=(\d+))?(?: months=(\d+))?(?: next=(\S+))?(?: cron=(\S+))?`)
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package backuphost
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -188,6 +190,41 @@ func TestRunnerSurfacesHostFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 现场原错:ssh: connect to host 120.76.217.51 port 22: Operation timed out。
|
||||
// 连不上时脚本根本没跑,只能说"不可达";断言配对的反面:不能说脚本缺失。
|
||||
func TestHostFailureSeparatesUnreachableFromRemoteCommand(t *testing.T) {
|
||||
unreachable := hostFailure("weknora-test", "ssh: connect to host 120.76.217.51 port 22: Operation timed out")
|
||||
if !strings.Contains(unreachable.Error(), "不可达") || !strings.Contains(unreachable.Error(), "Operation timed out") {
|
||||
t.Fatalf("连接超时应报不可达并带原错: %v", unreachable)
|
||||
}
|
||||
if strings.Contains(unreachable.Error(), "主机侧命令失败") || strings.Contains(unreachable.Error(), "脚本缺失") {
|
||||
t.Fatalf("连接失败不能报成远端命令/脚本问题: %v", unreachable)
|
||||
}
|
||||
remote := hostFailure("weknora-test", "bash: /opt/weknora-test/logical-backup.sh: No such file or directory")
|
||||
if !strings.Contains(remote.Error(), "已连上") || !strings.Contains(remote.Error(), "No such file") {
|
||||
t.Fatalf("已连接但脚本失败时应原样带回原因: %v", remote)
|
||||
}
|
||||
if strings.Contains(remote.Error(), "不可达") {
|
||||
t.Fatalf("已连上就不能说不可达: %v", remote)
|
||||
}
|
||||
}
|
||||
|
||||
// 页面要能说清"实际拨号的地址",否则改错 ssh_config 也看不出来。
|
||||
func TestRunnerEndpointReadsDialedHostPort(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "ssh_config")
|
||||
config := "Host other\n HostName 10.0.0.9\n Port 2222\n\nHost weknora-test\n HostName 100.85.111.121\n HostKeyAlias 120.76.217.51\n"
|
||||
if err := os.WriteFile(path, []byte(config), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := New(Config{SSHConfig: path, Target: "weknora-test", ScriptDir: "/opt/weknora-test"})
|
||||
if got := runner.Endpoint(); got != "100.85.111.121:22" {
|
||||
t.Fatalf("应报真实拨号地址(默认 22),得到 %q", got)
|
||||
}
|
||||
if got := New(Config{SSHConfig: filepath.Join(t.TempDir(), "missing"), Target: "weknora-test"}).Endpoint(); got != "" {
|
||||
t.Fatalf("配置文件不可读时应返回空,不猜地址,得到 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerRunNowReadsBackLastRun(t *testing.T) {
|
||||
calls := 0
|
||||
runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) {
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
// Package backupinventory 读取**宿主采集器**产出的备份元数据快照。
|
||||
//
|
||||
// 为什么不在 API 里遍历备份目录:备份目录通常是 root:root 0700,API 容器用户
|
||||
// 没有进入权限;容器里遍历只能得到 permission denied 的部分字节,绝不能把部分
|
||||
// 计数当成实际占盘。这里只读宿主进程原子写出的 metadata.json,并校验 schema、
|
||||
// 批次路径、主机根、时效与完整性。API 不接触备份目录,也不借用 SSH/容器特权。
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SchemaVersion = 1
|
||||
defaultMaxAge = 15 * time.Minute
|
||||
defaultMaxBytes = 16 << 20
|
||||
futureTolerance = 2 * time.Minute
|
||||
measurementLabel = "host_collector"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
// MetadataPath 是 API 容器内挂载的 metadata.json(宿主采集器原子写出)。
|
||||
MetadataPath string
|
||||
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
||||
HostRoot string
|
||||
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
||||
Source string
|
||||
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
||||
MaxAge time.Duration
|
||||
// MaxBytes 防止异常大文件拖死 API。
|
||||
MaxBytes int64
|
||||
}
|
||||
|
||||
type ManifestState string
|
||||
|
||||
const (
|
||||
ManifestOK ManifestState = "ok"
|
||||
ManifestMissing ManifestState = "missing"
|
||||
ManifestInvalid ManifestState = "invalid"
|
||||
)
|
||||
|
||||
type MetadataInfo struct {
|
||||
Configured bool `json:"configured"`
|
||||
Present bool `json:"present"`
|
||||
Valid bool `json:"valid"`
|
||||
Fresh bool `json:"fresh"`
|
||||
Complete bool `json:"complete"`
|
||||
Path string `json:"path"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
AgeSeconds int64 `json:"age_seconds"`
|
||||
MaxAgeSeconds int64 `json:"max_age_seconds"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Generation string `json:"generation"`
|
||||
Host string `json:"host"`
|
||||
CollectorVersion string `json:"collector_version"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type MountInfo struct {
|
||||
ContainerRoot string `json:"container_root"`
|
||||
MountVerified bool `json:"mount_verified"`
|
||||
LivesOnContainerRoot bool `json:"lives_on_container_root"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Evidence string `json:"evidence"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Device string `json:"device"`
|
||||
FSType string `json:"fs_type"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Capacity struct {
|
||||
Measured bool `json:"measured"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
UsedBytes int64 `json:"used_bytes"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Database struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
}
|
||||
|
||||
type Batch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
ManifestState ManifestState `json:"manifest_state"`
|
||||
ManifestPath string `json:"manifest_path"`
|
||||
ManifestError string `json:"manifest_error,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
SizesComplete bool `json:"sizes_complete"`
|
||||
SizesError string `json:"sizes_error,omitempty"`
|
||||
Databases []Database `json:"databases"`
|
||||
}
|
||||
|
||||
type Skipped struct {
|
||||
Name string `json:"name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type Totals struct {
|
||||
BatchCount int `json:"batch_count"`
|
||||
DatabaseCount int `json:"database_count"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
LatestStamp string `json:"latest_stamp"`
|
||||
LatestActualBytes *int64 `json:"latest_actual_bytes"`
|
||||
Complete bool `json:"complete"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Wired bool `json:"wired"`
|
||||
Metadata MetadataInfo `json:"metadata"`
|
||||
Root string `json:"root"`
|
||||
HostRoot string `json:"host_root"`
|
||||
Source string `json:"source"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Measurement string `json:"measurement"`
|
||||
Mount MountInfo `json:"mount"`
|
||||
Capacity Capacity `json:"capacity"`
|
||||
Batches []Batch `json:"batches"`
|
||||
Totals Totals `json:"totals"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
type Reader struct {
|
||||
config Config
|
||||
now func() time.Time
|
||||
read func(string) ([]byte, error)
|
||||
}
|
||||
|
||||
func New(config Config) *Reader {
|
||||
if config.MaxAge <= 0 {
|
||||
config.MaxAge = defaultMaxAge
|
||||
}
|
||||
if config.MaxBytes <= 0 {
|
||||
config.MaxBytes = defaultMaxBytes
|
||||
}
|
||||
return &Reader{config: config, now: time.Now, read: os.ReadFile}
|
||||
}
|
||||
|
||||
func (r *Reader) Available() bool {
|
||||
return r != nil && strings.TrimSpace(r.config.MetadataPath) != ""
|
||||
}
|
||||
|
||||
// ---- 宿主快照文件(collector 的输出;只读、字段可验证) ----
|
||||
|
||||
type metadata struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
CollectorVersion string `json:"collector_version"`
|
||||
Generation string `json:"generation"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
Host string `json:"host"`
|
||||
Source string `json:"source"`
|
||||
Root string `json:"root"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
Filesystem metadataFilesystem `json:"filesystem"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Batches []metadataBatch `json:"batches"`
|
||||
}
|
||||
|
||||
type metadataFilesystem struct {
|
||||
MountPoint string `json:"mount_point"`
|
||||
MountSource string `json:"mount_source"`
|
||||
FSType string `json:"fs_type"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
}
|
||||
|
||||
type metadataBatch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
ManifestState string `json:"manifest_state"`
|
||||
ManifestError string `json:"manifest_error"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
Databases []metadataDatabase `json:"databases"`
|
||||
}
|
||||
|
||||
type metadataDatabase struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
}
|
||||
|
||||
// Snapshot 只返回可验证的事实:陈旧/缺失/不完整一律不给批次字节与容量。
|
||||
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
|
||||
snapshot := Snapshot{
|
||||
Wired: r.Available(),
|
||||
Measurement: measurementLabel,
|
||||
Batches: []Batch{},
|
||||
Skipped: []Skipped{},
|
||||
ObservedAt: r.observedAt(),
|
||||
Metadata: MetadataInfo{
|
||||
Configured: r.Available(),
|
||||
MaxAgeSeconds: int64(r.config.MaxAge / time.Second),
|
||||
},
|
||||
}
|
||||
if r == nil || !r.Available() {
|
||||
snapshot.Metadata.Error = "元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)"
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Metadata.Path = r.config.MetadataPath
|
||||
snapshot.HostRoot = r.config.HostRoot
|
||||
snapshot.Source = r.config.Source
|
||||
if ctx.Err() != nil {
|
||||
snapshot.Metadata.Error = "读取被取消:" + ctx.Err().Error()
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
raw, err := r.read(r.config.MetadataPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
snapshot.Metadata.Error = "宿主元数据快照不存在:需要先运行 collect_backup_metadata.py"
|
||||
} else {
|
||||
snapshot.Metadata.Error = "宿主元数据快照不可读:" + err.Error()
|
||||
}
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Metadata.Present = true
|
||||
if int64(len(raw)) > r.config.MaxBytes {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据快照超过 %d 字节读取上限", r.config.MaxBytes))
|
||||
}
|
||||
var file metadata
|
||||
if err := json.Unmarshal(raw, &file); err != nil {
|
||||
return invalid(snapshot, "元数据快照无法解析:"+err.Error())
|
||||
}
|
||||
snapshot.Metadata.SchemaVersion = file.SchemaVersion
|
||||
snapshot.Metadata.Generation = file.Generation
|
||||
snapshot.Metadata.Host = file.Host
|
||||
snapshot.Metadata.CollectorVersion = file.CollectorVersion
|
||||
snapshot.Metadata.CollectedAt = file.CollectedAt
|
||||
snapshot.Metadata.Complete = file.Complete
|
||||
if file.Source != "" {
|
||||
snapshot.Source = file.Source
|
||||
}
|
||||
if file.SchemaVersion != SchemaVersion {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 schema_version=%d,API 只支持 %d", file.SchemaVersion, SchemaVersion))
|
||||
}
|
||||
collectedAt, err := time.Parse(time.RFC3339, file.CollectedAt)
|
||||
if err != nil {
|
||||
return invalid(snapshot, "元数据 collected_at 非法:"+file.CollectedAt)
|
||||
}
|
||||
age := r.now().UTC().Sub(collectedAt.UTC())
|
||||
if age < -futureTolerance {
|
||||
return invalid(snapshot, "元数据 collected_at 在未来,拒绝使用")
|
||||
}
|
||||
snapshot.Metadata.AgeSeconds = int64(age / time.Second)
|
||||
if age > r.config.MaxAge {
|
||||
snapshot.Metadata.Fresh = false
|
||||
return invalid(snapshot, fmt.Sprintf("元数据已陈旧:采集于 %s,超过 %s", file.CollectedAt, r.config.MaxAge))
|
||||
}
|
||||
snapshot.Metadata.Fresh = true
|
||||
if strings.TrimSpace(r.config.HostRoot) == "" {
|
||||
return invalid(snapshot, "宿主根路径未配置:无法校验批次路径")
|
||||
}
|
||||
expectedRoot := path.Clean(strings.TrimSpace(r.config.HostRoot))
|
||||
snapshot.HostRoot = expectedRoot
|
||||
root := strings.TrimSpace(file.Root)
|
||||
if !path.IsAbs(root) || path.Clean(root) != root {
|
||||
return invalid(snapshot, "元数据 root 不是规范绝对路径:"+root)
|
||||
}
|
||||
if root != expectedRoot {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
|
||||
}
|
||||
snapshot.Root = root
|
||||
if err := validateBatches(root, file.Batches); err != nil {
|
||||
return invalid(snapshot, err.Error())
|
||||
}
|
||||
snapshot.Metadata.Valid = true
|
||||
snapshot.IncompleteCount = file.IncompleteCount
|
||||
snapshot.Skipped = append(snapshot.Skipped, file.Skipped...)
|
||||
snapshot.Truncated = file.Truncated
|
||||
snapshot.Mount = MountInfo{
|
||||
Evidence: "宿主采集器上报:" + file.Host,
|
||||
MountPoint: file.Filesystem.MountPoint,
|
||||
Device: file.Filesystem.MountSource,
|
||||
FSType: file.Filesystem.FSType,
|
||||
ReadOnly: file.Filesystem.ReadOnly,
|
||||
}
|
||||
if file.Filesystem.MountPoint == "" || !path.IsAbs(file.Filesystem.MountPoint) {
|
||||
snapshot.Mount.Error = "宿主采集器没有给出文件系统挂载点"
|
||||
} else if root != file.Filesystem.MountPoint && !strings.HasPrefix(root, strings.TrimSuffix(file.Filesystem.MountPoint, "/")+"/") {
|
||||
snapshot.Mount.Error = "批次根不在采集器上报的挂载点下"
|
||||
} else {
|
||||
snapshot.Mount.MountVerified = true
|
||||
snapshot.Mount.Evidence = fmt.Sprintf("宿主采集器:%s 挂在 %s(%s),API 不遍历备份目录",
|
||||
file.Filesystem.MountSource, file.Filesystem.MountPoint, file.Filesystem.FSType)
|
||||
}
|
||||
|
||||
// 快照不完整/截断:路径与清单状态可展示,但所有字节与容量一律未知,
|
||||
// 绝不用部分 counts 或完整批次的局部字节拼总量。
|
||||
complete := file.Complete && !file.Truncated && snapshot.Mount.MountVerified && allBatchesComplete(file.Batches)
|
||||
if !complete {
|
||||
snapshot.Metadata.Complete = false
|
||||
snapshot.Metadata.Error = incompleteReason(file)
|
||||
snapshot.Capacity = Capacity{Error: "采集快照不完整:容量与占盘未知"}
|
||||
snapshot.Mount.MountVerified = false
|
||||
snapshot.Mount.Error = "采集快照不完整,不能据此判定文件系统与占盘"
|
||||
snapshot.Batches = projectBatches(root, file.Batches, false)
|
||||
snapshot.Totals = totals(snapshot.Batches, false)
|
||||
snapshot.Error = ""
|
||||
return snapshot
|
||||
}
|
||||
|
||||
snapshot.Metadata.Complete = true
|
||||
snapshot.Capacity = projectCapacity(file.Filesystem)
|
||||
snapshot.Batches = projectBatches(root, file.Batches, true)
|
||||
snapshot.Totals = totals(snapshot.Batches, true)
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (r *Reader) observedAt() string {
|
||||
if r == nil || r.now == nil {
|
||||
return ""
|
||||
}
|
||||
return r.now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func invalid(snapshot Snapshot, reason string) Snapshot {
|
||||
snapshot.Metadata.Valid = false
|
||||
snapshot.Metadata.Complete = false
|
||||
snapshot.Metadata.Error = reason
|
||||
snapshot.Error = reason
|
||||
snapshot.Batches = []Batch{}
|
||||
snapshot.Capacity = Capacity{Error: reason}
|
||||
snapshot.Totals = Totals{}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func incompleteReason(file metadata) string {
|
||||
if len(file.Errors) > 0 {
|
||||
return "采集不完整:" + strings.Join(limit(file.Errors, 3), ";")
|
||||
}
|
||||
for _, batch := range file.Batches {
|
||||
if len(batch.Errors) > 0 {
|
||||
return "采集不完整:" + strings.Join(limit(batch.Errors, 3), ";")
|
||||
}
|
||||
}
|
||||
return "采集不完整:存在无法遍历/统计的目录,占盘与容量未知"
|
||||
}
|
||||
|
||||
func limit(items []string, n int) []string {
|
||||
if len(items) <= n {
|
||||
return items
|
||||
}
|
||||
return items[:n]
|
||||
}
|
||||
|
||||
func allBatchesComplete(batches []metadataBatch) bool {
|
||||
for _, batch := range batches {
|
||||
if !batch.Complete || batch.ActualBytes == nil || batch.ApparentBytes == nil || batch.FileCount == nil {
|
||||
return false
|
||||
}
|
||||
for _, database := range batch.Databases {
|
||||
if database.ActualBytes == nil || database.ApparentBytes == nil || database.FileCount == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 校验的是"快照里的路径能否被安全地当成这台主机的批次/子库":
|
||||
// 根必须精确匹配配置,批次必须精确等于 root/<stamp>,子库必须精确等于
|
||||
// batch/<name>.dir,且不允许重复、分隔符、.incomplete。
|
||||
func validateBatches(root string, batches []metadataBatch) error {
|
||||
seen := map[string]bool{}
|
||||
for _, batch := range batches {
|
||||
stamp := strings.TrimSpace(batch.Stamp)
|
||||
if err := safeSegment(stamp); err != nil {
|
||||
return fmt.Errorf("批次名不合法:%q(%v)", stamp, err)
|
||||
}
|
||||
if strings.HasSuffix(stamp, ".incomplete") {
|
||||
return fmt.Errorf("批次 %q 是未完成目录,不应进入快照", stamp)
|
||||
}
|
||||
if seen[stamp] {
|
||||
return fmt.Errorf("批次 %q 重复", stamp)
|
||||
}
|
||||
seen[stamp] = true
|
||||
expected := path.Join(root, stamp)
|
||||
if batch.Path != expected || !path.IsAbs(batch.Path) {
|
||||
return fmt.Errorf("批次 %q 路径 %q 不等于 %q", stamp, batch.Path, expected)
|
||||
}
|
||||
switch ManifestState(batch.ManifestState) {
|
||||
case ManifestOK, ManifestMissing, ManifestInvalid:
|
||||
default:
|
||||
return fmt.Errorf("批次 %q 的 manifest_state 不认识:%q", stamp, batch.ManifestState)
|
||||
}
|
||||
databaseSeen := map[string]bool{}
|
||||
for _, database := range batch.Databases {
|
||||
name := strings.TrimSpace(database.Name)
|
||||
if err := safeSegment(name); err != nil {
|
||||
return fmt.Errorf("批次 %q 子库名不合法:%q", stamp, name)
|
||||
}
|
||||
if databaseSeen[name] {
|
||||
return fmt.Errorf("批次 %q 子库 %q 重复", stamp, name)
|
||||
}
|
||||
databaseSeen[name] = true
|
||||
expectedDir := path.Join(expected, name+".dir")
|
||||
if database.DirName != name+".dir" || database.Path != expectedDir || !path.IsAbs(database.Path) {
|
||||
return fmt.Errorf("批次 %q 子库 %q 路径不合法:%q", stamp, name, database.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeSegment(value string) error {
|
||||
if value == "" || value == "." || value == ".." {
|
||||
return errors.New("空值或相对路径")
|
||||
}
|
||||
for _, r := range value {
|
||||
if r == '/' || r == '\\' || r == 0 || r == '\n' || r == '\r' {
|
||||
return errors.New("包含路径分隔符或控制字符")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func projectBatches(root string, batches []metadataBatch, complete bool) []Batch {
|
||||
result := make([]Batch, 0, len(batches))
|
||||
for _, batch := range batches {
|
||||
item := Batch{
|
||||
Stamp: batch.Stamp,
|
||||
Path: path.Join(root, batch.Stamp),
|
||||
HostPath: path.Join(root, batch.Stamp),
|
||||
ManifestState: ManifestState(batch.ManifestState),
|
||||
ManifestPath: path.Join(root, batch.Stamp, "MANIFEST.json"),
|
||||
ManifestError: batch.ManifestError,
|
||||
Kind: batch.Kind,
|
||||
CreatedAt: batch.CreatedAt,
|
||||
StartedAt: batch.StartedAt,
|
||||
DurationSeconds: batch.DurationSeconds,
|
||||
SizesComplete: complete && batch.Complete,
|
||||
Databases: []Database{},
|
||||
}
|
||||
if complete && batch.Complete {
|
||||
item.ManifestTotalBytes = batch.ManifestTotalBytes
|
||||
item.ApparentBytes = batch.ApparentBytes
|
||||
item.ActualBytes = batch.ActualBytes
|
||||
item.FileCount = batch.FileCount
|
||||
}
|
||||
for _, database := range batch.Databases {
|
||||
entry := Database{
|
||||
Name: database.Name,
|
||||
DirName: database.DirName,
|
||||
Path: path.Join(root, batch.Stamp, database.DirName),
|
||||
HostPath: path.Join(root, batch.Stamp, database.DirName),
|
||||
Present: database.Present,
|
||||
Failed: database.Failed,
|
||||
InManifest: database.InManifest,
|
||||
}
|
||||
if complete && batch.Complete {
|
||||
entry.ApparentBytes = database.ApparentBytes
|
||||
entry.ActualBytes = database.ActualBytes
|
||||
entry.FileCount = database.FileCount
|
||||
}
|
||||
item.Databases = append(item.Databases, entry)
|
||||
}
|
||||
if !item.SizesComplete {
|
||||
item.SizesError = "宿主采集器该项不完整,占盘未知"
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return result[i].Stamp > result[j].Stamp })
|
||||
return result
|
||||
}
|
||||
|
||||
func totals(batches []Batch, complete bool) Totals {
|
||||
result := Totals{BatchCount: len(batches), Complete: complete}
|
||||
if len(batches) > 0 {
|
||||
result.LatestStamp = batches[0].Stamp
|
||||
}
|
||||
for _, batch := range batches {
|
||||
result.DatabaseCount += len(batch.Databases)
|
||||
}
|
||||
if !complete {
|
||||
return result
|
||||
}
|
||||
var apparent, actual int64
|
||||
for _, batch := range batches {
|
||||
if batch.ApparentBytes != nil {
|
||||
apparent += *batch.ApparentBytes
|
||||
}
|
||||
if batch.ActualBytes != nil {
|
||||
actual += *batch.ActualBytes
|
||||
}
|
||||
}
|
||||
result.ApparentBytes = &apparent
|
||||
result.ActualBytes = &actual
|
||||
if len(batches) > 0 {
|
||||
result.LatestActualBytes = batches[0].ActualBytes
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func projectCapacity(filesystem metadataFilesystem) Capacity {
|
||||
if filesystem.TotalBytes <= 0 {
|
||||
return Capacity{Error: "宿主采集器没有给出文件系统容量"}
|
||||
}
|
||||
used := filesystem.TotalBytes - filesystem.FreeBytes
|
||||
if used < 0 {
|
||||
used = 0
|
||||
}
|
||||
return Capacity{
|
||||
Measured: true,
|
||||
TotalBytes: filesystem.TotalBytes,
|
||||
FreeBytes: filesystem.FreeBytes,
|
||||
AvailableBytes: filesystem.AvailableBytes,
|
||||
UsedBytes: used,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const hostRoot = "/srv/kb-backups/rds-logical"
|
||||
|
||||
func int64p(value int64) *int64 { return &value }
|
||||
func intp(value int) *int { return &value }
|
||||
|
||||
func validMetadata() metadata {
|
||||
latest := hostRoot + "/20261118T193001Z"
|
||||
broken := hostRoot + "/20261117T193001Z"
|
||||
without := hostRoot + "/20261116T193001Z"
|
||||
return metadata{
|
||||
SchemaVersion: SchemaVersion,
|
||||
CollectorVersion: "backup-metadata/1",
|
||||
Generation: "20261120T010000Z-abc123",
|
||||
CollectedAt: "2026-11-20T01:00:00Z",
|
||||
Host: "weknora-test",
|
||||
Source: "weknora-test:" + hostRoot,
|
||||
Root: hostRoot,
|
||||
Complete: true,
|
||||
Errors: []string{},
|
||||
Filesystem: metadataFilesystem{
|
||||
MountPoint: "/srv/kb-backups",
|
||||
MountSource: "/dev/sdb1",
|
||||
FSType: "ext4",
|
||||
ReadOnly: false,
|
||||
TotalBytes: 1000,
|
||||
FreeBytes: 400,
|
||||
AvailableBytes: 350,
|
||||
},
|
||||
IncompleteCount: 1,
|
||||
Skipped: []Skipped{{Name: "notes.txt", Reason: "不是批次目录"}},
|
||||
Batches: []metadataBatch{
|
||||
{
|
||||
Stamp: "20261118T193001Z",
|
||||
Path: latest,
|
||||
ManifestState: "ok",
|
||||
Kind: "rds-logical-backup",
|
||||
CreatedAt: "20261118T193001Z",
|
||||
StartedAt: "20261118T192908Z",
|
||||
DurationSeconds: 53,
|
||||
ManifestTotalBytes: int64p(300),
|
||||
Complete: true,
|
||||
ApparentBytes: int64p(300),
|
||||
ActualBytes: int64p(4096),
|
||||
FileCount: intp(3),
|
||||
Databases: []metadataDatabase{
|
||||
{
|
||||
Name: "weknora_v090prod", DirName: "weknora_v090prod.dir",
|
||||
Path: latest + "/weknora_v090prod.dir", Present: true, InManifest: true,
|
||||
ApparentBytes: int64p(250), ActualBytes: int64p(4096), FileCount: intp(2),
|
||||
},
|
||||
{
|
||||
Name: "weknora_test", DirName: "weknora_test.dir",
|
||||
Path: latest + "/weknora_test.dir", Present: true, InManifest: true, Failed: true,
|
||||
ApparentBytes: int64p(50), ActualBytes: int64p(0), FileCount: intp(1),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Stamp: "20261117T193001Z",
|
||||
Path: broken,
|
||||
ManifestState: "invalid", ManifestError: "清单无法解析:unexpected end",
|
||||
Complete: true, ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
|
||||
Databases: []metadataDatabase{{
|
||||
Name: "weknora_prod", DirName: "weknora_prod.dir",
|
||||
Path: broken + "/weknora_prod.dir", Present: true,
|
||||
ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
|
||||
}},
|
||||
},
|
||||
{
|
||||
Stamp: "20261116T193001Z",
|
||||
Path: without,
|
||||
ManifestState: "missing",
|
||||
Complete: true, ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
|
||||
Databases: []metadataDatabase{{
|
||||
Name: "weknora_archive", DirName: "weknora_archive.dir",
|
||||
Path: without + "/weknora_archive.dir", Present: true,
|
||||
ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func writeMetadata(t *testing.T, value metadata) string {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filename := filepath.Join(t.TempDir(), "metadata.json")
|
||||
if err := os.WriteFile(filename, raw, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return filename
|
||||
}
|
||||
|
||||
func readerAt(filename string, now time.Time) *Reader {
|
||||
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
|
||||
reader.now = func() time.Time { return now }
|
||||
return reader
|
||||
}
|
||||
|
||||
func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
|
||||
filename := writeMetadata(t, validMetadata())
|
||||
now := time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)
|
||||
snapshot := readerAt(filename, now).Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Error != "" || !snapshot.Metadata.Valid || !snapshot.Metadata.Fresh || !snapshot.Metadata.Complete {
|
||||
t.Fatalf("应接受新鲜的完整快照: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || snapshot.Mount.MountPoint != "/srv/kb-backups" {
|
||||
t.Fatalf("宿主挂载判定不对: %+v", snapshot.Mount)
|
||||
}
|
||||
if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
|
||||
t.Fatalf("容量不对: %+v", snapshot.Capacity)
|
||||
}
|
||||
if snapshot.Metadata.AgeSeconds != 300 || snapshot.Metadata.Generation == "" || snapshot.Metadata.Host != "weknora-test" {
|
||||
t.Fatalf("元数据字段不对: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 || len(snapshot.Skipped) != 1 {
|
||||
t.Fatalf("批次计数不对: %+v", snapshot)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK || latest.SizesComplete != true {
|
||||
t.Fatalf("最近批次不对: %+v", latest)
|
||||
}
|
||||
if latest.HostPath != hostRoot+"/20261118T193001Z" || latest.ManifestTotalBytes == nil || *latest.ManifestTotalBytes != 300 {
|
||||
t.Fatalf("批次路径/清单不对: %+v", latest)
|
||||
}
|
||||
prod := latest.Databases[0]
|
||||
if prod.HostPath != hostRoot+"/20261118T193001Z/weknora_v090prod.dir" || prod.ActualBytes == nil || *prod.ActualBytes != 4096 {
|
||||
t.Fatalf("子库完整路径/占盘不对: %+v", prod)
|
||||
}
|
||||
if !latest.Databases[1].Failed {
|
||||
t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
|
||||
}
|
||||
if snapshot.Batches[1].ManifestState != ManifestInvalid || snapshot.Batches[1].ManifestError == "" {
|
||||
t.Fatalf("损坏清单没有如实标记: %+v", snapshot.Batches[1])
|
||||
}
|
||||
if snapshot.Batches[2].ManifestState != ManifestMissing {
|
||||
t.Fatalf("缺清单没有如实标记: %+v", snapshot.Batches[2])
|
||||
}
|
||||
if snapshot.Totals.ActualBytes == nil || *snapshot.Totals.ActualBytes != 4096+2048+1024 || !snapshot.Totals.Complete {
|
||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||
}
|
||||
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
|
||||
t.Fatalf("来源/测量方式不对: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotStaleIsUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.CollectedAt = "2026-11-20T00:00:00Z"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || snapshot.Metadata.Fresh || snapshot.Metadata.Complete {
|
||||
t.Fatalf("陈旧快照不能算有效: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 0 || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
|
||||
t.Fatalf("陈旧快照不能给批次/容量/占盘: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "陈旧") {
|
||||
t.Fatalf("陈旧原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotMissingMetadata(t *testing.T) {
|
||||
reader := New(Config{MetadataPath: filepath.Join(t.TempDir(), "missing.json"), HostRoot: hostRoot})
|
||||
snapshot := reader.Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Metadata.Present || snapshot.Metadata.Valid {
|
||||
t.Fatalf("缺失快照不能算有效: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "不存在") {
|
||||
t.Fatalf("缺失原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotPermissionFailureNeverUsesPartialBytes(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Complete = false
|
||||
value.Errors = nil
|
||||
value.Batches[0].Complete = false
|
||||
value.Batches[0].Errors = []string{"遍历失败:PermissionError: Permission denied ('.../weknora_v090prod.dir')"}
|
||||
// 模拟采集器在权限失败前已经数到的部分字节;API 绝不能把它们当占盘。
|
||||
value.Batches[0].ActualBytes = int64p(100)
|
||||
value.Batches[0].Databases[0].ActualBytes = int64p(100)
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if !snapshot.Metadata.Valid || snapshot.Metadata.Complete {
|
||||
t.Fatalf("不完整快照应 valid=true/complete=false: %+v", snapshot.Metadata)
|
||||
}
|
||||
if snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil || snapshot.Totals.ApparentBytes != nil {
|
||||
t.Fatalf("不完整快照不能给容量/总量: %+v", snapshot)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 {
|
||||
t.Fatalf("路径仍应列出: %+v", snapshot.Batches)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.ActualBytes != nil || latest.ApparentBytes != nil || latest.FileCount != nil || latest.SizesComplete {
|
||||
t.Fatalf("不完整批次不能保留部分字节: %+v", latest)
|
||||
}
|
||||
if latest.Databases[0].ActualBytes != nil || latest.Databases[0].ApparentBytes != nil {
|
||||
t.Fatalf("不完整子库不能保留部分字节: %+v", latest.Databases[0])
|
||||
}
|
||||
if !strings.Contains(snapshot.Metadata.Error, "Permission") {
|
||||
t.Fatalf("权限失败原因丢失: %q", snapshot.Metadata.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotTruncatedIsUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Truncated = true
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Complete || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
|
||||
t.Fatalf("截断快照不能算完整/容量: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsPathMismatch(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Batches[0].Path = "/srv/kb-backups/rds-logical/../evil"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("路径不一致必须整块拒绝: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "路径") {
|
||||
t.Fatalf("路径错误原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsUnsupportedSchema(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.SchemaVersion = 99
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || !strings.Contains(snapshot.Error, "schema_version") {
|
||||
t.Fatalf("不支持的 schema 必须拒绝: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotUnconfigured(t *testing.T) {
|
||||
snapshot := New(Config{}).Snapshot(context.Background())
|
||||
if snapshot.Wired || snapshot.Error == "" || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("未接线必须给出原因且不伪造批次: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "未接线") {
|
||||
t.Fatalf("未接线原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// 宿主采集器的权限失败回归:self-test 用注入 walker 模拟 PermissionError,
|
||||
// 断言不完整时字节为 null 且不产生部分统计。
|
||||
func TestCollectorSelfTest(t *testing.T) {
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("python3 not available")
|
||||
}
|
||||
command := exec.Command(python, "../../scripts/collect_backup_metadata.py", "--self-test")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("collector self-test failed: %v\n%s", err, output)
|
||||
}
|
||||
if !strings.Contains(string(output), "self-test ok") {
|
||||
t.Fatalf("collector self-test output unexpected: %s", output)
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,22 @@ package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CredentialStatus contains metadata only, never credential values.
|
||||
type CredentialStatus struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at,omitempty"`
|
||||
CorpName string `json:"corp_name,omitempty"`
|
||||
UserName string `json:"user_name,omitempty"`
|
||||
StatusKnown bool `json:"status_known"`
|
||||
}
|
||||
|
||||
func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) {
|
||||
@@ -20,13 +26,23 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus,
|
||||
return CredentialStatus{}, errors.New("could not read DWS credential status")
|
||||
}
|
||||
var decoded struct {
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpID json.RawMessage `json:"corp_id"`
|
||||
UserID json.RawMessage `json:"user_id"`
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpName string `json:"corp_name"`
|
||||
UserName string `json:"user_name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil {
|
||||
return CredentialStatus{}, errors.New("invalid DWS credential status")
|
||||
}
|
||||
return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil
|
||||
identity := ""
|
||||
if len(decoded.CorpID) > 0 && len(decoded.UserID) > 0 && string(decoded.CorpID) != "null" && string(decoded.UserID) != "null" {
|
||||
sum := sha256.Sum256(append(append(decoded.CorpID, 0), decoded.UserID...))
|
||||
identity = hex.EncodeToString(sum[:])
|
||||
}
|
||||
return CredentialStatus{Identity: identity, Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrLoginBusy = errors.New("another DWS authorization is active")
|
||||
var ErrLoginNotFound = errors.New("DWS authorization not found")
|
||||
|
||||
// DeviceLoginView contains only the user-facing challenge. Tokens remain in the
|
||||
// CLI's shared credential store; command output is never logged or returned.
|
||||
type DeviceLoginView struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
VerificationURL string `json:"verification_url,omitempty"`
|
||||
UserCode string `json:"user_code,omitempty"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type deviceLogin struct {
|
||||
view DeviceLoginView
|
||||
owner string
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type DeviceLoginManager struct {
|
||||
ctx context.Context
|
||||
runner ExecRunner
|
||||
mu sync.Mutex
|
||||
sessions map[string]*deviceLogin
|
||||
}
|
||||
|
||||
func NewDeviceLoginManager(ctx context.Context, runner ExecRunner) *DeviceLoginManager {
|
||||
return &DeviceLoginManager{ctx: ctx, runner: runner, sessions: make(map[string]*deviceLogin)}
|
||||
}
|
||||
|
||||
func loginActive(state string) bool {
|
||||
return state == "starting" || state == "waiting" || state == "verifying"
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Start(owner string) (DeviceLoginView, error) {
|
||||
if owner == "" {
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for id, s := range m.sessions {
|
||||
if s.view.State == "cancelled" || s.view.State == "expired" {
|
||||
select {
|
||||
case <-s.done:
|
||||
default:
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
}
|
||||
if loginActive(s.view.State) {
|
||||
if s.owner == owner {
|
||||
return s.view, nil
|
||||
}
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
if time.Since(s.view.ExpiresAt) > 30*time.Minute || len(m.sessions) >= 16 {
|
||||
delete(m.sessions, id)
|
||||
}
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return DeviceLoginView{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(m.ctx, 20*time.Minute)
|
||||
s := &deviceLogin{view: DeviceLoginView{ID: hex.EncodeToString(b[:]), State: "starting", ExpiresAt: time.Now().UTC().Add(20 * time.Minute)}, owner: owner, cancel: cancel, done: make(chan struct{})}
|
||||
m.sessions[s.view.ID] = s
|
||||
go m.run(ctx, s)
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Get(owner, id string) (DeviceLoginView, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s := m.sessions[id]
|
||||
if s == nil || s.owner != owner {
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
if loginActive(s.view.State) && !time.Now().Before(s.view.ExpiresAt) {
|
||||
s.cancel()
|
||||
finishLogin(s, "expired", "授权已过期,请重新发起。")
|
||||
}
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) Cancel(owner, id string) (DeviceLoginView, error) {
|
||||
m.mu.Lock()
|
||||
s := m.sessions[id]
|
||||
if s == nil || s.owner != owner {
|
||||
m.mu.Unlock()
|
||||
return DeviceLoginView{}, ErrLoginNotFound
|
||||
}
|
||||
if loginActive(s.view.State) {
|
||||
s.cancel()
|
||||
finishLogin(s, "cancelled", "")
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// Do not acknowledge cancellation while the old CLI could still write tokens.
|
||||
timer := time.NewTimer(7 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-s.done:
|
||||
case <-timer.C:
|
||||
return DeviceLoginView{}, ErrLoginBusy
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return s.view, nil
|
||||
}
|
||||
|
||||
func finishLogin(s *deviceLogin, state, message string) {
|
||||
s.view.State = state
|
||||
s.view.Error = message
|
||||
s.view.VerificationURL = ""
|
||||
s.view.UserCode = ""
|
||||
}
|
||||
|
||||
var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`)
|
||||
var challengeCode = regexp.MustCompile(`(?:授权码|User code|User Code)\s*[::]\s*([A-Za-z0-9-]{4,32})`)
|
||||
var challengeExpiry = regexp.MustCompile(`(?:将在\s*|expires in\s*)([0-9]+)\s*(?:秒|seconds)`)
|
||||
|
||||
func safeDeviceURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && u.Scheme == "https" && u.Host == "login.dingtalk.com" && u.User == nil && u.Fragment == "" && u.Path == "/oauth2/device/verify.htm"
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) observe(s *deviceLogin, line string) {
|
||||
line = strings.TrimSpace(ansiEscape.ReplaceAllString(line, ""))
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if match := challengeCode.FindStringSubmatch(line); len(match) == 2 {
|
||||
s.view.UserCode = match[1]
|
||||
}
|
||||
if match := challengeExpiry.FindStringSubmatch(line); len(match) == 2 {
|
||||
seconds, _ := strconv.Atoi(match[1])
|
||||
if seconds > 0 && seconds <= 1800 {
|
||||
s.view.ExpiresAt = time.Now().UTC().Add(time.Duration(seconds) * time.Second)
|
||||
}
|
||||
}
|
||||
if safeDeviceURL(line) {
|
||||
u, _ := url.Parse(line)
|
||||
if s.view.VerificationURL == "" || u.Query().Get("user_code") != "" {
|
||||
s.view.VerificationURL = line
|
||||
}
|
||||
}
|
||||
if s.view.State == "starting" && s.view.UserCode != "" && s.view.VerificationURL != "" {
|
||||
s.view.State = "waiting"
|
||||
}
|
||||
if strings.Contains(line, "Step 3:") {
|
||||
s.view.State = "verifying"
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) run(ctx context.Context, s *deviceLogin) {
|
||||
defer close(s.done)
|
||||
defer s.cancel()
|
||||
command, err := m.runner.command(ctx, "auth", "login", "--device", "--no-browser", "--format", "json")
|
||||
if err != nil {
|
||||
m.failed(s, "DWS 登录程序不可用,请联系管理员检查服务配置。")
|
||||
return
|
||||
}
|
||||
command.Env = append(command.Env, "DWS_LANG=zh", "NO_COLOR=1", "TERM=dumb")
|
||||
command.Stdout = io.Discard
|
||||
stderr, err := command.StderrPipe()
|
||||
if err != nil {
|
||||
m.failed(s, "无法启动 DWS 授权,请重试。")
|
||||
return
|
||||
}
|
||||
if err = command.Start(); err != nil {
|
||||
m.failed(s, "无法启动 DWS 授权,请检查凭据目录权限。")
|
||||
return
|
||||
}
|
||||
scanner := bufio.NewScanner(stderr)
|
||||
scanner.Buffer(make([]byte, 4096), 64*1024)
|
||||
for scanner.Scan() {
|
||||
m.observe(s, scanner.Text())
|
||||
}
|
||||
if scanner.Err() != nil {
|
||||
s.cancel()
|
||||
}
|
||||
err = command.Wait()
|
||||
m.mu.Lock()
|
||||
active := loginActive(s.view.State)
|
||||
m.mu.Unlock()
|
||||
if !active {
|
||||
return
|
||||
}
|
||||
if err != nil || ctx.Err() != nil {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || !time.Now().Before(s.view.ExpiresAt) {
|
||||
finishLogin(s, "expired", "授权已过期,请重新发起。")
|
||||
} else {
|
||||
finishLogin(s, "failed", "DWS 授权未完成,请重试;若组织未开通 CLI 数据权限,请联系钉钉管理员。")
|
||||
}
|
||||
return
|
||||
}
|
||||
// A process exit alone is not proof that usable credentials were persisted.
|
||||
checkCtx, cancel := context.WithTimeout(m.ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
status, statusErr := ReadCredentialStatus(checkCtx, m.runner)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !loginActive(s.view.State) {
|
||||
return
|
||||
}
|
||||
if statusErr != nil || !status.Authenticated || !status.RefreshTokenValid || !status.StatusKnown {
|
||||
finishLogin(s, "failed", "授权结束,但未读到有效 DWS 凭据,请重新授权。")
|
||||
} else {
|
||||
finishLogin(s, "succeeded", "")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *DeviceLoginManager) failed(s *deviceLogin, message string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if loginActive(s.view.State) {
|
||||
finishLogin(s, "failed", message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func deviceFixture(t *testing.T) (*DeviceLoginManager, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, "dws")
|
||||
script := `#!/usr/bin/env python3
|
||||
import sys,time,pathlib,json,os
|
||||
root=pathlib.Path(` + strconv.Quote(root) + `)
|
||||
a=sys.argv[1:]
|
||||
if a==['auth','login','--device','--no-browser','--format','json']:
|
||||
(root/'pid').write_text(str(os.getpid()))
|
||||
print(' 授权码: TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('授权码将在 900 秒后过期。',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm',file=sys.stderr,flush=True)
|
||||
print('never-expose-this-marker',file=sys.stderr,flush=True)
|
||||
while not (root/'finish').exists(): time.sleep(.01)
|
||||
if (root/'fail').exists(): sys.exit(1)
|
||||
elif a==['auth','status','--readonly','--format','json']:
|
||||
print(json.dumps({'authenticated':not (root/'invalid').exists(),'refresh_token_valid':True,'corp_name':'测试组织','user_name':'测试账号','access_token':'never-expose-this-marker'}))
|
||||
else: sys.exit(9)
|
||||
`
|
||||
if err := os.WriteFile(binary, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
return NewDeviceLoginManager(ctx, ExecRunner{Binary: binary}), root
|
||||
}
|
||||
func awaitDevice(t *testing.T, m *DeviceLoginManager, id, state string) DeviceLoginView {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
v, e := m.Get("owner", id)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if v.State == state {
|
||||
return v
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
v, _ := m.Get("owner", id)
|
||||
t.Fatalf("state=%s want=%s error=%s", v.State, state, v.Error)
|
||||
return v
|
||||
}
|
||||
func TestDeviceLoginUsesOfficialChallengeAndSharedCLI(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
initial, err := m.Start("owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.State != "starting" {
|
||||
t.Fatal(initial)
|
||||
}
|
||||
waiting := awaitDevice(t, m, initial.ID, "waiting")
|
||||
if waiting.UserCode != "TEST-CODE" || !strings.Contains(waiting.VerificationURL, "user_code=TEST-CODE") {
|
||||
t.Fatal("missing complete official challenge")
|
||||
}
|
||||
if _, err = m.Start("other"); !errors.Is(err, ErrLoginBusy) {
|
||||
t.Fatal("parallel logins may overwrite shared credentials")
|
||||
}
|
||||
duplicate, _ := m.Start("owner")
|
||||
if duplicate.ID != initial.ID {
|
||||
t.Fatal("duplicate start was not idempotent")
|
||||
}
|
||||
if _, err = m.Get("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("challenge leaked to another owner")
|
||||
}
|
||||
if _, err = m.Cancel("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("foreign cancellation permitted")
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(root, "finish"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := awaitDevice(t, m, initial.ID, "succeeded")
|
||||
raw, _ := json.Marshal(done)
|
||||
if done.UserCode != "" || done.VerificationURL != "" || strings.Contains(string(raw), "never-expose") {
|
||||
t.Fatal("completed session retained sensitive output")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginCancellationClearsChallenge(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
v, _ := m.Start("owner")
|
||||
awaitDevice(t, m, v.ID, "waiting")
|
||||
closed, err := m.Cancel("owner", v.ID)
|
||||
if err != nil || closed.State != "cancelled" || closed.UserCode != "" || closed.VerificationURL != "" {
|
||||
t.Fatal(closed, err)
|
||||
}
|
||||
pidBytes, err := os.ReadFile(filepath.Join(root, "pid"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pid, _ := strconv.Atoi(string(pidBytes))
|
||||
if syscall.Kill(pid, 0) == nil {
|
||||
t.Fatal("cancel returned while credential-writing process was still running")
|
||||
}
|
||||
again, _ := m.Get("owner", v.ID)
|
||||
if again.State != "cancelled" {
|
||||
t.Fatal("late process exit overwrote cancellation")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginRejectsExitWithoutPersistedCredentials(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "invalid"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if !strings.Contains(done.Error, "未读到有效") {
|
||||
t.Fatal("successful exit was treated as authenticated")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginFailureIsRedactedAndRetryable(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "fail"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if strings.Contains(done.Error, "never-expose") || done.Error == "" {
|
||||
t.Fatal("raw CLI output or missing error")
|
||||
}
|
||||
retry, e := m.Start("owner")
|
||||
if e != nil || retry.ID == v.ID {
|
||||
t.Fatal("cannot retry failed authorization")
|
||||
}
|
||||
}
|
||||
func TestDeviceChallengeRejectsUntrustedLinksAndExpires(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
_ = root
|
||||
s := &deviceLogin{view: DeviceLoginView{State: "starting", ExpiresAt: time.Now().Add(time.Minute)}, cancel: func() {}}
|
||||
m.observe(s, "授权码: TEST-CODE")
|
||||
for _, link := range []string{"http://login.dingtalk.com/oauth2/device/verify.htm", "https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm", "https://user:pass@login.dingtalk.com/oauth2/device/verify.htm", "javascript:alert(1)", "https://login.dingtalk.com/other"} {
|
||||
m.observe(s, link)
|
||||
}
|
||||
if s.view.State != "starting" || s.view.VerificationURL != "" {
|
||||
t.Fatal("untrusted link accepted")
|
||||
}
|
||||
s.view.ID = "test-expired"
|
||||
s.owner = "owner"
|
||||
s.view.ExpiresAt = time.Now().Add(-time.Second)
|
||||
m.sessions[s.view.ID] = s
|
||||
got, e := m.Get("owner", s.view.ID)
|
||||
if e != nil || got.State != "expired" || got.UserCode != "" {
|
||||
t.Fatal("expired challenge retained")
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
|
||||
type KnowledgeBase struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
SpaceType string `json:"space_type"`
|
||||
@@ -30,6 +31,7 @@ type KnowledgeBase struct {
|
||||
|
||||
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
|
||||
type DriveSpace struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
RootFolderID string `json:"root_folder_id,omitempty"`
|
||||
@@ -38,6 +40,7 @@ type DriveSpace struct {
|
||||
|
||||
// Result 是一次发现的结果。
|
||||
type Result struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
|
||||
DriveSpaces []DriveSpace `json:"drive_spaces"`
|
||||
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
|
||||
@@ -70,21 +73,26 @@ func SpaceListArgs(spaceType string) []string {
|
||||
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
|
||||
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
|
||||
func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result := Result{FetchedAt: time.Now().UTC()}
|
||||
result := Result{FetchedAt: time.Now().UTC(), KnowledgeBases: []KnowledgeBase{}, DriveSpaces: []DriveSpace{}}
|
||||
successful := 0
|
||||
causes := []error{}
|
||||
|
||||
failures := make([]string, 0, len(knowledgeSpaceTypes))
|
||||
seenKnowledge := map[string]bool{}
|
||||
for _, spaceType := range knowledgeSpaceTypes {
|
||||
raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
bases, notice, err := parseKnowledgeBases(raw, spaceType)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
if notice != "" {
|
||||
result.KnowledgeNotice = notice
|
||||
}
|
||||
@@ -96,9 +104,6 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.KnowledgeBases = append(result.KnowledgeBases, base)
|
||||
}
|
||||
}
|
||||
if len(result.KnowledgeBases) == 0 && len(failures) > 0 {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";"))
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";")
|
||||
}
|
||||
@@ -107,14 +112,17 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
for _, spaceType := range []string{"mySpace", "orgSpace"} {
|
||||
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
spaces, err := parseDriveSpaces(raw, spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
for _, space := range spaces {
|
||||
if seenDrive[space.SpaceType+":"+space.SpaceID] {
|
||||
continue
|
||||
@@ -123,11 +131,21 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.DriveSpaces = append(result.DriveSpaces, space)
|
||||
}
|
||||
}
|
||||
if successful == 0 && len(causes) > 0 {
|
||||
return result, fmt.Errorf("%w: %w", ErrUnavailable, errors.Join(causes...))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func describe(scope string, err error) string {
|
||||
return scope + ":" + err.Error()
|
||||
reason := "读取失败,请重试"
|
||||
if errors.Is(err, ErrCredentials) {
|
||||
reason = "DWS 授权已失效"
|
||||
}
|
||||
if errors.Is(err, ErrPermission) {
|
||||
reason = "当前范围权限不足"
|
||||
}
|
||||
return scope + ":" + reason
|
||||
}
|
||||
|
||||
// parseKnowledgeBases 解析 `dws wiki +space-list`:
|
||||
|
||||
@@ -127,7 +127,7 @@ func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) {
|
||||
if len(result.DriveSpaces) != 0 {
|
||||
t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces))
|
||||
}
|
||||
if !strings.Contains(result.DriveNotice, "permission denied") {
|
||||
if !strings.Contains(result.DriveNotice, "权限") {
|
||||
t.Fatalf("drive notice = %q", result.DriveNotice)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@ type ExecRunner struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// RunDWS 运行 `dws <args…>` 并返回 stdout。
|
||||
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
|
||||
// command keeps device login and source reads on one credential environment.
|
||||
func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, error) {
|
||||
binary := r.Binary
|
||||
if binary == "" {
|
||||
binary = os.Getenv("DWS_BIN")
|
||||
@@ -32,14 +32,24 @@ func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error)
|
||||
}
|
||||
binary = found
|
||||
}
|
||||
command := exec.CommandContext(ctx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
command.WaitDelay = 2 * time.Second
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// RunDWS uses the same executable and credential environment as device login.
|
||||
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
|
||||
timeout := r.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 25 * time.Second
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
command := exec.CommandContext(runCtx, binary, args...)
|
||||
command.Env = dwsEnv()
|
||||
command, err := r.command(runCtx, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout = &stdout
|
||||
command.Stderr = &stderr
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrCredentials = errors.New("DWS authorization required")
|
||||
var ErrPermission = errors.New("DWS directory permission denied")
|
||||
|
||||
// failureCause inspects only structured CLI errors; no upstream text is returned.
|
||||
func failureCause(raw []byte, cause error) error {
|
||||
var v struct {
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Code any `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &v) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
text := strings.ToLower(v.Error.Type + " " + fmt.Sprint(v.Error.Code) + " " + v.Error.Message)
|
||||
for _, key := range []string{"permission", "forbidden", "scope", "access denied", "权限", "403"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrPermission
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"unauth", "not_logged_in", "not logged", "login_required", "login required", "authentication", "auth_required", "credential", "token_expired", "invalid_token", "token expired", "invalid_grant", "未登录", "授权已过期", "授权失效"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrCredentials
|
||||
}
|
||||
}
|
||||
if errors.Is(cause, ErrCredentials) || errors.Is(cause, ErrPermission) {
|
||||
return cause
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
@@ -16,9 +16,8 @@ func developmentNotes(changelog, version, sha string) string {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(changelog, "\n")
|
||||
prefix := "## 开发快照 snapshot/v" + version + " - "
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
if developmentHeadingMatches(line, version) {
|
||||
end := len(lines)
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
if strings.HasPrefix(lines[j], "## ") {
|
||||
@@ -39,3 +38,33 @@ func developmentNotes(changelog, version, sha string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// developmentHeadingMatches 接受两种真实标题:
|
||||
// - 旧格式:## 开发快照 snapshot/v0.1.1 - 2026-10-18
|
||||
// - 开发快照:## 开发快照 0.1.351(索引预检使用目标映射 ID)
|
||||
//
|
||||
// 版本号后必须是字符串结束或分隔符,避免 0.1.35 命中 0.1.351;
|
||||
// 只读取到下一个二级标题,不跨版本吞正文。
|
||||
func developmentHeadingMatches(line, version string) bool {
|
||||
prefixes := []string{
|
||||
"## 开发快照 snapshot/v" + version,
|
||||
"## 开发快照 " + version,
|
||||
}
|
||||
for _, prefix := range prefixes {
|
||||
if !strings.HasPrefix(line, prefix) {
|
||||
continue
|
||||
}
|
||||
rest := line[len(prefix):]
|
||||
if rest == "" {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(rest, "—") || strings.HasPrefix(rest, "(") {
|
||||
return true
|
||||
}
|
||||
switch rest[0] {
|
||||
case ' ', '\t', '-', '(':
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -44,6 +44,10 @@ const (
|
||||
// 读出来封存成快照并逐类校验,再登记成 production_effective。
|
||||
// 它不写目标内容、不清空目标、不猜版本——基线只能来自真实捕获与校验。
|
||||
LibraryJobBaseline LibraryJobKind = "baseline"
|
||||
// LibraryJobVerify 是"恢复验证":在维护窗口内捕获目标 → 校验基线一致 →
|
||||
// 写一个 canary 证明校验能发现差异 → 按预备份恢复 → 复核完全一致。
|
||||
// 它是唯一能产生"生产可恢复"证据的作业,页面不再接受手填开关。
|
||||
LibraryJobVerify LibraryJobKind = "verify"
|
||||
)
|
||||
|
||||
type LibraryJobState string
|
||||
@@ -173,6 +177,12 @@ func BaselineStages() []string {
|
||||
return []string{"capture", "verify", "finalize"}
|
||||
}
|
||||
|
||||
// VerifyStages 是恢复验证的阶段:捕获 → 基线校验 → 写 canary(证明校验有效)
|
||||
// → 按预备份恢复 → 恢复后复核。canary 与 restore 都是真实写入,失败必须可见。
|
||||
func VerifyStages() []string {
|
||||
return []string{"capture", "verify", "canary", "restore", "finalize"}
|
||||
}
|
||||
|
||||
// LibraryReleaseAuthorization 是生产发布授权:绑定目标、快照、参数摘要与有效期。
|
||||
type LibraryReleaseAuthorization struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -147,7 +147,7 @@ func ValidateLibraryOperation(op LibraryOperation) error {
|
||||
return errors.New("library operation requires internal or external scope")
|
||||
}
|
||||
switch op.Kind {
|
||||
case LibraryJobSeal, LibraryJobSync, LibraryJobRestore, LibraryJobBaseline, LibraryJobRecover:
|
||||
case LibraryJobSeal, LibraryJobSync, LibraryJobRestore, LibraryJobBaseline, LibraryJobRecover, LibraryJobVerify:
|
||||
default:
|
||||
return fmt.Errorf("unsupported library operation kind %q", op.Kind)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LibraryRestoreVerification 是一次**真实**恢复验证(备份 → canary → 恢复 → 复核)的登记。
|
||||
//
|
||||
// 为什么不能继续用环境变量 PRODUCTION_BACKUP_RESTORE_VERIFIED:那是一个可以手填的开关,
|
||||
// 它既证明不了"有人真跑过恢复",也证明不了"跑的是当前目标"。这里的每条记录由 worker
|
||||
// 在真实演练结束后写入,绑定 target_id(实例+库+索引+桶)与 scope,失败也照实留痕。
|
||||
type LibraryRestoreVerification struct {
|
||||
ID string `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
Status string `json:"status"` // passed | failed
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
JobID string `json:"job_id"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
Report map[string]any `json:"report,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
const (
|
||||
LibraryVerificationPassed = "passed"
|
||||
LibraryVerificationFailed = "failed"
|
||||
)
|
||||
|
||||
// LibraryVerificationSatisfied 只回答一件事:这条证据能不能支撑"当前目标的恢复验证已通过"。
|
||||
// 通过的条件必须是全部成立——状态 passed、scope 相同、快照非空、完成时间有效。
|
||||
// target_id 的匹配由查询层(按当前 target_id 过滤)保证,这里不重复比较。
|
||||
func LibraryVerificationSatisfied(verification LibraryRestoreVerification, scope string) (bool, string) {
|
||||
if verification.Status != LibraryVerificationPassed {
|
||||
reason := "最近一次恢复验证没有通过"
|
||||
if detail := strings.TrimSpace(verification.Failure); detail != "" {
|
||||
reason += ":" + detail
|
||||
}
|
||||
return false, reason
|
||||
}
|
||||
if verification.Scope != scope {
|
||||
return false, "恢复验证证据属于另一个 scope(" + verification.Scope + ")"
|
||||
}
|
||||
if strings.TrimSpace(verification.SnapshotID) == "" {
|
||||
return false, "恢复验证证据没有绑定快照,不能作为备份可恢复的证明"
|
||||
}
|
||||
if verification.FinishedAt.IsZero() {
|
||||
return false, "恢复验证证据没有完成时间"
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 证据能不能支撑"当前目标可恢复"只由这四个条件回答:
|
||||
// 状态 passed、scope 相同、绑定了快照、有完成时间。少任何一条都不算。
|
||||
func TestLibraryVerificationSatisfied(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
cases := []struct {
|
||||
name string
|
||||
verification LibraryRestoreVerification
|
||||
scope string
|
||||
want bool
|
||||
reason string
|
||||
}{
|
||||
{name: "passed with snapshot", scope: "internal", want: true,
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal",
|
||||
SnapshotID: "snap-1", FinishedAt: now}},
|
||||
{name: "failed carries failure", scope: "internal", want: false, reason: "canary 后校验仍通过",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationFailed, Scope: "internal",
|
||||
SnapshotID: "snap-1", Failure: "canary 后校验仍通过", FinishedAt: now}},
|
||||
{name: "wrong scope", scope: "internal", want: false, reason: "另一个 scope",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "external",
|
||||
SnapshotID: "snap-1", FinishedAt: now}},
|
||||
{name: "no snapshot", scope: "internal", want: false, reason: "没有绑定快照",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal",
|
||||
FinishedAt: now}},
|
||||
{name: "no finish time", scope: "internal", want: false, reason: "没有完成时间",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal",
|
||||
SnapshotID: "snap-1"}},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
ok, reason := LibraryVerificationSatisfied(testCase.verification, testCase.scope)
|
||||
if ok != testCase.want {
|
||||
t.Fatalf("satisfied=%v want=%v reason=%q", ok, testCase.want, reason)
|
||||
}
|
||||
if !testCase.want && testCase.reason != "" && !containsText(reason, testCase.reason) {
|
||||
t.Fatalf("reason=%q want contains %q", reason, testCase.reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func containsText(haystack, needle string) bool {
|
||||
return len(haystack) >= len(needle) && (haystack == needle || indexOf(haystack, needle) >= 0)
|
||||
}
|
||||
|
||||
func indexOf(haystack, needle string) int {
|
||||
for i := 0; i+len(needle) <= len(haystack); i++ {
|
||||
if haystack[i:i+len(needle)] == needle {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
@@ -36,8 +36,11 @@ type ServiceHealth struct {
|
||||
ObservedAt time.Time `json:"observed_at"`
|
||||
LastSuccessAt *time.Time `json:"last_success_at"`
|
||||
ConsecutiveFailures int `json:"consecutive_failures"`
|
||||
Configured bool `json:"configured"`
|
||||
Applicable bool `json:"applicable"`
|
||||
// ProbeTarget names the object being probed (instance + short binding id),
|
||||
// never credentials or full UUIDs, so a red light can be attributed.
|
||||
ProbeTarget string `json:"probe_target"`
|
||||
Configured bool `json:"configured"`
|
||||
Applicable bool `json:"applicable"`
|
||||
}
|
||||
|
||||
type KnowledgeBaseProgress struct {
|
||||
|
||||
@@ -116,6 +116,7 @@ type CatalogRouteRequest struct {
|
||||
// fulfillment path needs to materialize and fetch it later.
|
||||
type CatalogRouteFile struct {
|
||||
NodeID string
|
||||
ParentNodeID string
|
||||
Name string
|
||||
RelativePath string
|
||||
SizeBytes *int64
|
||||
|
||||
@@ -107,6 +107,9 @@ func classifyRole(method, path string) string {
|
||||
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
|
||||
return roleAdmin
|
||||
}
|
||||
if strings.HasPrefix(path, "/api/v1/dws-login") || strings.HasPrefix(path, "/api/v1/pp-connection") || strings.HasPrefix(path, "/api/v1/dingtalk-spaces") || strings.HasPrefix(path, "/api/v1/dingtalk-session") {
|
||||
return roleAdmin
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
return roleViewer
|
||||
}
|
||||
@@ -138,6 +141,11 @@ func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 「知识库绑定」saves a connection (address + key) and both bindings for one
|
||||
// environment in one write: same authority as the annotation binding.
|
||||
if strings.HasPrefix(path, "/api/v1/kb-bindings") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Choosing the production base a release writes into is a production
|
||||
// authority change, exactly like the annotation binding above.
|
||||
if path == "/api/v1/production-kb-bindings" && method != http.MethodGet {
|
||||
@@ -148,6 +156,11 @@ func classifyRole(method, path string) string {
|
||||
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 核对封存结果会把一个 pending 业务作业修成 succeeded;只允许管理员,
|
||||
// 且 handler 仍要求 completed queue、精确版本和归档复核。
|
||||
if strings.HasPrefix(path, "/api/v1/library/jobs/") && strings.HasSuffix(path, "/reconcile-capture") {
|
||||
return roleAdmin
|
||||
}
|
||||
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
|
||||
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
|
||||
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
// BackupInventoryReader 读取宿主采集器写出的元数据快照。它与 SSH 主机计划读回完全独立:
|
||||
// 快照缺失/陈旧不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
|
||||
type BackupInventoryReader interface {
|
||||
Available() bool
|
||||
Snapshot(context.Context) backupinventory.Snapshot
|
||||
}
|
||||
|
||||
// handleBackupInventory 返回宿主采集器快照里的批次、子库路径与容量。
|
||||
// 未接线/快照缺失/陈旧/不完整/路径不一致都作为 200 的字段返回,由页面区分原因;
|
||||
// 只有投影本身失败才 500。
|
||||
func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
|
||||
snapshot := config.BackupInventory.Snapshot(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": snapshot})
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
type fakeBackupInventory struct {
|
||||
snapshot backupinventory.Snapshot
|
||||
}
|
||||
|
||||
func (fake fakeBackupInventory) Available() bool { return fake.snapshot.Wired }
|
||||
|
||||
func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapshot {
|
||||
return fake.snapshot
|
||||
}
|
||||
|
||||
func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
actual := int64(1024)
|
||||
databaseActual := int64(512)
|
||||
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
|
||||
Mount: backupinventory.MountInfo{
|
||||
MountVerified: true,
|
||||
ReadOnly: true,
|
||||
Evidence: "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4)",
|
||||
},
|
||||
Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
|
||||
Batches: []backupinventory.Batch{{
|
||||
Stamp: "20261118T193001Z",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
ManifestState: backupinventory.ManifestOK,
|
||||
ActualBytes: &actual,
|
||||
Databases: []backupinventory.Database{{
|
||||
Name: "weknora_v090prod",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
Present: true,
|
||||
ActualBytes: &databaseActual,
|
||||
}},
|
||||
}},
|
||||
Totals: backupinventory.Totals{BatchCount: 1, ActualBytes: &actual, LatestStamp: "20261118T193001Z", Complete: true},
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !payload.Data.Wired || !payload.Data.Mount.MountVerified || !payload.Data.Capacity.Measured {
|
||||
t.Fatalf("接线/挂载/容量字段丢失: %+v", payload.Data)
|
||||
}
|
||||
if len(payload.Data.Batches) != 1 ||
|
||||
payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
|
||||
t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
|
||||
}
|
||||
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
|
||||
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
|
||||
config := Config{BackupInventory: backupinventory.New(backupinventory.Config{})}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("未接线不应 500: %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Data.Wired || payload.Data.Error == "" || payload.Data.Batches == nil {
|
||||
t.Fatalf("未接线必须给原因且批次为空数组: %+v", payload.Data)
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ type BackupScheduleStore interface {
|
||||
type BackupHost interface {
|
||||
Available() bool
|
||||
Target() string
|
||||
// Endpoint 是挂载的 ssh 配置里该别名真实拨号的 host:port;页面据此证明
|
||||
// "连的是哪条通道",而不是只显示一个别名。
|
||||
Endpoint() string
|
||||
Show(context.Context) (backuphost.ShowResult, error)
|
||||
Apply(context.Context, bool, string, int, int) (backuphost.ApplyResult, error)
|
||||
RunNow(context.Context) (backuphost.RunResult, error)
|
||||
@@ -82,8 +85,11 @@ type backupScheduleView struct {
|
||||
// HostConfigured/HostReachable 区分"没接线"与"接线了但连不上"。
|
||||
HostConfigured bool `json:"host_configured"`
|
||||
HostTarget string `json:"host_target"`
|
||||
HostReachable bool `json:"host_reachable"`
|
||||
HostError string `json:"host_error"`
|
||||
// HostEndpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。
|
||||
// 连接失败时它就是"到底往哪连"的唯一证据,不能只给一个别名让人猜。
|
||||
HostEndpoint string `json:"host_endpoint"`
|
||||
HostReachable bool `json:"host_reachable"`
|
||||
HostError string `json:"host_error"`
|
||||
|
||||
HostScheduleEnabled bool `json:"host_schedule_enabled"`
|
||||
HostScheduleTime string `json:"host_schedule_time"`
|
||||
@@ -92,6 +98,8 @@ type backupScheduleView struct {
|
||||
HostCronLines []string `json:"host_cron_lines"`
|
||||
HostCronService string `json:"host_cron_service"`
|
||||
HostScriptPresent bool `json:"host_script_present"`
|
||||
// HostCheckedAt 是本次真实主机探测时间;没有探测(只读库)时为空。
|
||||
HostCheckedAt string `json:"host_checked_at,omitempty"`
|
||||
|
||||
LastRunStamp string `json:"last_run_stamp"`
|
||||
LastRunCreatedAt string `json:"last_run_created_at"`
|
||||
@@ -281,6 +289,7 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool)
|
||||
}
|
||||
view.HostConfigured = config.BackupHost.Available()
|
||||
view.HostTarget = config.BackupHost.Target()
|
||||
view.HostEndpoint = config.BackupHost.Endpoint()
|
||||
if !view.HostConfigured {
|
||||
view.InSync = false
|
||||
view.HostError = "目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)"
|
||||
@@ -289,10 +298,14 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool)
|
||||
if !probeHost {
|
||||
return view, nil
|
||||
}
|
||||
view.HostCheckedAt = formatTime(config.Now().UTC())
|
||||
show, err := config.BackupHost.Show(ctx)
|
||||
if err != nil {
|
||||
view.HostReachable = false
|
||||
view.HostError = err.Error()
|
||||
if view.HostEndpoint != "" {
|
||||
view.HostError += "(拨号地址 " + view.HostEndpoint + ")"
|
||||
}
|
||||
view.InSync = false
|
||||
} else {
|
||||
view.HostReachable = true
|
||||
|
||||
@@ -46,6 +46,7 @@ func (store *fakeBackupScheduleStore) MarkBackupScheduleApplied(_ context.Contex
|
||||
type fakeBackupHost struct {
|
||||
available bool
|
||||
target string
|
||||
endpoint string
|
||||
show backuphost.ShowResult
|
||||
showErr error
|
||||
apply backuphost.ApplyResult
|
||||
@@ -59,6 +60,9 @@ type fakeBackupHost struct {
|
||||
|
||||
func (host *fakeBackupHost) Available() bool { return host.available }
|
||||
func (host *fakeBackupHost) Target() string { return host.target }
|
||||
func (host *fakeBackupHost) Endpoint() string {
|
||||
return host.endpoint
|
||||
}
|
||||
func (host *fakeBackupHost) Show(context.Context) (backuphost.ShowResult, error) {
|
||||
return host.show, host.showErr
|
||||
}
|
||||
@@ -166,6 +170,48 @@ func TestHandleBackupScheduleHostFlagsDrift(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBackupScheduleHostUnreachableSeparatesConnectionFromHostState(t *testing.T) {
|
||||
// 现场原错:ssh connect to host 120.76.217.51 port 22 Operation timed out。
|
||||
// 连接没建立 ⇒ 既不能报"脚本缺失",也不能报"计划未下发",只能报不可达 + 拨号地址。
|
||||
host := &fakeBackupHost{
|
||||
available: true, target: "weknora-test", endpoint: "100.85.111.121:22",
|
||||
showErr: errors.New("目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知"),
|
||||
}
|
||||
config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, host)
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupScheduleHost(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/host", nil))
|
||||
data := decodeData(t, recorder)
|
||||
if data["host_reachable"] != false || data["in_sync"] != false {
|
||||
t.Fatalf("连不上时不能报告可达或已同步: %+v", data)
|
||||
}
|
||||
message := data["host_error"].(string)
|
||||
if !strings.Contains(message, "不可达") || !strings.Contains(message, "100.85.111.121:22") {
|
||||
t.Fatalf("应报不可达并给出真实拨号地址: %q", message)
|
||||
}
|
||||
if strings.Contains(message, "脚本缺失") || strings.Contains(message, "未下发") {
|
||||
t.Fatalf("未观测到的脚本/计划状态不能当成结论: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBackupScheduleHostReportsMissingScriptOnlyAfterConnecting(t *testing.T) {
|
||||
// 真正的脚本缺失:ssh 已连上,主机回的是脚本不存在 ⇒ 这时才允许说脚本缺失。
|
||||
host := &fakeBackupHost{
|
||||
available: true, target: "weknora-test", endpoint: "100.85.111.121:22",
|
||||
showErr: errors.New("已连上 weknora-test,但主机侧命令失败: bash: /opt/weknora-test/install_backup_schedule.sh: No such file or directory"),
|
||||
}
|
||||
config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, host)
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupScheduleHost(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/host", nil))
|
||||
data := decodeData(t, recorder)
|
||||
message := data["host_error"].(string)
|
||||
if !strings.Contains(message, "已连上") || !strings.Contains(message, "No such file") {
|
||||
t.Fatalf("已连接但脚本缺失时应原样带回主机原因: %q", message)
|
||||
}
|
||||
if strings.Contains(message, "不可达") {
|
||||
t.Fatalf("已连上就不能说不可达: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBackupScheduleHostUnconfiguredDegrades(t *testing.T) {
|
||||
config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, &fakeBackupHost{available: false})
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/ppauth"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Credential events are committed with their secret revision in one atomic file.
|
||||
// Merge them into the existing audit view without copying secrets into SQL.
|
||||
func combinedSourceAudit(ctx context.Context, reader sourceAuditReader, manager *ppauth.Manager, limit, offset int) (postgresstore.SourceAuditPage, error) {
|
||||
if manager == nil {
|
||||
return reader.ListSourceAudit(ctx, limit, offset)
|
||||
}
|
||||
events, err := manager.Events(ctx)
|
||||
if err != nil {
|
||||
return postgresstore.SourceAuditPage{}, err
|
||||
}
|
||||
if len(events) == 0 {
|
||||
return reader.ListSourceAudit(ctx, limit, offset)
|
||||
}
|
||||
start := offset - len(events)
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
rows := make([]postgresstore.SourceAuditItem, 0, limit+len(events))
|
||||
total := 0
|
||||
for next := start; len(rows) < limit+len(events); {
|
||||
take := limit + len(events) - len(rows)
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
page, e := reader.ListSourceAudit(ctx, take, next)
|
||||
if e != nil {
|
||||
return postgresstore.SourceAuditPage{}, e
|
||||
}
|
||||
total = page.Total
|
||||
rows = append(rows, page.Items...)
|
||||
next += len(page.Items)
|
||||
if next >= total || len(page.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, e := range events {
|
||||
rows = append(rows, postgresstore.SourceAuditItem{ID: e.ID, ConnectionID: "", SourceName: e.SourceName, Action: e.Action, Actor: e.Actor, CreatedAt: e.CreatedAt, Detail: e.Detail})
|
||||
}
|
||||
sort.SliceStable(rows, func(i, j int) bool {
|
||||
if rows[i].CreatedAt.Equal(rows[j].CreatedAt) {
|
||||
return rows[i].ID > rows[j].ID
|
||||
}
|
||||
return rows[i].CreatedAt.After(rows[j].CreatedAt)
|
||||
})
|
||||
skip := offset - start
|
||||
if skip > len(rows) {
|
||||
skip = len(rows)
|
||||
}
|
||||
end := skip + limit
|
||||
if end > len(rows) {
|
||||
end = len(rows)
|
||||
}
|
||||
return postgresstore.SourceAuditPage{Items: rows[skip:end], Total: total + len(events), Limit: limit, Offset: offset}, nil
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -25,25 +24,16 @@ func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config)
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
lister := config.DingtalkSources
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
|
||||
identity, _ := requireSessionIdentity(w, r)
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "需要管理员身份列举数据源"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
// 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来",
|
||||
// 不是平台故障,也不该把内部错误细节当 500 抛出去。
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "dingtalk_discovery_unavailable",
|
||||
"hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"})
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") {
|
||||
if !strings.Contains(rec.Body.String(), "dws_unavailable") {
|
||||
t.Fatalf("body = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,59 +2,42 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func TestDWSNameConflictIsNotASuccessfulRegistration(t *testing.T) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: postgresstore.ErrDingtalkSpaceNameTaken}
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "wiki", SpaceID: "testspace"}}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", nil)
|
||||
registerSpaceThroughDWS(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
|
||||
if rec.Code != http.StatusConflict {
|
||||
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", nil)
|
||||
registerDWSOnlySpace(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
|
||||
if rec.Code != 409 {
|
||||
t.Fatalf("name conflict must not claim success: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 登记走 dws 不是侧车:解析出来的键、名称、根节点直接决定新来源的确定性 id。
|
||||
func TestResolveSpaceViaDWSUsesTheSpaceCredentialsAlreadyHeld(t *testing.T) {
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{
|
||||
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{
|
||||
{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"},
|
||||
{Name: "视觉文档", SpaceID: "9JOGO9EEOMLMWX4Q"},
|
||||
},
|
||||
DriveSpaces: []dingtalkdiscovery.DriveSpace{
|
||||
{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a"},
|
||||
},
|
||||
}}
|
||||
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(
|
||||
context.Background(), lister, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
|
||||
if !ok || rootKey != "space-9JOGOLBQndOyaz4Q" || name != "国内技术支持管理" || rootID != "9JOGOLBQndOyaz4Q" || spaceID != "9JOGOLBQndOyaz4Q" {
|
||||
t.Fatalf("knowledge base resolved as key=%q name=%q root=%q space=%q ok=%v", rootKey, name, rootID, spaceID, ok)
|
||||
result := dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"}}, DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "drive-root"}}}
|
||||
input, err := resolveDWS(result, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
|
||||
if err != nil || input.RootKey != "space-9JOGOLBQndOyaz4Q" || input.Name != "国内技术支持管理" || input.RootID != "9JOGOLBQndOyaz4Q" || input.SpaceID != "9JOGOLBQndOyaz4Q" {
|
||||
t.Fatalf("wiki resolution=%+v %v", input, err)
|
||||
}
|
||||
|
||||
// 钉盘的根是 rootFolderId,不是空间 id:抓取侧按它遍历。
|
||||
rootKey, _, rootID, _, ok = resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("102571304"))
|
||||
if !ok || rootID != "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a" || rootKey != "space-102571304" {
|
||||
t.Fatalf("drive space resolved as key=%q root=%q ok=%v", rootKey, rootID, ok)
|
||||
input, err = resolveDWS(result, dingtalkdiscovery.SpaceURL("102571304"))
|
||||
if err != nil || input.RootID != "drive-root" || input.RootKey != "space-102571304" {
|
||||
t.Fatalf("drive resolution=%+v %v", input, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSpaceViaDWSLeavesUnknownSpacesToTheFallback(t *testing.T) {
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{}}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("unknownspace1")); ok {
|
||||
t.Fatal("an unknown space must not resolve")
|
||||
func TestResolveDWSRejectsUnknownAndUnwiredWithoutBrowserFallback(t *testing.T) {
|
||||
if _, err := resolveDWS(dingtalkdiscovery.Result{}, dingtalkdiscovery.SpaceURL("unknownspace1")); err == nil {
|
||||
t.Fatal("unknown space resolved")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok {
|
||||
t.Fatal("without a lister nothing can resolve")
|
||||
if _, err := availableDWS(context.Background(), Config{}); err == nil {
|
||||
t.Fatal("unwired service resolved")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok {
|
||||
t.Fatal("a URL without a space id must not resolve")
|
||||
if _, err := resolveDWS(dingtalkdiscovery.Result{}, "not-a-space-url"); err == nil {
|
||||
t.Fatal("invalid space resolved")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,7 @@ package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -12,10 +10,6 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// DingTalk login proxy. The scan-code login itself lives in the
|
||||
@@ -102,86 +96,15 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"})
|
||||
return
|
||||
}
|
||||
// dws 已经持有有效凭据(access 自动续期、refresh 一个月),登记也该走它:
|
||||
// 只有 dws 解析不出这个空间时,才回落到老的扫码侧车。
|
||||
if registered, ok := registerSpaceThroughDWS(w, r, config, strings.TrimSpace(input.URL), operationID); ok || registered {
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)})
|
||||
status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload)
|
||||
if status != http.StatusOK {
|
||||
if status == 0 {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"})
|
||||
return
|
||||
}
|
||||
// Relay the sidecar's error (login_required / space_not_found /
|
||||
// name_conflict) verbatim; bodies are machine codes, no secrets.
|
||||
writeProxyResult(w, status, data)
|
||||
return
|
||||
}
|
||||
var resolved struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
Root string `json:"root"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &resolved); err != nil || resolved.Key == "" || resolved.Name == "" || resolved.Root == "" {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "invalid sidecar registration response"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
|
||||
return
|
||||
}
|
||||
spaceID := extractDingtalkSpaceID(input.URL)
|
||||
if spaceID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid space url"})
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_name_conflict",
|
||||
"hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。",
|
||||
})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。",
|
||||
})
|
||||
return
|
||||
case err != nil:
|
||||
// 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
// First scan is enqueued right away: the new connection has no catalog
|
||||
// head yet, so the generic sources/{id}/refresh endpoint would 404 until
|
||||
// the first snapshot exists.
|
||||
if enqueuer, ok := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); ok {
|
||||
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(r.Context(), governance.CatalogSource{
|
||||
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: resolved.Name,
|
||||
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
|
||||
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
|
||||
}
|
||||
}
|
||||
log.Printf("dingtalk space %q registered as connection %s by %s", resolved.Name, connectionID, actorFor(r))
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
|
||||
"connection_id": connectionID, "name": resolved.Name,
|
||||
}})
|
||||
registerDWSOnlySpace(w, r, config, strings.TrimSpace(input.URL), operationID)
|
||||
}
|
||||
|
||||
var dingtalkSpacePattern = regexp.MustCompile(`/spaces/([A-Za-z0-9_-]+)`)
|
||||
|
||||
func extractDingtalkSpaceID(raw string) string {
|
||||
if !validDingtalkURL(raw) {
|
||||
return ""
|
||||
}
|
||||
match := dingtalkSpacePattern.FindStringSubmatch(raw)
|
||||
if len(match) == 2 {
|
||||
return match[1]
|
||||
@@ -244,76 +167,3 @@ func proxyDingtalk(method, path string, body []byte) (int, []byte) {
|
||||
}
|
||||
return resp.StatusCode, data
|
||||
}
|
||||
|
||||
// resolveSpaceViaDWS 用 dws 列举结果定位一个空间:返回确定性登记键、名称与根节点。
|
||||
// 认不出就 ok=false,调用方回落到老的扫码侧车(历史空间仍能被登记)。
|
||||
func resolveSpaceViaDWS(ctx context.Context, lister dingtalkSourcesLister, rawURL string) (rootKey, name, rootID, spaceID string, ok bool) {
|
||||
spaceID = extractDingtalkSpaceID(rawURL)
|
||||
if lister == nil || spaceID == "" {
|
||||
return "", "", "", "", false
|
||||
}
|
||||
discovered, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
return "", "", "", "", false
|
||||
}
|
||||
for _, base := range discovered.KnowledgeBases {
|
||||
if base.SpaceID == spaceID {
|
||||
// 知识库:URL 里的 id 就是空间 id,抓取侧按 spaces/<id> 匹配。
|
||||
return "space-" + spaceID, base.Name, spaceID, spaceID, true
|
||||
}
|
||||
}
|
||||
for _, space := range discovered.DriveSpaces {
|
||||
if space.SpaceID == spaceID && space.RootFolderID != "" {
|
||||
return "space-" + spaceID, space.Name, space.RootFolderID, spaceID, true
|
||||
}
|
||||
}
|
||||
return "", "", "", "", false
|
||||
}
|
||||
|
||||
// registerSpaceThroughDWS 用 dws 凭据直接登记来源,不再要求扫码会话。
|
||||
func registerSpaceThroughDWS(w http.ResponseWriter, r *http.Request, config Config, rawURL, operationID string) (bool, bool) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(ctx, config.DingtalkSources, rawURL)
|
||||
if !ok {
|
||||
return false, false
|
||||
}
|
||||
store, wired := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !wired {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
|
||||
return true, false
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: rootKey, Name: name, SpaceID: spaceID, RootID: rootID, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源,但空间标识不一致;请核对已有来源,不能按名称判定添加成功。"})
|
||||
return true, false
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试。",
|
||||
})
|
||||
return true, false
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return true, false
|
||||
}
|
||||
if enqueuer, wired := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); wired {
|
||||
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{
|
||||
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: name,
|
||||
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
|
||||
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
|
||||
}
|
||||
}
|
||||
log.Printf("dingtalk space %q registered as connection %s by %s (dws)", name, connectionID, actorFor(r))
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
|
||||
"connection_id": connectionID, "name": name,
|
||||
}})
|
||||
return true, true
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
@@ -123,7 +124,7 @@ func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) {
|
||||
|
||||
call := func(storeErr error) (int, string) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr}
|
||||
handler, err := NewHandler(Config{Store: store})
|
||||
handler, err := NewHandler(Config{Store: store, DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "公司级技术支持知识库", SpaceID: "9JOK9EEOMLMWX4Q"}}}}})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func registerDWSLoginRoutes(mux *http.ServeMux, config Config) {
|
||||
mux.HandleFunc("POST /api/v1/dws-login", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "start") })
|
||||
mux.HandleFunc("GET /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "get") })
|
||||
mux.HandleFunc("DELETE /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "cancel") })
|
||||
}
|
||||
|
||||
func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, action string) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "需要管理员身份才能管理 DWS 授权"})
|
||||
return
|
||||
}
|
||||
if action != "get" {
|
||||
originOK := true
|
||||
if raw := r.Header.Get("Origin"); raw != "" {
|
||||
origin, err := url.Parse(raw)
|
||||
originOK = err == nil && origin.Host == r.Host && (origin.Scheme == "http" || origin.Scheme == "https")
|
||||
}
|
||||
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != "dws-login" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "请从本平台的数据源配置页发起授权"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if config.DWSLogin == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "DWS 登录服务未接通,请联系管理员"})
|
||||
return
|
||||
}
|
||||
// Bind the challenge to this authenticated administrator and browser session.
|
||||
owner := identity.UserID + "/" + identity.SessionID
|
||||
var view dingtalkdiscovery.DeviceLoginView
|
||||
var err error
|
||||
switch action {
|
||||
case "start":
|
||||
view, err = config.DWSLogin.Start(owner)
|
||||
case "get":
|
||||
view, err = config.DWSLogin.Get(owner, r.PathValue("id"))
|
||||
case "cancel":
|
||||
view, err = config.DWSLogin.Cancel(owner, r.PathValue("id"))
|
||||
}
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, dingtalkdiscovery.ErrLoginNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "授权会话已结束或服务已重启,请重新发起"})
|
||||
case errors.Is(err, dingtalkdiscovery.ErrLoginBusy):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "另一位管理员正在授权,请稍后再试"})
|
||||
default:
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法发起 DWS 授权,请重试"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if config.PPConnection != nil && (action != "get" || view.State == "succeeded" || view.State == "failed" || view.State == "expired") {
|
||||
if err := config.PPConnection.AuditOnce(r.Context(), "dws-"+view.ID+"-"+string(view.State), "钉钉账号(DWS)", "dws_authorization", identity.Username, "DWS 授权状态:"+string(view.State)); err != nil {
|
||||
if action == "start" {
|
||||
_, _ = config.DWSLogin.Cancel(owner, view.ID)
|
||||
}
|
||||
writeJSON(w, 503, map[string]string{"error": "授权审计写入失败,请重试"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if action != "get" {
|
||||
log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username)
|
||||
}
|
||||
status := http.StatusOK
|
||||
if action == "start" {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"data": view})
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"})
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
if role != "" {
|
||||
r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session}))
|
||||
}
|
||||
r.Header.Set("Origin", origin)
|
||||
r.Header.Set("X-Governance-Action", intent)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, role := range []string{"", roleViewer, roleEngineer} {
|
||||
w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login")
|
||||
if w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("role=%q status=%d", role, w.Code)
|
||||
}
|
||||
}
|
||||
for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} {
|
||||
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1])
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("origin/intent not enforced: %d", w.Code)
|
||||
}
|
||||
}
|
||||
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login")
|
||||
if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("start=%d body=%s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Data dingtalkdiscovery.DeviceLoginView `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" {
|
||||
t.Fatal("missing session", err)
|
||||
}
|
||||
path := "/api/v1/dws-login/" + body.Data.ID
|
||||
for _, method := range []string{"GET", "DELETE"} {
|
||||
w = call(method, path, roleAdmin, "other-session", "", "dws-login")
|
||||
if w.Code != 404 {
|
||||
t.Fatalf("foreign session %s=%d", method, w.Code)
|
||||
}
|
||||
w = call(method, path, roleEngineer, "s1", "", "dws-login")
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("engineer %s=%d", method, w.Code)
|
||||
}
|
||||
}
|
||||
w = call("GET", path, roleAdmin, "s1", "", "")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("get=%d", w.Code)
|
||||
}
|
||||
w = call("DELETE", path, roleAdmin, "s1", "", "dws-login")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("cancel=%d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDWSLoginRoutesAreAdminOnly(t *testing.T) {
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
|
||||
for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} {
|
||||
if got := classifyRole(method, path); got != roleAdmin {
|
||||
t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dwsSourceError struct {
|
||||
Status int
|
||||
Code, Hint string
|
||||
}
|
||||
|
||||
func (e *dwsSourceError) Error() string { return e.Hint }
|
||||
func writeDWSSourceError(w http.ResponseWriter, err error) {
|
||||
var e *dwsSourceError
|
||||
if errors.As(err, &e) {
|
||||
writeJSON(w, e.Status, map[string]string{"error": e.Code, "hint": e.Hint})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 500, map[string]string{"error": "dws_source_failed", "hint": "读取钉钉来源失败,请重试"})
|
||||
}
|
||||
func availableDWS(ctx context.Context, config Config) (dingtalkdiscovery.Result, error) {
|
||||
identity := ""
|
||||
if config.DingtalkSources == nil {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{501, "dws_unwired", "DWS 来源服务未接通"}
|
||||
}
|
||||
if reader, ok := config.DingtalkSources.(interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
}); ok {
|
||||
status, err := reader.ReadDWSMetadata(ctx)
|
||||
if err != nil || !status.StatusKnown {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{503, "dws_status_unavailable", "暂时无法读取 DWS 授权状态,请重试"}
|
||||
}
|
||||
identity = status.Identity
|
||||
if !status.Authenticated && !status.RefreshTokenValid {
|
||||
return dingtalkdiscovery.Result{}, &dwsSourceError{401, "dws_login_required", "DWS 未登录或授权已失效,请重新授权"}
|
||||
}
|
||||
}
|
||||
result, err := config.DingtalkSources.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrCredentials) {
|
||||
return result, &dwsSourceError{401, "dws_login_required", "DWS 授权已失效,请重新授权"}
|
||||
}
|
||||
if errors.Is(err, dingtalkdiscovery.ErrPermission) {
|
||||
return result, &dwsSourceError{403, "dws_permission_denied", "当前 DWS 账号缺少目录读取权限"}
|
||||
}
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
return result, &dwsSourceError{503, "dws_unavailable", "DWS 目录暂时无法读取,请检查连接后重试"}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
if identity != "" {
|
||||
reader := config.DingtalkSources.(interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
})
|
||||
fresh, e := reader.ReadDWSMetadata(ctx)
|
||||
if e != nil {
|
||||
return result, &dwsSourceError{503, "dws_status_unavailable", "无法确认当前账号,请重试"}
|
||||
}
|
||||
if fresh.Identity != identity {
|
||||
return result, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"}
|
||||
}
|
||||
}
|
||||
result.Identity = identity
|
||||
if config.Store != nil {
|
||||
if page, e := config.Store.ListSourceConnections(ctx); e == nil {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range page.Items {
|
||||
seen[c.ID] = true
|
||||
}
|
||||
for i, kb := range result.KnowledgeBases {
|
||||
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + kb.SpaceID}
|
||||
result.KnowledgeBases[i].Registered = seen[in.ConnectionID()]
|
||||
}
|
||||
for i, space := range result.DriveSpaces {
|
||||
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + space.SpaceID}
|
||||
result.DriveSpaces[i].Registered = seen[in.ConnectionID()]
|
||||
}
|
||||
}
|
||||
}
|
||||
if registry, ok := config.Store.(interface {
|
||||
RegisteredDingtalkSpaceIDs(context.Context) (map[string]bool, error)
|
||||
}); ok {
|
||||
ids, e := registry.RegisteredDingtalkSpaceIDs(ctx)
|
||||
if e != nil {
|
||||
return result, &dwsSourceError{503, "dws_registration_state_unavailable", "无法核对已接入空间,请重试"}
|
||||
}
|
||||
for i, kb := range result.KnowledgeBases {
|
||||
result.KnowledgeBases[i].Registered = ids[kb.SpaceID]
|
||||
}
|
||||
for i, space := range result.DriveSpaces {
|
||||
result.DriveSpaces[i].Registered = ids[space.SpaceID]
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func resolveDWS(result dingtalkdiscovery.Result, raw string) (postgresstore.RegisterDingtalkSpaceInput, error) {
|
||||
spaceID := extractDingtalkSpaceID(raw)
|
||||
if spaceID == "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"}
|
||||
}
|
||||
for _, base := range result.KnowledgeBases {
|
||||
if base.SpaceID == spaceID {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: base.Name, RootID: spaceID, SpaceID: spaceID}, nil
|
||||
}
|
||||
}
|
||||
for _, space := range result.DriveSpaces {
|
||||
if space.SpaceID == spaceID && space.RootFolderID != "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: space.Name, RootID: space.RootFolderID, SpaceID: spaceID}, nil
|
||||
}
|
||||
}
|
||||
if result.KnowledgeNotice != "" || result.DriveNotice != "" {
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{503, "dws_scope_incomplete", "当前目录结果不完整,无法确认所选空间;请检查相应目录权限后重试"}
|
||||
}
|
||||
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{409, "dws_space_not_visible", "当前 DWS 账号已看不到所选空间,请刷新范围或核对账号权限"}
|
||||
}
|
||||
func registerDWSOnlySpace(w http.ResponseWriter, r *http.Request, config Config, raw, operationID string) {
|
||||
if extractDingtalkSpaceID(raw) == "" {
|
||||
writeDWSSourceError(w, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
|
||||
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
|
||||
return
|
||||
}
|
||||
input, err := resolveDWS(result, raw)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
input.Now = config.Now()
|
||||
input.Actor = actorFor(r)
|
||||
store, ok := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, 503, map[string]string{"error": "registration_unavailable"})
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, 409, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源仍在使用:请核对空间身份,必要时先移除旧连接(原去掉来源操作)"})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, 409, map[string]string{"error": "space_identity_conflict", "hint": "登记键已指向另一个空间,请刷新后核对来源"})
|
||||
return
|
||||
case err != nil:
|
||||
writeJSON(w, 500, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
queued := false
|
||||
if queue, ok := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); ok {
|
||||
_, _, err = queue.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: input.Name}, "dws-source-first:"+connectionID, config.Now().UTC())
|
||||
queued = err == nil
|
||||
}
|
||||
writeJSON(w, 201, map[string]any{"data": map[string]any{"connection_id": connectionID, "name": input.Name, "first_scan_queued": queued}})
|
||||
}
|
||||
func validateDWSSpace(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !credentialAdmin(w, r, "dingtalk-space") {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
if decodeJSONStrict(r, &input) != nil || len(input.URLs) == 0 || len(input.URLs) > 100 {
|
||||
writeJSON(w, 400, map[string]string{"error": "请选择有效的空间范围"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
result, err := availableDWS(ctx, config)
|
||||
if err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
|
||||
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
|
||||
return
|
||||
}
|
||||
for _, raw := range input.URLs {
|
||||
if _, err := resolveDWS(result, raw); err != nil {
|
||||
writeDWSSourceError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"valid": true, "checked_at": config.Now().UTC(), "count": len(input.URLs)}})
|
||||
}
|
||||
func validDingtalkURL(raw string) bool {
|
||||
if !strings.Contains(raw, "://") {
|
||||
return true
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && u.Scheme == "https" && u.Host == "alidocs.dingtalk.com" && u.User == nil && u.Fragment == ""
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDWSRegistrationNeverFallsBackToBrowserSession(t *testing.T) {
|
||||
calls := 0
|
||||
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(401) }))
|
||||
defer sidecar.Close()
|
||||
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
|
||||
h, err := NewHandler(Config{Store: &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}}, DingtalkSources: fakeDingtalkSources{err: dingtalkdiscovery.ErrUnavailable}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/valid-space-id/overview"}`))
|
||||
req.Header.Set("Idempotency-Key", "op-dws-only")
|
||||
req.Header.Set("X-Governance-Action", "dingtalk-space")
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if calls != 0 || rec.Code != 503 || !strings.Contains(rec.Body.String(), "dws_unavailable") {
|
||||
t.Fatalf("DWS failed: legacy calls=%d status=%d body=%s", calls, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
// KBBindingStore is the environment-scoped 「知识库绑定」capability. Save does
|
||||
// the real candidate read itself, so the HTTP layer decides no policy beyond
|
||||
// status/role.
|
||||
type KBBindingStore interface {
|
||||
List(context.Context) ([]kbbinding.View, error)
|
||||
Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error)
|
||||
Save(context.Context, string, kbbinding.SaveInput, string, time.Time) (kbbinding.View, error)
|
||||
ResolveBaseURL(context.Context, string) string
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
views, err := config.KBBindings.List(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load knowledge base bindings"})
|
||||
return
|
||||
}
|
||||
storageReady := false
|
||||
for _, view := range views {
|
||||
storageReady = storageReady || view.StorageReady
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.CatalogInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": catalog})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.SaveInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view, "operation": "saved"})
|
||||
}
|
||||
|
||||
func writeKBBindingError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, kbbinding.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "绑定参数不合法:请检查地址、密钥与内外库选择"})
|
||||
case errors.Is(err, kbbinding.ErrConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "该环境的绑定已被其他保存更新;草稿未写入,旧绑定保持不变,请重新读取后再试"})
|
||||
case errors.Is(err, kbbinding.ErrKeyForwarding):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址"})
|
||||
case errors.Is(err, kbbinding.ErrNotConfigured):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "这个地址还没有可用 API Key:请输入密钥或先选择已配置的连接"})
|
||||
case errors.Is(err, kbbinding.ErrStorage):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "独立安全存储未就绪(WEKNORA_BINDING_MASTER_KEY_FILE);未写入任何绑定"})
|
||||
case errors.Is(err, kbbinding.ErrRejected):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrRejected.Error()+":")})
|
||||
case errors.Is(err, kbbinding.ErrUnreachable):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrUnreachable.Error()+":")})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
type fakeKBBindings struct {
|
||||
views []kbbinding.View
|
||||
catalog kbbinding.Catalog
|
||||
saveErr error
|
||||
catalogErr error
|
||||
lastSave kbbinding.SaveInput
|
||||
lastActor string
|
||||
}
|
||||
|
||||
func (fake *fakeKBBindings) List(context.Context) ([]kbbinding.View, error) {
|
||||
return fake.views, nil
|
||||
}
|
||||
func (fake *fakeKBBindings) Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) {
|
||||
return fake.catalog, fake.catalogErr
|
||||
}
|
||||
func (fake *fakeKBBindings) Save(_ context.Context, _ string, input kbbinding.SaveInput, actor string, _ time.Time) (kbbinding.View, error) {
|
||||
fake.lastSave = input
|
||||
fake.lastActor = actor
|
||||
if fake.saveErr != nil {
|
||||
return kbbinding.View{}, fake.saveErr
|
||||
}
|
||||
return fake.views[0], nil
|
||||
}
|
||||
func (fake *fakeKBBindings) ResolveBaseURL(context.Context, string) string { return "" }
|
||||
|
||||
func kbBindingHandler(t *testing.T, store KBBindingStore) *Config {
|
||||
t.Helper()
|
||||
config := &Config{KBBindings: store, Now: func() time.Time { return time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) }}
|
||||
return config
|
||||
}
|
||||
|
||||
func TestKBBindingsReadNeverEchoesSecretsAndWriteRequiresIntent(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{
|
||||
Environment: kbbinding.EnvTest, Revision: 2, BaseURL: "https://weknora.test.example",
|
||||
KeyConfigured: true, KeySource: "sealed", InternalKBID: "kb-in", InternalKBName: "内部",
|
||||
ExternalKBID: "kb-out", ExternalKBName: "对外", Source: "web", StorageReady: true,
|
||||
}}}
|
||||
config := kbBindingHandler(t, store)
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, forbidden := range []string{"api_key", "key_ciphertext", "sealed-key-value"} {
|
||||
if strings.Contains(body, forbidden) {
|
||||
t.Fatalf("read response exposes %q: %s", forbidden, body)
|
||||
}
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("save without intent status = %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
|
||||
store := &fakeKBBindings{
|
||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}},
|
||||
saveErr: kbbinding.ErrConflict,
|
||||
}
|
||||
config := kbBindingHandler(t, store)
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "旧绑定保持不变") {
|
||||
t.Fatalf("conflict status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
|
||||
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}}
|
||||
config := kbBindingHandler(t, store)
|
||||
body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
|
||||
request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") {
|
||||
t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "typed-key") {
|
||||
t.Fatal("catalog response echoed the typed key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||
for _, path := range []string{"/api/v1/kb-bindings/test", "/api/v1/kb-bindings/test/catalog"} {
|
||||
if role := classifyRole(http.MethodPut, path); role != roleAdmin {
|
||||
t.Fatalf("PUT %s role = %s, want admin", path, role)
|
||||
}
|
||||
if role := classifyRole(http.MethodGet, "/api/v1/kb-bindings"); role != roleViewer {
|
||||
t.Fatalf("GET bindings role = %s, want viewer", role)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// libraryCaptureReconciler is deliberately narrow: it repairs one business
|
||||
// seal job only after the completed capture queue, the successful export stage,
|
||||
// the exact test-sealed version and the archived bytes all agree. It never
|
||||
// captures, freezes writers, creates snapshots, writes source/target content or
|
||||
// changes historical failure evidence.
|
||||
type libraryCaptureReconciler interface {
|
||||
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
|
||||
LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error)
|
||||
LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error)
|
||||
EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error)
|
||||
ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error)
|
||||
ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error)
|
||||
}
|
||||
|
||||
const (
|
||||
legacyOrphanError = "队列中已无对应作业,业务作业未收到结果"
|
||||
legacyOrphanRecovery = "封存作业由 agent 恢复来源;确认来源 healthy 后可重发"
|
||||
)
|
||||
|
||||
type libraryCaptureQueueReader interface {
|
||||
QueueJob(ctx context.Context, id string) (jobs.Job, bool, error)
|
||||
}
|
||||
|
||||
func libraryCaptureReconcile(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(libraryCaptureReconciler)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "封存作业核对存储不可用"})
|
||||
return
|
||||
}
|
||||
queueStore, ok := config.Store.(libraryCaptureQueueReader)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "队列精确读取不可用"})
|
||||
return
|
||||
}
|
||||
jobID := strings.TrimSpace(r.PathValue("id"))
|
||||
if jobID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"})
|
||||
return
|
||||
}
|
||||
job, err := store.LibraryJob(r.Context(), jobID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
|
||||
return
|
||||
}
|
||||
if job.Kind != governance.LibraryJobSeal {
|
||||
conflict(w, "只有封存作业可以核对封存结果")
|
||||
return
|
||||
}
|
||||
systemMisclassified := job.State == governance.LibraryJobFailed && job.Stage == "" &&
|
||||
job.Error == legacyOrphanError && job.Recovery == legacyOrphanRecovery && job.SnapshotID == ""
|
||||
if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning &&
|
||||
job.State != governance.LibraryJobSucceeded && !systemMisclassified {
|
||||
conflict(w, "作业是真实失败/取消终态,不能改写成成功")
|
||||
return
|
||||
}
|
||||
if job.QueueJobID == "" {
|
||||
conflict(w, "作业没有关联队列号,不能证明封存完成")
|
||||
return
|
||||
}
|
||||
captureJob := strings.TrimPrefix(job.ID, "libseal-")
|
||||
if captureJob == "" || captureJob == job.ID {
|
||||
conflict(w, "作业号不是封存作业身份")
|
||||
return
|
||||
}
|
||||
queue, found, err := queueStore.QueueJob(r.Context(), job.QueueJobID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture queue"})
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
conflict(w, "队列作业不存在,不能证明封存完成")
|
||||
return
|
||||
}
|
||||
if queue.Type != libraryCaptureJobType || queue.State != jobs.StateCompleted {
|
||||
conflict(w, "队列作业不是 completed 的 library.capture")
|
||||
return
|
||||
}
|
||||
var payload struct {
|
||||
Scope string `json:"scope"`
|
||||
CaptureJob string `json:"capture_job"`
|
||||
}
|
||||
if err := json.Unmarshal(queue.Payload, &payload); err != nil ||
|
||||
payload.Scope != job.Scope || payload.CaptureJob != captureJob ||
|
||||
queue.IdempotencyKey != "library.capture:"+captureJob {
|
||||
conflict(w, "队列作业的 scope/capture_job/幂等键与业务作业不一致")
|
||||
return
|
||||
}
|
||||
stageState, _, err := store.LibraryCaptureExportEvidence(r.Context(), job.ID)
|
||||
if err != nil || stageState != "succeeded" {
|
||||
conflict(w, "导出阶段没有成功证据,不能修复终态")
|
||||
return
|
||||
}
|
||||
version, found, err := store.LibraryTestSealedVersionForJob(r.Context(), job.Scope, job.ID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read exact test-sealed version"})
|
||||
return
|
||||
}
|
||||
if !found || version.Kind != governance.LibraryVersionTestSealed ||
|
||||
version.Scope != job.Scope || version.SourceJobID != job.ID || version.SnapshotID == "" {
|
||||
conflict(w, "没有与作业/scope 精确绑定的测试封存版本")
|
||||
return
|
||||
}
|
||||
source := configuredLibrarySource(config, job.Scope)
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "来源身份配置不完整,无法核对封存来源"})
|
||||
return
|
||||
}
|
||||
evidenceSource, _ := version.Evidence["source_id"].(string)
|
||||
evidenceCapture, _ := version.Evidence["capture_job"].(string)
|
||||
if evidenceSource != sourceID || evidenceCapture != captureJob {
|
||||
conflict(w, "版本来源或 capture_job 与当前作业不一致")
|
||||
return
|
||||
}
|
||||
if config.LibraryArchiveRoot == "" {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "未接线归档根,无法复核归档完整性"})
|
||||
return
|
||||
}
|
||||
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "归档不可读,不能确认封存完整"})
|
||||
return
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(version.SnapshotID)
|
||||
if err != nil {
|
||||
conflict(w, "归档字节复核失败,不能修复作业")
|
||||
return
|
||||
}
|
||||
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID ||
|
||||
manifest.KnowledgeBaseID != source.KnowledgeBaseID {
|
||||
conflict(w, "归档清单来源身份与当前来源不一致")
|
||||
return
|
||||
}
|
||||
if job.SnapshotID != "" && job.SnapshotID != version.SnapshotID {
|
||||
conflict(w, "作业已有不同快照,不能覆盖")
|
||||
return
|
||||
}
|
||||
if job.State == governance.LibraryJobSucceeded {
|
||||
if job.SnapshotID != version.SnapshotID {
|
||||
conflict(w, "作业已成功但快照与精确版本不一致")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"repaired": false, "already_succeeded": true, "job_id": job.ID,
|
||||
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
|
||||
"version_id": version.ID,
|
||||
})
|
||||
return
|
||||
}
|
||||
actor := ""
|
||||
if identity, ok := sessionFrom(r.Context()); ok {
|
||||
actor = identity.Username
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
digest, err := governance.LibraryRequestDigest(job.Scope, governance.LibraryJobRecover, map[string]any{
|
||||
"kind": "capture_reconcile", "job_id": job.ID, "queue_job_id": queue.ID,
|
||||
"snapshot_id": version.SnapshotID, "capture_job": captureJob, "stage": "export",
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build reconcile audit digest"})
|
||||
return
|
||||
}
|
||||
if systemMisclassified {
|
||||
auditID := "librepair-" + digest[:16]
|
||||
updated, repairErr := store.ReconcileMisclassifiedLibraryCapture(r.Context(), job.ID, job.Scope,
|
||||
job.QueueJobID, version.SnapshotID, job.Stage, legacyOrphanError, legacyOrphanRecovery,
|
||||
job.FinishedAt, auditID, actor, "completed capture queue + export succeeded + exact version + archive verified; legacy orphan misclassification", map[string]any{
|
||||
"original_state": job.State, "original_error": job.Error, "original_recovery": job.Recovery,
|
||||
"original_finished_at": job.FinishedAt, "queue_job_id": queue.ID,
|
||||
"snapshot_id": version.SnapshotID, "version_id": version.ID, "archive_verified": true,
|
||||
}, now)
|
||||
if repairErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot persist misclassification repair"})
|
||||
return
|
||||
}
|
||||
if !updated {
|
||||
conflict(w, "原误判行状态/错误/完成时间已变化,拒绝覆盖")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"repaired": true, "already_succeeded": false, "misclassification_repaired": true,
|
||||
"job_id": job.ID, "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
|
||||
"stage": "export", "version_id": version.ID, "audit_repair_id": auditID,
|
||||
})
|
||||
return
|
||||
}
|
||||
opID := "libop-capture-reconcile-" + digest[:16]
|
||||
op, _, err := store.EnsureLibraryOperation(r.Context(), governance.LibraryOperation{
|
||||
ID: opID, Scope: job.Scope, Kind: governance.LibraryJobRecover,
|
||||
TargetSnapshotID: version.SnapshotID, RequestDigest: digest,
|
||||
OperationKey: "capture-reconcile:" + job.ID, Actor: actor, CreatedAt: now,
|
||||
})
|
||||
if errors.Is(err, governance.ErrLibraryOperationConflict) {
|
||||
conflict(w, "同一核对键对应了不同证据,拒绝修复")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record reconcile audit"})
|
||||
return
|
||||
}
|
||||
updated, err := store.ReconcileLibraryCaptureTerminal(r.Context(), job.ID, job.Scope, job.QueueJobID, version.SnapshotID, now)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{
|
||||
"error": "cannot persist reconciled job terminal", "audit_operation_id": op.ID,
|
||||
})
|
||||
return
|
||||
}
|
||||
if !updated {
|
||||
conflict(w, "作业状态/身份在核对期间变化,拒绝覆盖")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"repaired": true, "already_succeeded": false, "job_id": job.ID,
|
||||
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
|
||||
"stage": "export", "version_id": version.ID, "audit_operation_id": op.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func conflict(w http.ResponseWriter, reason string) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"available": false, "repaired": false, "reason": reason})
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
func (f *fakeLibraryStore) QueueJob(_ context.Context, id string) (jobs.Job, bool, error) {
|
||||
if f.queue == nil || f.queue.ID != id {
|
||||
return jobs.Job{}, false, nil
|
||||
}
|
||||
return *f.queue, true, nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryCaptureExportEvidence(_ context.Context, _ string) (string, string, error) {
|
||||
return f.stageState, "", f.stageErr
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryJobStage(_ context.Context, _, stage string) (string, string, error) {
|
||||
if f.stageErr != nil {
|
||||
return "", "", f.stageErr
|
||||
}
|
||||
if stage != "export" {
|
||||
return "", "", errors.New("unexpected stage")
|
||||
}
|
||||
return f.stageState, "", nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryTestSealedVersionForJob(_ context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
|
||||
if f.versionErr != nil {
|
||||
return governance.LibraryVersion{}, false, f.versionErr
|
||||
}
|
||||
if f.sealedVersion == nil || f.sealedVersion.Scope != scope || f.sealedVersion.SourceJobID != jobID {
|
||||
return governance.LibraryVersion{}, false, nil
|
||||
}
|
||||
return *f.sealedVersion, true, nil
|
||||
}
|
||||
|
||||
func reconcileFixture(t *testing.T) (*fakeLibraryStore, Config, governance.LibraryJob, []byte) {
|
||||
t.Helper()
|
||||
root := libraryFixtureRoot(t)
|
||||
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := archive.Load(snapshotID)
|
||||
archive.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := Config{LibraryArchiveRoot: root,
|
||||
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
|
||||
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
|
||||
source := configuredLibrarySource(config, "internal")
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := governance.LibraryJob{ID: "libseal-cap-1", Scope: "internal", Kind: governance.LibraryJobSeal,
|
||||
State: governance.LibraryJobPending, QueueJobID: "libcap-1"}
|
||||
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "cap-1"})
|
||||
store := &fakeLibraryStore{
|
||||
jobs: []governance.LibraryJob{job},
|
||||
stageState: "succeeded",
|
||||
queue: &jobs.Job{ID: "libcap-1", Type: libraryCaptureJobType, State: jobs.StateCompleted,
|
||||
Payload: payload, IdempotencyKey: "library.capture:cap-1"},
|
||||
sealedVersion: &governance.LibraryVersion{ID: "libver-1", Scope: "internal",
|
||||
Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshotID, SourceJobID: job.ID,
|
||||
Evidence: map[string]any{"source_id": sourceID, "capture_job": "cap-1"}},
|
||||
}
|
||||
config.Store = store
|
||||
return store, config, job, payload
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) ReconcileLibraryCaptureTerminal(_ context.Context, jobID, scope, queueJobID, snapshotID string, _ time.Time) (bool, error) {
|
||||
if f.reconcileDenied {
|
||||
return false, nil
|
||||
}
|
||||
for index := range f.jobs {
|
||||
if f.jobs[index].ID != jobID || f.jobs[index].Scope != scope || f.jobs[index].Kind != governance.LibraryJobSeal ||
|
||||
f.jobs[index].QueueJobID != queueJobID || (f.jobs[index].State != governance.LibraryJobPending && f.jobs[index].State != governance.LibraryJobRunning) ||
|
||||
(f.jobs[index].SnapshotID != "" && f.jobs[index].SnapshotID != snapshotID) {
|
||||
return false, nil
|
||||
}
|
||||
f.jobs[index].State = governance.LibraryJobSucceeded
|
||||
f.jobs[index].SnapshotID = snapshotID
|
||||
f.lastState = governance.LibraryJobSucceeded
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) ReconcileMisclassifiedLibraryCapture(_ context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, _ string, _ string, _ string, _ map[string]any, _ time.Time) (bool, error) {
|
||||
if f.reconcileDenied {
|
||||
return false, nil
|
||||
}
|
||||
for index := range f.jobs {
|
||||
j := &f.jobs[index]
|
||||
if j.ID != jobID || j.Scope != scope || j.Kind != governance.LibraryJobSeal || j.QueueJobID != queueJobID ||
|
||||
j.State != governance.LibraryJobFailed || j.Stage != expectedStage || j.Error != expectedError ||
|
||||
j.Recovery != expectedRecovery || j.SnapshotID != "" || (j.FinishedAt == nil) != (expectedFinished == nil) ||
|
||||
(j.FinishedAt != nil && expectedFinished != nil && !j.FinishedAt.Equal(*expectedFinished)) {
|
||||
return false, nil
|
||||
}
|
||||
j.State = governance.LibraryJobSucceeded
|
||||
j.SnapshotID = snapshotID
|
||||
j.Stage = "export"
|
||||
f.lastState = governance.LibraryJobSucceeded
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var _ libraryCaptureReconciler = (*fakeLibraryStore)(nil)
|
||||
|
||||
func runReconcile(t *testing.T, config Config, jobID string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+jobID+"/reconcile-capture", nil)
|
||||
req.SetPathValue("id", jobID)
|
||||
rec := httptest.NewRecorder()
|
||||
libraryCaptureReconcile(rec, req, config)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRepairsExactCompletedCapture(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["repaired"] != true || body["snapshot_id"] == "" || body["audit_operation_id"] == "" {
|
||||
t.Fatalf("body=%v", body)
|
||||
}
|
||||
if store.lastState != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("advanced state=%s", store.lastState)
|
||||
}
|
||||
if len(store.operations) != 1 {
|
||||
t.Fatalf("audit operations=%v", store.operations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileAlreadySucceededIsReadOnly(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.State = governance.LibraryJobSucceeded
|
||||
job.SnapshotID = store.sealedVersion.SnapshotID
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
if body["already_succeeded"] != true || body["repaired"] != false || store.lastState != "" {
|
||||
t.Fatalf("body=%v advanced=%q", body, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsQueueNotCompleted(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.queue.State = jobs.StateRunning
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsStageNotSucceeded(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.stageState = "failed"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsWrongVersionSource(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.Evidence["source_id"] = "other-source"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsWrongCaptureJob(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.Evidence["capture_job"] = "other-capture"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsBadArchive(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.SnapshotID = "missing-snapshot"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsFailedJob(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.State = governance.LibraryJobFailed
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileIsIdempotent(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
first := runReconcile(t, config, job.ID)
|
||||
if first.Code != http.StatusOK {
|
||||
t.Fatalf("first code=%d body=%s", first.Code, first.Body.String())
|
||||
}
|
||||
second := runReconcile(t, config, job.ID)
|
||||
if second.Code != http.StatusOK {
|
||||
t.Fatalf("second code=%d body=%s", second.Code, second.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(second.Body.Bytes(), &body)
|
||||
if body["already_succeeded"] != true || len(store.operations) != 1 {
|
||||
t.Fatalf("body=%v ops=%v", body, store.operations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsMissingQueue(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.queue = nil
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsQueueScope(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.queue.Payload, _ = json.Marshal(map[string]string{"scope": "external", "capture_job": "cap-1"})
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsMissingVersion(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion = nil
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsWrongScopeVersion(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.Scope = "external"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsDifferentExistingSnapshot(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.SnapshotID = "other-snapshot"
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileConditionalWriteRejectsConcurrentState(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.reconcileDenied = true
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRepairsExactLegacyMisclassification(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
finished := time.Now().UTC()
|
||||
job.State = governance.LibraryJobFailed
|
||||
job.Stage = ""
|
||||
job.Error = legacyOrphanError
|
||||
job.Recovery = legacyOrphanRecovery
|
||||
job.FinishedAt = &finished
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
if body["misclassification_repaired"] != true || store.lastState != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("body=%v advanced=%q", body, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsOtherFailedError(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
finished := time.Now().UTC()
|
||||
job.State = governance.LibraryJobFailed
|
||||
job.Stage = ""
|
||||
job.Error = "capture export failed"
|
||||
job.Recovery = legacyOrphanRecovery
|
||||
job.FinishedAt = &finished
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsRealFailureAndCancel(t *testing.T) {
|
||||
for _, state := range []governance.LibraryJobState{governance.LibraryJobFailed, governance.LibraryJobCancelled} {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.State = state
|
||||
job.Error = "real failure"
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("state=%s code=%d advanced=%q", state, rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileMisclassificationCASRejectsChange(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
finished := time.Now().UTC()
|
||||
job.State = governance.LibraryJobFailed
|
||||
job.Stage = ""
|
||||
job.Error = legacyOrphanError
|
||||
job.Recovery = legacyOrphanRecovery
|
||||
job.FinishedAt = &finished
|
||||
store.jobs[0] = job
|
||||
store.reconcileDenied = true
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// Vertical PostgreSQL path: the real worker startup reconciliation must leave
|
||||
// a pending seal with a completed capture queue intact, then the actual HTTP
|
||||
// handler must verify archive/version/stage and repair it. This is not a fake
|
||||
// store or a direct helper test.
|
||||
func verticalReconcileFixture(t *testing.T) (*postgresstore.Store, Config, string, *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("isolated database required")
|
||||
}
|
||||
cfg.MaxConns = 1
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TEMP TABLE library_jobs(
|
||||
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
|
||||
state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '',
|
||||
idempotency_key varchar(255) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL DEFAULT '',
|
||||
queue_job_id varchar(64) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '',
|
||||
target_snapshot_id varchar(64) NOT NULL DEFAULT '', actor varchar(128) NOT NULL DEFAULT '',
|
||||
error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
|
||||
operation_id varchar(64) NOT NULL DEFAULT '', attempt_epoch integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, finished_at timestamptz,
|
||||
target_id text NOT NULL DEFAULT '');
|
||||
CREATE TEMP TABLE library_job_stages(
|
||||
job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL,
|
||||
total bigint, completed bigint, bytes_total bigint, bytes_done bigint,
|
||||
detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage));
|
||||
CREATE TEMP TABLE library_versions(
|
||||
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL,
|
||||
snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '',
|
||||
source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '',
|
||||
attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL, superseded_at timestamptz);
|
||||
CREATE TEMP TABLE library_job_repairs(
|
||||
id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL,
|
||||
kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL,
|
||||
original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '',
|
||||
original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '',
|
||||
original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
|
||||
evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL);
|
||||
CREATE TEMP TABLE library_operations(
|
||||
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
|
||||
target_snapshot_id varchar(64) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL,
|
||||
operation_key varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL, target_id text NOT NULL DEFAULT '',
|
||||
first_backup_snapshot_id varchar(64), first_backup_bytes bigint, first_backup_at timestamptz,
|
||||
writeset_digest varchar(64), writeset_rows bigint, target_fingerprint varchar(128), anchors_at timestamptz);
|
||||
CREATE UNIQUE INDEX library_operations_key_test ON library_operations(scope,kind,operation_key);
|
||||
CREATE TEMP TABLE jobs(
|
||||
id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, payload jsonb NOT NULL,
|
||||
state varchar(16) NOT NULL, priority integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL,
|
||||
lease_owner varchar(128), lease_until timestamptz, attempt integer NOT NULL DEFAULT 0,
|
||||
max_attempts integer NOT NULL DEFAULT 1, last_error text, idempotency_key varchar(255) NOT NULL,
|
||||
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL);`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := libraryFixtureRoot(t)
|
||||
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := archive.Load(snapshotID)
|
||||
archive.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := Config{LibraryArchiveRoot: root,
|
||||
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
|
||||
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
|
||||
source := configuredLibrarySource(config, "internal")
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical"})
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
|
||||
VALUES('q-vertical','library.capture',$1,'completed',$2,'library.capture:vertical',$2,$2)`, payload, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
|
||||
VALUES('ver-vertical','internal','test_sealed',$1,'libseal-vertical',$2,$3)`, snapshotID,
|
||||
map[string]any{"source_id": sourceID, "capture_job": "vertical"}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
|
||||
VALUES('libseal-vertical','export','succeeded','已封存快照', $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := postgresstore.NewStore(pool)
|
||||
config.Store = store
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,created_at,updated_at)
|
||||
VALUES('libseal-vertical','internal','seal','pending','k','d','q-vertical',$1,$1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, config, snapshotID, pool
|
||||
}
|
||||
|
||||
func TestStartupReconcileThenHandlerRepairsPendingCapture(t *testing.T) {
|
||||
store, config, _, _ := verticalReconcileFixture(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
|
||||
t.Fatalf("startup reconcile n=%d err=%v", n, err)
|
||||
}
|
||||
job, err := store.LibraryJob(ctx, "libseal-vertical")
|
||||
if err != nil || job.State != governance.LibraryJobPending {
|
||||
t.Fatalf("startup changed job: %+v err=%v", job, err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical/reconcile-capture", nil)
|
||||
req.SetPathValue("id", "libseal-vertical")
|
||||
rec := httptest.NewRecorder()
|
||||
libraryCaptureReconcile(rec, req, config)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
job, err = store.LibraryJob(ctx, "libseal-vertical")
|
||||
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID == "" {
|
||||
t.Fatalf("handler did not repair: %+v err=%v", job, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupReconcilePreservesFailedCapturesForExactReconcile(t *testing.T) {
|
||||
store, config, snapshotID, pool := verticalReconcileFixture(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
source := configuredLibrarySource(config, "internal")
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical-failed"})
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
|
||||
VALUES('q-failed','library.capture',$1,'completed',$2,'library.capture:vertical-failed',$2,$2)`, payload, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
|
||||
VALUES('ver-failed','internal','test_sealed',$1,'libseal-vertical-failed',$2,$3)`,
|
||||
snapshotID, map[string]any{"source_id": sourceID, "capture_job": "vertical-failed"}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
|
||||
VALUES('libseal-vertical-failed','export','succeeded','已封存快照', $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
finished := now.Truncate(time.Microsecond)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,error,recovery,created_at,updated_at,finished_at)
|
||||
VALUES('libseal-vertical-failed','internal','seal','failed','kf','df','q-failed',$1,$2,$3,$3,$3)`,
|
||||
"队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", finished); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
|
||||
t.Fatalf("startup reconcile n=%d err=%v", n, err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical-failed/reconcile-capture", nil)
|
||||
req.SetPathValue("id", "libseal-vertical-failed")
|
||||
rec := httptest.NewRecorder()
|
||||
libraryCaptureReconcile(rec, req, config)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
job, err := store.LibraryJob(ctx, "libseal-vertical-failed")
|
||||
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID != snapshotID {
|
||||
t.Fatalf("failed misclassification not repaired: %+v err=%v", job, err)
|
||||
}
|
||||
var originalState, originalError string
|
||||
if err := pool.QueryRow(ctx, `SELECT original_state, original_error FROM library_job_repairs WHERE job_id='libseal-vertical-failed'`).
|
||||
Scan(&originalState, &originalError); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if originalState != "failed" || originalError == "" {
|
||||
t.Fatalf("audit missing original: state=%q error=%q", originalState, originalError)
|
||||
}
|
||||
}
|
||||
@@ -342,7 +342,11 @@ type libraryOverview struct {
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
CaptureReason string `json:"capture_reason,omitempty"`
|
||||
Executor libraryExecutorView `json:"executor"`
|
||||
Now time.Time `json:"now"`
|
||||
// 实际目标身份:页面不能只显示"weknora-test"或旧文档级绑定名称。
|
||||
TargetInstance string `json:"target_instance,omitempty"`
|
||||
TargetProject string `json:"target_project,omitempty"`
|
||||
TargetKnowledgeBaseID string `json:"target_knowledge_base_id,omitempty"`
|
||||
Now time.Time `json:"now"`
|
||||
}
|
||||
|
||||
// libraryVersionRef 只回答"这个快照被登记成哪一类版本、由哪个作业登记"。
|
||||
@@ -595,6 +599,11 @@ func testSealedOf(versions []governance.LibraryVersion, byID map[string]libraryS
|
||||
// 它刻意只说配置:能停写入者/关入口/证明排空的真实能力在 worker 侧(docker socket、
|
||||
// 闸门、排空文件),API 若声称"能力可用"就是拿配置字符串冒充执行证据。
|
||||
func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
mode := strings.TrimSpace(config.LibraryTargetIngressMode)
|
||||
if mode == "" {
|
||||
mode = "gate"
|
||||
}
|
||||
noGate := mode == "none"
|
||||
missing := make([]string, 0, 6)
|
||||
if config.LibraryTargetInstance == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INSTANCE")
|
||||
@@ -605,11 +614,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
if len(config.LibraryTargetWriters) == 0 {
|
||||
missing = append(missing, "LIBRARY_TARGET_WRITERS")
|
||||
}
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
if noGate {
|
||||
// 没有闸门:页面必须如实说"无闸门(测试模式)",不能显示"打开"。
|
||||
if config.LibraryTargetHealthURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
|
||||
}
|
||||
} else {
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
}
|
||||
}
|
||||
if config.LibraryTargetJournalRoot == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
|
||||
@@ -617,12 +633,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
if config.LibraryTargetDockerSocket == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_DOCKER_SOCKET")
|
||||
}
|
||||
ingressState := "闸门"
|
||||
if noGate {
|
||||
ingressState = "无闸门(测试模式)"
|
||||
}
|
||||
return map[string]any{
|
||||
"configured": len(missing) == 0,
|
||||
"missing": missing,
|
||||
"instance": config.LibraryTargetInstance,
|
||||
"project": config.LibraryTargetProject,
|
||||
"writers": config.LibraryTargetWriters,
|
||||
"ingress_mode": mode,
|
||||
"ingress_state": ingressState,
|
||||
"ingress_service": config.LibraryTargetIngressService,
|
||||
"note": "配置齐全只说明治理侧接线完整;停写入者、关入口与排空由 worker 在作业内校验并执行",
|
||||
}
|
||||
@@ -642,9 +664,7 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
gate.Reasons = append(gate.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
gate.Reasons = append(gate.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
|
||||
}
|
||||
gate.Reasons = append(gate.Reasons, restoreGateReasons(config)...)
|
||||
// 生产端点以"整库目标是否配置"为准:整库同步直接写 PG/ES/对象,
|
||||
// 不依赖 WeKnora 的 HTTP 端,所以不能拿它是否配置当门禁。
|
||||
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
|
||||
@@ -688,10 +708,16 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now,
|
||||
TargetInstance: config.LibraryTargetInstance, TargetProject: config.LibraryTargetProject,
|
||||
Gate: libraryGateView{Reasons: []string{}},
|
||||
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
|
||||
// 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。
|
||||
overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config)
|
||||
if scope == "internal" {
|
||||
overview.TargetKnowledgeBaseID = config.LibraryProductionInternalKB
|
||||
} else {
|
||||
overview.TargetKnowledgeBaseID = config.LibraryProductionExternalKB
|
||||
}
|
||||
|
||||
// 测试封存来自归档 + 版本登记:归档里**不止**测试封存——生产预备份与目标基线
|
||||
// 快照同样带 scope,如果只按"这个 scope 最新一份"挑,页面就会把目标自己的内容
|
||||
@@ -814,7 +840,8 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
|
||||
grant, hasGrant := activeGrantFor(r.Context(), config, scope, target)
|
||||
overview.Authorization = authorizationViewOf(grant, hasGrant)
|
||||
overview.Gate = librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, target, hasGrant)
|
||||
// 闸口按当前目标的真实恢复证据判断(没有证据时也接受历史 env 覆盖)。
|
||||
overview.Gate = librarySyncGateWithGrant(config.withRestoreEvidence(r.Context(), scope), overview.Production, overview.Prebackup, target, hasGrant)
|
||||
writeJSON(w, http.StatusOK, overview)
|
||||
}
|
||||
|
||||
@@ -963,7 +990,7 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
gate := librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, request.Target, hasGrant)
|
||||
gate := librarySyncGateWithGrant(config.withRestoreEvidence(r.Context(), request.Scope), overview.Production, overview.Prebackup, request.Target, hasGrant)
|
||||
if !gate.SyncAllowed {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_sync_blocked", "reasons": gate.Reasons,
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证
|
||||
@@ -37,6 +38,13 @@ type fakeLibraryStore struct {
|
||||
resumeOK bool
|
||||
resumeErr error
|
||||
resumeCalls []string
|
||||
// capture reconciliation fixtures
|
||||
queue *jobs.Job
|
||||
stageState string
|
||||
stageErr error
|
||||
sealedVersion *governance.LibraryVersion
|
||||
versionErr error
|
||||
reconcileDenied bool
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
|
||||
@@ -127,8 +135,16 @@ func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error {
|
||||
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, _, _, _, snapshotID, _ string, _ time.Time) error {
|
||||
f.lastState = state
|
||||
for index := range f.jobs {
|
||||
if f.jobs[index].ID == jobID {
|
||||
f.jobs[index].State = state
|
||||
if snapshotID != "" {
|
||||
f.jobs[index].SnapshotID = snapshotID
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -266,3 +266,25 @@ func TestLibraryReadPathsRejectTamperedManifest(t *testing.T) {
|
||||
t.Fatalf("storage must fail closed: status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// F11: the HTTP projection must include binding and Wiki log counts; the
|
||||
// previous projection silently omitted them and the UI turned absence into 0.
|
||||
func TestLibrarySnapshotTotalsIncludeBindingsAndWikiLogs(t *testing.T) {
|
||||
view := librarySnapshotViewOfNoUsage("snap-totals", librarysnapshot.Manifest{
|
||||
Scope: "internal", KnowledgeBaseID: "kb", TenantID: 10000,
|
||||
Parts: []librarysnapshot.Part{
|
||||
{Kind: "database", Name: "knowledges", Count: 4},
|
||||
{Kind: "database", Name: "chunks", Count: 38},
|
||||
{Kind: "database", Name: "resources", Count: 21},
|
||||
{Kind: "database", Name: "resource_bindings", Count: 4},
|
||||
{Kind: "wiki", Name: "wiki_pages", Count: 31},
|
||||
{Kind: "wiki", Name: "wiki_folders", Count: 21},
|
||||
{Kind: "wiki", Name: "wiki_log_entries", Count: 11},
|
||||
},
|
||||
})
|
||||
for key, want := range map[string]int64{"documents": 4, "chunks": 38, "resources": 21, "bindings": 4, "wiki_pages": 31, "wiki_folders": 21, "wiki_log_entries": 11} {
|
||||
if view.Totals[key] != want {
|
||||
t.Fatalf("totals[%s]=%d want=%d (%v)", key, view.Totals[key], want, view.Totals)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,9 +71,7 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
reasons = append(reasons, "生产写入闸口关闭")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
reasons = append(reasons, "没有已核验的生产恢复演练证据")
|
||||
}
|
||||
reasons = append(reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), request.Scope))...)
|
||||
authorizationOK := false
|
||||
if storeWithAuth, ok := config.Store.(interface {
|
||||
ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error)
|
||||
@@ -169,9 +167,7 @@ func libraryRestoreAvailability(w http.ResponseWriter, r *http.Request, config C
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
view.Reasons = append(view.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
view.Reasons = append(view.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
|
||||
}
|
||||
view.Reasons = append(view.Reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), scope))...)
|
||||
digest, err := libraryRestoreParamsDigest(scope, snapshotID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"})
|
||||
@@ -228,9 +224,7 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
reasons = append(reasons, "生产写入闸口关闭")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
reasons = append(reasons, "没有已核验的生产恢复演练证据")
|
||||
}
|
||||
reasons = append(reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), source.Scope))...)
|
||||
var digest string
|
||||
switch source.Kind {
|
||||
case governance.LibraryJobSync:
|
||||
|
||||
@@ -261,10 +261,14 @@ func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest)
|
||||
}
|
||||
case "resources":
|
||||
snapshot.Totals["resources"] = part.Count
|
||||
case "resource_bindings":
|
||||
snapshot.Totals["bindings"] = part.Count
|
||||
case "wiki_pages":
|
||||
snapshot.Totals["wiki_pages"] = part.Count
|
||||
case "wiki_folders":
|
||||
snapshot.Totals["wiki_folders"] = part.Count
|
||||
case "wiki_log_entries":
|
||||
snapshot.Totals["wiki_log_entries"] = part.Count
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshot.Parts, func(i, j int) bool {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user