Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 73413c59ee | |||
| 32c773e24d | |||
| f97c62cc99 | |||
| ca870564b0 | |||
| 6539a6b77c | |||
| 424a75d516 | |||
| 144b49cb53 | |||
| 65476750b0 | |||
| b59ec66387 | |||
| 7801c163e4 | |||
| 15dbc2469b | |||
| da568dfa2c | |||
| 7b4ec1f89d | |||
| 6a6fa7129a | |||
| c12152529c | |||
| 4d73aa999b | |||
| cc289b63e5 | |||
| 9ddc3291cc | |||
| 32c7074f41 | |||
| 7926c8e8b9 | |||
| bb57a9835c | |||
| 49f9994ea6 | |||
| 501fbae6ff | |||
| 45aef5016a | |||
| c90cb803fa |
+1
-2
@@ -28,8 +28,7 @@ QA_AI_MASTER_KEY_FILE=
|
|||||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||||
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。
|
# 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。
|
||||||
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
|
|
||||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||||
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
||||||
QA_AI_DNS_OVER_TLS=
|
QA_AI_DNS_OVER_TLS=
|
||||||
|
|||||||
@@ -80,3 +80,39 @@ jobs:
|
|||||||
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
||||||
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
||||||
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
||||||
|
notify:
|
||||||
|
needs: [guard, publish]
|
||||||
|
if: always()
|
||||||
|
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
|
||||||
|
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: 上报 ci-bridge(发布结果,通知失败不改变发布结论)
|
||||||
|
if: always()
|
||||||
|
env:
|
||||||
|
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
|
||||||
|
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
|
||||||
|
CI_PUBLIC_BASE_URL: https://gitea.zheromiku.top
|
||||||
|
GUARD_RESULT: ${{ needs.guard.result }}
|
||||||
|
PUBLISH_RESULT: ${{ needs.publish.result }}
|
||||||
|
DEPLOY_SHA: ${{ inputs.sha }}
|
||||||
|
DEPLOY_BUNDLE: ${{ inputs.bundle }}
|
||||||
|
DEPLOY_TASK: ${{ inputs.task }}
|
||||||
|
run: |
|
||||||
|
set +e; set +o pipefail
|
||||||
|
B="${BRIDGE_URL:-}"
|
||||||
|
for cand in "$B" "http://172.17.0.1:8899" "http://192.168.50.134:8899" "http://100.92.49.78:8899"; do
|
||||||
|
if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi
|
||||||
|
done
|
||||||
|
echo "使用 ci-bridge: ${B:-(不可达)}"
|
||||||
|
CI_BRIDGE_RESOLVED="$B" python3 scripts/cd_notify.py
|
||||||
|
echo "上报结束(通知失败不改变发布结论)"
|
||||||
|
|||||||
+102
@@ -1,5 +1,107 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 开发快照 0.1.425(WeKnora 0.9.1:schema 137 + 漏表门禁 + 编辑历史搬运)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **libraryprofile 新增 v0.9.1(137)**:由 v0.9.0 声明克隆,只改版本字段;`For(137)`/`Supported()`
|
||||||
|
与错误信息同步。135–137 只改审计列宽/凭据表/IM 唯一索引,不碰知识域,测试断言 v090/v091
|
||||||
|
除版本外逐字段相等。
|
||||||
|
- **知识域关联表分类**:每个版本声明 `copied/derived/excluded` 及理由;覆盖真实 0.9.x 的 18 张
|
||||||
|
候选表与条件迁移的 `embeddings`。
|
||||||
|
- **漏表门禁**:导出前(源库只读快照事务)与导入前(写事务内、DELETE 前)扫描带
|
||||||
|
`knowledge_base_id/knowledge_id/kb_id` 的表;未分类且有本库数据 → `release_undeclared_kb_table`
|
||||||
|
(表名+行数,不可重试);未分类空表放行并留警告(导入侧写入 `WriteSet.Warnings`)。
|
||||||
|
- **编辑历史搬运**:`chunk_revisions`、`wiki_page_revisions` 进入 v090/v091 的必需表与归档部件,
|
||||||
|
复用范围改写 + 目标身份映射 + 自然键预检;插在父表之后、删除/回滚先删两表;只导出活跃父行,
|
||||||
|
父行完全缺失即拒绝;唯一索引映射后仍唯一;`editor_id` 原样保留(目标显示未知编辑者)。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **兼容性(人类裁定 Q1=B)**:两表部件为 **RequiredParts**。T1 部署前生成的 0.9.0 库归档/预备份
|
||||||
|
将因缺少这两个部件而无法加载;升级前如需保留回滚能力,先在旧版本完成回滚或保留旧二进制。
|
||||||
|
- 修订正文不参与资源发现(Q2=B):`resource://` 文本原样保留;资源作用域/校验/恢复保护统一排除两表。
|
||||||
|
- 同步 `docs/library-target-id-mapping.md`、`docs/library-data-contract.md`、`docs/library-capture.md`,
|
||||||
|
并按 T0 要求把 `docs/architecture/three-agent-handoff-workflow.md` §2 的 main 直推改为分支 + PR。
|
||||||
|
|
||||||
|
## 开发快照 0.1.424(存储与备份:删批次前预检,失败零删除)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **配额清理会把旧批次删一半再失败**:`shutil.rmtree` 先删子项、最后删目录,批次根只读时
|
||||||
|
失败发生在内容已清空之后,调用方只看到非 0 退出却打印「旧备份未被删除」。现在删除分三段:
|
||||||
|
逐目录可写性检查 + 同父目录改名探针(不动内容)→ 全部改名成 `.prune-<pid>-<戳>` 隔离
|
||||||
|
(原子、不进批次候选)→ 才真删。任一预检或改名失败整体回滚、**零删除**(新退出码 `5`);
|
||||||
|
真删阶段才失败时报隔离路径(`rc=4`),`logical-backup.sh` 按 `rc` 区分提示,不再误报。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)改由 `scripts/prune_backup_batches.py --rotate` 实现,
|
||||||
|
与配额清理共用同一套预检/隔离/回滚,删掉 `logical-backup.sh` 里的第二份内联 `rmtree`。
|
||||||
|
self-test 增加预检零删除、改名失败回滚、只读批次根、轮转与遗留隔离目录用例。
|
||||||
|
|
||||||
|
## 开发快照 0.1.423(存储与备份:配额改按备份根占用)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **页面配额行读错数据源**:`归档占用` 卡片读 `/api/v1/library/storage`(`runtime/library`
|
||||||
|
归档库,现场 1.67 MB),与 `/srv/kb-backups` 的整库逻辑备份无关;现改为「备份占用 X / 配额 50 GB」,
|
||||||
|
只读宿主采集器上报的备份根累计占用。归档库接口仍服务归档写入门禁,不再被本页调用。
|
||||||
|
- **备份没有按字节的执行路径**:`logical-backup.sh` 过去只有按份数/月份轮转;现在 dump 前按
|
||||||
|
`KB_BACKUP_QUOTA_BYTES` 预检,最旧优先清理且保留最新一份,空间仍不够时零删除并取消本次备份;
|
||||||
|
dump 后复查并保护本次新批次。只删 `rds-logical` 完整批次,`es-snapshots`/`target-kb-snapshots`/
|
||||||
|
`logs` 与 `*.incomplete` 不动。
|
||||||
|
- **根占用不完整不牵连批次**:采集器对根树遍历失败时 `usage.actual_bytes=null`,批次表与磁盘容量仍可用;
|
||||||
|
旧采集器快照缺 `usage/quota` 时显式「未上报」,不用批次和冒充。
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- 采集器 `collect_backup_metadata.py` 新增 `--usage-root/--quota-bytes/--config`,快照新增
|
||||||
|
`backup_root/usage/quota_bytes/quota_error`(加性字段,schema 仍为 1),根占用与 `du -sB1` 对拍。
|
||||||
|
- `scripts/prune_backup_batches.py`:配额清理独立工具 + self-test(最旧优先、预检保留最新、
|
||||||
|
不足零删除、非批次日录/符号链接不动、dump 后保护新批次)。
|
||||||
|
- API 校验 `usage.root == BACKUP_HOST_ROOT`,占用与配额不完整/非法时只降级对应字段;
|
||||||
|
`install_backup_schedule.sh --show` 增加备份根占用/配额读数。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `backup_layout.sh` 把 `KB_BACKUP_QUOTA_BYTES=53687091200` 写入 `backup.env`(已有值不覆盖);
|
||||||
|
页面 4 条容量告警的配额项统一改用备份占用/配额,磁盘项仍取文件系统实测值。
|
||||||
|
- 契约与核验命令更新到 `docs/STORAGE_BACKUP_READONLY_API.md`、`docs/PRODUCTION_BACKUP_RECOVERY.md`。
|
||||||
|
|
||||||
|
## 开发快照 0.1.422(知识库绑定:不再按控制台传输形态拦截 Key)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **非 HTTPS 控制台仍无法录入 API Key**:页面删除 `secret_entry_allowed` 能力位与
|
||||||
|
`secure`/`keyEntryBlocked` 传输判定,服务端删除 KB 专用的
|
||||||
|
`secretTransportAllowedForPrivateConsole` 写侧校验。管理员在任意同源控制台都能录入/
|
||||||
|
更换 Key,不再出现「可输入但保存 400」的半修复。
|
||||||
|
- **提示与录入门禁解耦**:非 HTTPS、非回环页面保留「当前通过明文 HTTP 访问:录入的
|
||||||
|
API Key 会在内网明文传输。」,只提示不阻断;HTTPS 页面不再提示反代是否受信。
|
||||||
|
- **保存落审计**:`weknora_environment_binding_history` 同一事务写入操作人、时间、
|
||||||
|
环境、客户端地址与控制台来源(`source_address`/`source_origin`),明文录入事后可追溯;
|
||||||
|
来源只做取证,不参与放行判定,解析不出就留空而不猜值。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `WEKNORA_ALLOW_PRIVATE_HTTP` 仅控制治理 API/worker 访问同网段 http 目标,不再决定
|
||||||
|
控制台密钥录入。问答 AI 模型密钥仍走严格 HTTPS/回环校验;管理员、`X-Governance-Action`
|
||||||
|
写意图与 Key 不回显边界不变。Web 与 API 是独立镜像,须同批次发布/回滚:旧 Web 对新
|
||||||
|
API 会禁用录入,新 Web 对旧 API 仍会被 400 拒绝。
|
||||||
|
|
||||||
|
## 开发快照 0.1.421(负责人手动切换需求状态)
|
||||||
|
|
||||||
|
- 原需求单在候选就绪和主站发布成功时回填回执,负责人按回执手动切换状态。
|
||||||
|
|
||||||
|
## 开发快照 0.1.420(需求单候选排队)
|
||||||
|
|
||||||
|
- 需求单预检通过后自动排队等待验收环境,构建链接回填原单。已发布批次释放其测试容器,接续下一张需求。
|
||||||
|
|
||||||
|
## 开发快照 0.1.419(候选预检识别落地 merge)
|
||||||
|
|
||||||
|
- 预检支持从含多个版本号的提交链中识别 `落地 merge`,并分别提示缺少和存在多个落地版本。
|
||||||
|
|
||||||
## 开发快照 0.1.418(原需求单发布)
|
## 开发快照 0.1.418(原需求单发布)
|
||||||
|
|
||||||
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
|
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
|
||||||
|
|||||||
+1
-1
@@ -1978,7 +1978,7 @@
|
|||||||
"Settings"
|
"Settings"
|
||||||
],
|
],
|
||||||
"operationId": "getBackupScheduleInventory",
|
"operationId": "getBackupScheduleInventory",
|
||||||
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
|
"summary": "读取宿主元数据快照:批次、子库完整路径、备份根累计占用、配额与文件系统容量(陈旧/不完整一律未知)",
|
||||||
"responses": {
|
"responses": {
|
||||||
"200": {
|
"200": {
|
||||||
"$ref": "#/components/responses/Envelope"
|
"$ref": "#/components/responses/Envelope"
|
||||||
|
|||||||
@@ -349,6 +349,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
|||||||
BackupInventory: backupinventory.New(backupinventory.Config{
|
BackupInventory: backupinventory.New(backupinventory.Config{
|
||||||
MetadataPath: config.BackupHostMetadataPath,
|
MetadataPath: config.BackupHostMetadataPath,
|
||||||
HostRoot: config.BackupHostReadonlyHostPath,
|
HostRoot: config.BackupHostReadonlyHostPath,
|
||||||
|
BackupRoot: config.BackupHostRoot,
|
||||||
Source: backupInventorySource(config),
|
Source: backupInventorySource(config),
|
||||||
MaxAge: config.BackupHostMetadataMaxAge,
|
MaxAge: config.BackupHostMetadataMaxAge,
|
||||||
}),
|
}),
|
||||||
|
|||||||
+1
-1
@@ -69,7 +69,7 @@ services:
|
|||||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||||
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
||||||
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。
|
# 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。
|
||||||
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
||||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||||
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
|
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Advance original-task candidate queue
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=%h/.local/lib/kg-candidate-release/python3 %h/.local/lib/kg-candidate-release/scripts/candidate_queue.py
|
||||||
|
TimeoutStartSec=180
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Check reviewed demand tasks waiting for QA
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnStartupSec=30s
|
||||||
|
OnUnitInactiveSec=45s
|
||||||
|
AccuracySec=5s
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
# 知识治理候选和批次验收
|
# 知识治理候选和批次验收
|
||||||
|
|
||||||
|
## 需求单的六个状态
|
||||||
|
|
||||||
|
新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
|
||||||
|
|
||||||
## 在原需求单发布
|
## 在原需求单发布
|
||||||
|
|
||||||
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后进入「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
||||||
|
|
||||||
## 旧版独立发布单的存量操作
|
## 旧版独立发布单的存量操作
|
||||||
|
|
||||||
@@ -30,6 +34,20 @@
|
|||||||
|
|
||||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||||
|
|
||||||
|
### 候选访问测试 WeKnora
|
||||||
|
|
||||||
|
候选容器不能直连测试宿主的内网地址。宿主用 `kg-qa-weknora-test-hop.service` 把 `0.0.0.0:18090` 转到测试 WeKnora 的 `127.0.0.1:8092`,候选与所有 docker 网桥都能通过 `http://172.17.0.1:18090` 访问;`172.17.0.1` 是 docker0 的固定地址,换候选不变。绑定地址要填 IP,服务端不接受主机名。API Key 由测试负责人经授权渠道录入,不写进评论。
|
||||||
|
|
||||||
|
### 候选的知识库绑定密钥
|
||||||
|
|
||||||
|
验收候选运行在 QA 库上,知识库绑定需要独立的 32 字节主密钥。执行器在 `~/.local/state/kg-candidate-release/qa-binding-master.key` 维护唯一一份(0600、属主为容器应用用户),以只读方式挂到 API 与 worker 的 `/run/qa/binding-master.key`。所有候选共用这一份,已保存的绑定在下一轮候选仍可解开。文件缺失时首个候选自动生成;权限、长度或属主不符时拒绝启动,不静默降级。
|
||||||
|
|
||||||
|
### 原需求单的逐项报告
|
||||||
|
|
||||||
|
测试机将 `scripts/qa_report.py` 安装为 `~/.local/bin/kg-qa-report`。在 QA 的 HiFox 任务会话中,从本轮测试设计取得完整编号,保存到 `plan.json` 的 `business`、`regression` 数组。执行 `kg-qa-report init <任务> plan.json sheet.json` 读取原单候选回执并生成待填清单。测试中填写各编号的 `status`(`passed`、`failed`、`blocked`)和 `evidence`。`candidate_check` 记录指定候选部署上的实际验证结果及证据。环境受阻时记录原因。
|
||||||
|
|
||||||
|
使用 `kg-qa-report check <任务> plan.json sheet.json` 预检。缺失项按编号提示。使用同一参数将 `check` 换为 `submit` 后,由 QA 本人的 HiFox 执行上下文发表评论。回执变化时,工具会提示重新核对。登记端重新核算汇总和候选实测结论。
|
||||||
|
|
||||||
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||||
|
|
||||||
## 执行器配置
|
## 执行器配置
|
||||||
|
|||||||
@@ -0,0 +1,243 @@
|
|||||||
|
# 需求书:解析监控重构为「导入对账」
|
||||||
|
|
||||||
|
> 状态:v0.5(2026-11-30),已批准;Q1、Q5、Q6、Q7、Q9、Q10、Q11 已裁定。
|
||||||
|
> 依据:本仓 `origin/main` `ca87056` 与上游 WeKnora v0.9.1 源码(`~/weknora-explore/WeKnora-v0.9.1`)的直接阅读。
|
||||||
|
> 本期总计划、分工与工单拆分见 [WEKNORA_091_PHASE_PLAN.md](WEKNORA_091_PHASE_PLAN.md);本文是其中 T6 的需求正文。
|
||||||
|
|
||||||
|
## 1. 背景与结论
|
||||||
|
|
||||||
|
现「解析监控」(`internal/monitoring`、`internal/httpapi/monitor_tasks.go`、`web/src/WeKnoraMonitor.tsx`、`web/src/monitorTasks.ts`)做三件事:服务探活、按测试库统计处理状态、文件处理大表(筛选/重试/详情)。其中「解析」「索引增强」两个阶段的进度与失败细节,是平台轮询 WeKnora 后转述出来的。
|
||||||
|
|
||||||
|
WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5895):按文档查看入库与 Wiki 进度、处理阶段、历史失败。平台再把这些阶段细节转述一遍,等于和上游做同一件事,违反硬约束 1,而且转述永远比源头旧。
|
||||||
|
|
||||||
|
**结论:WeKnora 内部的处理细节交给 WeKnora 看;平台只做 WeKnora 看不到、也只有平台能做的事:把「台账 ↔ 知识库」(之后扩展到「来源 ↔ 台账」「测试库 ↔ 生产库」)对起来,发现并处置不一致。** 页面由「解析监控」改为「导入对账」。
|
||||||
|
|
||||||
|
⚠️ **边界**:台账上的 `processing_state` 是**工作流状态**,审核、组批、发布门禁都依赖它,**本需求不删除它**,也不改写平台轮询 WeKnora 确认完成的逻辑。去掉的只是界面上"解析阶段明细"这层转述;台账状态与 WeKnora 实际状态不一致的情况,由对账的 R5 发现并修正。
|
||||||
|
|
||||||
|
## 2. 职责划分
|
||||||
|
|
||||||
|
| 问题 | 归属 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 取件、上传是否成功 | 平台 | WeKnora 收到文件之前的阶段,上游看不到 |
|
||||||
|
| 解析/切片/向量/Wiki 进行到哪一步、为何失败 | WeKnora | 平台按需实时读取展示,不落库、不自建阶段机 |
|
||||||
|
| 解析失败后重新解析 | WeKnora(仅测试环境) | 一期只给跳转链接。生产只做推理,任何重解析都不能指向生产 |
|
||||||
|
| 该在库里的是否都在、在的是否该在、内容是否最新 | **平台(本需求核心)** | 只有平台同时掌握来源身份、台账与目标库 |
|
||||||
|
| 应下架内容是否已移除 | 平台 | 依据来源策略 `policy_state=blocked` |
|
||||||
|
|
||||||
|
## 3. 分期
|
||||||
|
|
||||||
|
| 期 | 对账两侧 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| **一期(本期)** | 平台台账(`test_publications` 中 `superseded_at IS NULL` 的行)↔ 测试 WeKnora 知识库 | 两侧数据都已具备;依赖测试 WeKnora 已升级到 v0.9.1 |
|
||||||
|
| 二期 | 来源 ↔ 平台台账 | 漏取、来源已删除平台仍现行;各来源扫描能力不同,需逐源确认 |
|
||||||
|
| 三期 | 测试库 ↔ 生产库 | 生产只做推理,内容全部由整库发布从测试搬运,所以这一期核对的是"搬运是否完整"。复用 `librarysnapshot`/`librarydiff`,按稳定 ID 和内容摘要比对 |
|
||||||
|
|
||||||
|
下文只展开一期。
|
||||||
|
|
||||||
|
### 3.1 一期边界:只对测试库;生产的下架靠发布链路
|
||||||
|
|
||||||
|
一期只对测试 WeKnora 做对账,**生产库没有对账对象**。生产的下架保证不在本需求内,它依赖两段已有链路:
|
||||||
|
|
||||||
|
1. 来源判 `blocked`:`planned` 行置 `superseded_at`,来源项 `policy_state='blocked'`(`policy_intents.go`)。
|
||||||
|
2. 变更集确认后:已入库行置 `retrieval_state='disabling'` 并入队 `test.remove`,移除完成后为 `disabled`(`change_set_execution.go`、`publication_removal.go`)。
|
||||||
|
3. 下一轮整库发布以测试库为源做 diff,生产库里多出来的文档判 `Removed` 后删除。
|
||||||
|
|
||||||
|
所以**生产下架的最迟时间 = 测试移除完成 + 下一次整库发布**。两次发布之间的空窗期,生产仍可检索已被判禁止的内容,一期发现不了。这一条必须写进页面的范围说明;是否再显示「距上次整库发布 N 天」见 Q8(未裁定)。
|
||||||
|
|
||||||
|
## 4. 差异类型(一期)
|
||||||
|
|
||||||
|
**身份配对口径(已核实)**:平台上传时写入 `metadata.publication_id`、`metadata.content_sha256`,并设 `channel=governance`(`internal/workflows/testweknora/upload.go`,main 上第 141 行起);台账记录 `knowledge_id`。配对优先用 `knowledge_id`,其次用 `metadata.publication_id`。
|
||||||
|
|
||||||
|
⚠️ WeKnora 对相同字节去重,同一份文件放在两个来源目录时,**多条台账可以合法地指向同一个 knowledge**(同文件中 ErrConflict 分支的收养逻辑)。只有能找到收养的审计证据才算合法(与陷阱 16 同理)。
|
||||||
|
|
||||||
|
**两个谓词(全文只用这两个;不再出现未定义的「现行行」)**
|
||||||
|
|
||||||
|
- `ledger_current`:`test_publications.superseded_at IS NULL`。用于 R2、R8 反查台账,以及所有“现行”计数。
|
||||||
|
- `ledger_expected_live`:`ledger_current` 且 `knowledge_id <> ''`、`processing_state <> 'failed'`、`retrieval_state NOT IN ('disabling','disabled')`。用于 R1、R4、R5、R7 的正向核对。
|
||||||
|
|
||||||
|
`ledger_expected_live` 必须排除 `disabling`/`disabled`:移除完成只改 `retrieval_state`,`knowledge_id` 会保留(`publication_removal.go` 的 `RecordRemovalCompleted`),不排除就会把正常下架的条目永久误报成 R1。
|
||||||
|
|
||||||
|
| 编号 | 差异 | 判定口径 | 默认处置 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| R1 丢失 | 台账认为应仍在库,库里没有 | `ledger_expected_live`,且单条 `GET /knowledge/{id}` 返回 404;“列表里没看到”不算证据 | 建议「重排上传」(复用现有动作) |
|
||||||
|
| R2 孤儿 | 库里有平台导入的条目,台账没有现行行指向它 | `channel=governance`,且 `metadata.publication_id` 没有 `ledger_current` 台账行,也没有 `ledger_current` 行以 `knowledge_id` 指向它;同字节被兄弟台账合法收养(其 `publication_id` 有 `ledger_current` 行)不算孤儿 | 只报告;移除走现有「测试库移除」,需人工确认 |
|
||||||
|
| R3 非平台导入 | 库里有不是平台导入的条目 | `channel≠governance` | 只统计、单列,不算错误 |
|
||||||
|
| R4 内容过期 | 库里的内容不是台账现行版本 | `ledger_expected_live`;`metadata.content_sha256` ≠ 台账现行版本 sha256(来源链见下),或有独立 MD5 证据且与 `file_hash` 不符 | 建议重新上传 |
|
||||||
|
| R5 状态不一致 | 两边状态长期对不上 | 台账 `processing_state` 与 WeKnora `parse_status` 按 §4 矩阵归一后不同,且以 `run.started_at` 计算已超过宽限期(默认 30 分钟,可配);回写受迁移表约束 | 人工点击「以 WeKnora 为准回写」,写审计 |
|
||||||
|
| R6 应下架仍在 | 来源已判禁止导入,库里仍可检索 | `superseded_at IS NULL`、`knowledge_id<>''`、`processing_state='completed'`、`retrieval_state NOT IN ('disabling','disabled')`、`item.policy_state='blocked'`;**与 `/monitor/overview` 的「需下架」共用同一个实现**,不得两处各写一遍 | 进入现有「需下架」流程 |
|
||||||
|
| R7 卡住 | 长时间没有进展 | 上游 `stall_state=stalled`;或 `pending`/`processing` 超过阈值(默认 2 小时,可配,按 `run.started_at` 计算);或 `deleting` 超过同一阈值(删除卡住) | 展示 WeKnora 阶段与失败记录,并给出跳转 |
|
||||||
|
| R8 一对多异常 | 一条台账对应多个现行条目 | 同 tenant、同 KB 下按 `metadata.publication_id` 分组,**排除 `parse_status` 为 `failed`/`deleting` 的条目**后仍大于 1。上游去重作用域是「同 tenant + 同 KB + 同 file_type + file_hash,排除 failed/deleting」(`repository/knowledge.go:435-466`),所以“同 hash 一条 failed + 一条现役”“同字节 .md 与 .txt”都是合法共存,不进 R8 | 只报告,人工处理 |
|
||||||
|
|
||||||
|
**状态归一与判定矩阵**
|
||||||
|
|
||||||
|
上游 `parse_status`:`pending` / `processing` / `finalizing` / `completed` / `failed` / `cancelled` / `deleting`(`internal/types/knowledge.go`)。台账 `processing_state`:`planned` / `pending` / `processing` / `finalizing` / `completed` / `failed` / `stalled`。
|
||||||
|
|
||||||
|
归一表(上游 → 台账词汇):`pending→pending`、`processing→processing`、`finalizing→finalizing`、`completed→completed`、`failed→failed`、`cancelled→cancelled`、`deleting→deleting`。`cancelled`、`deleting` 在台账没有对应状态,保留原名,**不得静默归到“其他”**。
|
||||||
|
|
||||||
|
判定矩阵(行 = 台账,列 = 归一后的上游状态):
|
||||||
|
|
||||||
|
| 台账 \ 上游 | pending | processing | finalizing | completed | failed | cancelled | deleting |
|
||||||
|
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||||
|
| planned | — | — | — | — | — | — | — |
|
||||||
|
| pending | ✓ | G | G | G | G | G | D |
|
||||||
|
| processing | G | ✓ | G | G | G | G | D |
|
||||||
|
| finalizing | G | G | ✓ | G | G | G | D |
|
||||||
|
| completed | G | G | G | ✓ | G | G | D |
|
||||||
|
| failed | G | G | G | G | ✓ | G | D |
|
||||||
|
| stalled | S | S | S | G | S | S | D |
|
||||||
|
|
||||||
|
- ✓ 一致。
|
||||||
|
- G:超过宽限期报 R5;`completed` 行对任何 G 只报告、`suggested_action=none`(禁止把已完成降级)。
|
||||||
|
- S:报 R7,展示上游阶段与失败记录。
|
||||||
|
- D:等待删除完成;超过 2 小时仍是 `deleting` 转 R7。
|
||||||
|
- —:`planned` 正常没有 `knowledge_id`,不比较;若出现 `planned` 且有 `knowledge_id`,按 G 处理并标为台账异常。
|
||||||
|
|
||||||
|
矩阵只写在服务端一处;接口以 `normalized_state` 字段直接返回归一结果,前端不内置映射表(前端拿不到 Go 常量)。
|
||||||
|
|
||||||
|
**内容校验的证据链**:台账的 sha256 不在 `test_publications` 上,来源链固定为 `test_publications.source_item_version_id → source_item_versions.content_object_id → content_objects.sha256`;实现不得为此在台账加列。
|
||||||
|
|
||||||
|
- `metadata.content_sha256`:平台上传时写入的**声明**。
|
||||||
|
- `file_hash`:WeKnora 对收到字节算的 **MD5**(上游 `knowledge_util.go:131`),**独立证据**。
|
||||||
|
- 本期起上传时在台账新增 `upload_md5`(迁移),对账用它与 `file_hash` 比对。
|
||||||
|
|
||||||
|
证据等级:`independent`(声明 sha256 与 MD5 都可核且一致)、`declared_only`(历史数据只有 `metadata` 声明)、`none`(metadata 缺失或无 MD5 可比)。只有前两级可判 R4;`none` 只统计、不判差异。
|
||||||
|
|
||||||
|
## 5. 数据来源(已核实上游接口)
|
||||||
|
|
||||||
|
| 用途 | WeKnora 接口 | 鉴权 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 全量列出库内条目 | `GET /knowledge-bases/{id}/knowledge`(分页;可按 `parse_status`、`source`、时间、目录筛选) | 现有租户 API Key |
|
||||||
|
| 单条确认 | `GET /knowledge/{id}` | 现有租户 API Key |
|
||||||
|
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | **平台级 API Key,能力 `system_runtime_read`**(上游 `routes_auth_tenant.go:356`) |
|
||||||
|
| 队列深度 | `GET /system/admin/runtime/queues` | 同上 |
|
||||||
|
|
||||||
|
条目中对账要用的字段:`id`、`knowledge_base_id`、`channel`、`metadata`、`file_hash`、`parse_status`、`stall_state`、`enable_status`、`updated_at`。
|
||||||
|
|
||||||
|
**扫描参数**:列表接口 `page_size` 的上游上限是 1000(`types/search.go:320`),对账必须用 1000;平台现有客户端把上限卡在 100(`internal/platform/weknora/client.go:361`),T6a 要为对账放开到 1000,不能沿用上传恢复的 100。1 万条的库因此是 10 次请求而不是 100 次。
|
||||||
|
|
||||||
|
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
|
||||||
|
|
||||||
|
**平台级 Key 的配置契约(Q7 已裁定)**
|
||||||
|
|
||||||
|
- 键名 `WEKNORA_RUNTIME_KEY_FILE`,值为**绝对路径**,secret 文件挂载进容器;不写进 compose 环境变量、不进 Git。
|
||||||
|
- 启动时读取一次,权限 0400;换 Key 需重启平台(与现有 `*_API_KEY_FILE` 一致,不做热加载)。
|
||||||
|
- “变量为空”与“变量有值但文件缺失/不可读”要区分:前者静默降级;后者启动不失败,写一条 WARN 日志,运行时按未配置处理。
|
||||||
|
- 两种情况都让 `runtime/queues`、`runtime/documents/{id}` 返回 503 `runtime_read_unavailable`,`/monitor/overview` 的 `weknora_queues` 为 `null`;对账本身只需租户 Key,照常运行。
|
||||||
|
|
||||||
|
## 6. 运行方式
|
||||||
|
|
||||||
|
- **对账批次**:每次对账生成一个批次(run),记录开始/结束时间、两侧计数、各类差异计数和明细。结果持久化,可以和上一成功批次比较。触发方式:定时(默认每天 02:00,可配)+ 页面手动触发。
|
||||||
|
- **唯一观测时刻**:批次以 `run.started_at` 作为唯一的“现在”。R5 宽限期、R7 阈值和所有相对时间判断都用它,不用 `time.Now()`。同一批次因此可重放、可解释,验收里的“连续两次一致”才有定义。
|
||||||
|
- **全量扫描必须完整**:整页翻完才算完成,中途失败整批标为 `failed`,不产出部分结论。不能用“最近 N 条”代替全量(陷阱 17)。扫描使用 `page_size=1000`(§5)。这里的“完整”指本批把所有页翻完,不承诺对并发写入做快照:扫描期间有增删时可能漏掉个别条目,漏掉的在下一批补上,批次记 `window_overlapped` 供解释;不为此引入游标或重扫(Q10)。
|
||||||
|
- **先确认再判缺**:R1、R2 定论前必须逐条单独读一次(`GET /knowledge/{id}`),区分 404、`deleting` 和翻页窗口漂移;没有单条证据的 R1/R2 不写 finding。
|
||||||
|
- **并发**:同一测试库同时只能有一个 `running` 批次,用部分唯一索引兜底:`CREATE UNIQUE INDEX ... ON reconciliation_runs(test_kb_id) WHERE state='running'`;应用层的 409 只是友好提示。
|
||||||
|
- **僵死批次回收(Q11)**:`running` 超过 6 小时(可配)视为失败,启动或下次触发时自动置 `failed` 并释放并发位;否则进程崩溃会让该库永久 409。
|
||||||
|
- **与整库导出/发布重叠(Q6 已裁定)**:不互斥。批次开始或运行期间检测到整库导出/发布作业在跑,则 `run.window_overlapped=true`;该批次的 R1、R2 照常写入,但 `confirmation_state='pending'`,页面显示「待确认」,计数保留。
|
||||||
|
- **findings 保留(Q5 已裁定)**:`runs` 永久保留(含 counts/previous_counts);`findings` 只保留**最近 30 批且不超过 90 天**,超出后按 `run_id` 整批删除,不逐行删。清理在每批对账结束后执行,幂等;删明细不影响批次计数和历史对比。
|
||||||
|
- **对账只读**:对账过程不向 WeKnora 发起任何写请求。处置动作是人点击触发的独立动作,复用现有带审计的动作。
|
||||||
|
- **并发与限速**:默认全程串行(同一时刻只有 1 个在途请求)。翻页**不并发**:offset 分页本来就会漂,并发只会让重复/漏页更难复现;R1/R2 的单条确认可以小并发,配置项 `reconciliation_confirm_concurrency`,默认 1、上限 8。**不复用入库的 `ingestion_concurrency`**:对账是夜间批处理,1 万条也只有 10 次翻页请求,不需要和取件/上传抢配额。
|
||||||
|
|
||||||
|
## 7. 接口契约(后端 T6a 与前端 T6b 的分界线)
|
||||||
|
|
||||||
|
T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,作为冻结契约;T6b 按契约在 T6a 之后开发(同一执行人,只改 `web/`)。契约以后要改,必须 T6a/T6b 两边都确认,并同步更新本节。
|
||||||
|
|
||||||
|
响应风格、错误体、鉴权方式沿用现有 `/api/v1/monitor/*` 的约定。响应中不得出现 URL 凭据、Key、Authorization。
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 | 角色 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| POST | `/api/v1/reconciliation/runs` | 请求体 `{test_kb_id}`;返回 202 和 run 对象;该库已有运行中批次时返回 409 `reconciliation_run_in_progress` | 管理员、文档工程师 |
|
||||||
|
| GET | `/api/v1/reconciliation/runs?test_kb_id=&limit=&offset=` | 批次列表,按开始时间倒序 | 所有登录角色 |
|
||||||
|
| GET | `/api/v1/reconciliation/runs/{id}` | 单个批次 | 所有登录角色 |
|
||||||
|
| GET | `/api/v1/reconciliation/runs/{id}/findings?type=&q=&limit=&offset=` | 差异明细,`limit` ≤ 100 | 所有登录角色 |
|
||||||
|
| POST | `/api/v1/reconciliation/findings/{id}/writeback` | 仅限 R5:以 WeKnora 状态回写台账,写审计;返回更新后的 finding | 管理员、文档工程师 |
|
||||||
|
| POST | `/api/v1/reconciliation/findings/{id}/requeue` | 仅限 R1/R4:R1 清空 `knowledge_id` 后重排上传;R4 先删旧 knowledge 再重传,删除失败则动作失败且台账不变;写审计 | 管理员、文档工程师 |
|
||||||
|
| POST | `/api/v1/reconciliation/findings/{id}/remove` | 仅限 R2:按 `knowledge_id` 从测试库删除,404 视为已删除;写审计;重复点击幂等 | 管理员 |
|
||||||
|
| GET | `/api/v1/reconciliation/documents/{knowledge_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key 时返回 503 `runtime_read_unavailable` | 所有登录角色 |
|
||||||
|
| GET | `/api/v1/monitor/overview`(已有) | 新增 `weknora_queues` 字段(来自 `runtime/queues`,不可用时为 null);删除 Embedding/LLM 两张常量"未知"卡 | 不变 |
|
||||||
|
|
||||||
|
**run 对象**:`id`、`test_kb_id`、`state`(`running` \| `succeeded` \| `failed`)、`trigger`(`schedule` \| `manual`)、`started_at`(同时是观测时刻)、`finished_at`、`ledger_count`、`kb_count`、`counts`(键为 R1–R8,值为整数)、`previous_counts`(上一成功批次的 counts,没有则为 null)、`window_overlapped`(bool,Q6)、`error_code`。
|
||||||
|
|
||||||
|
**finding 对象**:`id`、`run_id`、`type`(R1–R8)、`publication_id`、`knowledge_id`、`title`、`path`、`source`、`target_scope`、`ledger_state`、`weknora_parse_status`、`normalized_state`(按 §4 矩阵归一后的值,供前端直接显示)、`ledger_sha256`、`declared_sha256`、`weknora_file_md5`、`evidence_level`(`independent` \| `declared_only` \| `none`)、`confirmation_state`(`confirmed` \| `pending`,仅 R1/R2 在 `window_overlapped` 批次里可为 pending)、`detail`(中文一句话)、`suggested_action`(`requeue_upload` \| `remove_from_test` \| `writeback_state` \| `enter_removal` \| `none`)、`action_state`(`open` \| `done`)、`weknora_url`(在 WeKnora 中打开的链接,可为空)。
|
||||||
|
|
||||||
|
**R5 回写的迁移约束**(`POST /api/v1/reconciliation/findings/{id}/writeback`)
|
||||||
|
|
||||||
|
| 当前台账 | 允许回写到 |
|
||||||
|
| --- | --- |
|
||||||
|
| `pending` | `processing`、`finalizing`、`completed`、`failed` |
|
||||||
|
| `processing` | `finalizing`、`completed`、`failed` |
|
||||||
|
| `finalizing` | `completed`、`failed` |
|
||||||
|
| `failed` | `pending`、`processing`、`completed` |
|
||||||
|
| `stalled` | `pending`、`processing`、`failed` |
|
||||||
|
|
||||||
|
- `completed` 不允许回写到任何其他状态;`planned` 不是回写目标;`stalled` 是平台派生状态,不可写。
|
||||||
|
- 目标是归一后的上游状态;`cancelled`、`deleting` 没有台账对应,不提供回写(`suggested_action=none`)。
|
||||||
|
- 幂等:台账已等于目标时返回 200,不写新审计。
|
||||||
|
- 台账在本批次后已被别的动作改过时返回 409 `reconciliation_writeback_stale`。
|
||||||
|
- 回写只改 `processing_state`,不动 `retrieval_state`,不触发发布。
|
||||||
|
|
||||||
|
**progress 对象**:`knowledge_id`、`parse_status`、`ingestion_status`、`wiki_status`、`stages[]`(name、status、error_code、finished_at)、`failures[]`(task_type、fail_count、failed_at、last_error,后者截断到 500 字符)、`has_more_failures`、`observed_at`。
|
||||||
|
|
||||||
|
处置动作的落点:`writeback_state`(R5)、`requeue_upload`(R1/R4)、`remove_from_test`(R2)、`enter_removal`(R6)各一个入口。**只有 R6 能复用现有接口**(`removal-retry`);R1/R4 不能走 `retryPublicationsBatch`(只接受 `failed`/`stalled`,`job_failures.go:448`),R2 不能走测试库移除(拒绝 `superseded`,`test_publication_removal.go:68`),所以这两个是新接口,不是同义接口。
|
||||||
|
|
||||||
|
## 8. 页面改造(T6b,前端)
|
||||||
|
|
||||||
|
| 现有部分 | 去向 |
|
||||||
|
| --- | --- |
|
||||||
|
| 左侧导航「解析监控」 | 改名为「导入对账」,路由保留旧地址并重定向 |
|
||||||
|
| 服务与依赖卡片区 | 收成页面顶部一行状态条;「队列」读 `weknora_queues`;删除 Embedding/LLM 两张常量"未知"卡 |
|
||||||
|
| 按测试库的状态计数 | 改为「最近一次对账」概览:批次时间、状态、R1–R8 计数及与上一批的变化,附「立即对账」按钮(按角色显示) |
|
||||||
|
| 文件处理大表 | 拆成两个页签:①**差异清单**(按类型、关键词筛选,每行显示证据等级、处置建议和按钮;`window_overlapped` 批次的 R1/R2 显示「待确认」徽标);②**平台侧流水**(沿用 `/monitor/tasks`,阶段筛选里的“解析”“索引增强”合并为“WeKnora 处理中”) |
|
||||||
|
| 文件详情抽屉 | 平台侧信息保持不变;新增「WeKnora 处理详情」区块,实时调用 progress 接口,展示阶段时间线和历史失败;503 时显示"未配置只读 Key"和跳转链接 |
|
||||||
|
|
||||||
|
⚠️ 两个页签口径不同:差异清单只看 `superseded_at IS NULL` 的行;平台侧流水沿用 `/monitor/tasks`,**不过滤被顶替行**(`internal/monitoring/real.go:197-214`)。这是有意的,页面要写一句说明,避免同一文件在两个页签结论不同被当成 bug。
|
||||||
|
|
||||||
|
差异清单页脚注明保留范围:明细只保留最近 30 批且不超过 90 天,更早批次只保留计数。
|
||||||
|
|
||||||
|
视觉沿用现有规范:dobot.cn 钴蓝 #0039C8 + 中性灰,不用紫色;导航保持 16px / 44px。
|
||||||
|
|
||||||
|
## 9. 验收标准
|
||||||
|
|
||||||
|
**后端(T6a)**
|
||||||
|
1. 用夹具(或在测试库人工构造)覆盖 R1–R8 每类至少一个样本,对账逐条命中,且没有多报。
|
||||||
|
2. 用固定夹具和固定 `started_at` 重放同一批次两次,差异集合逐条一致;跨批次的时间类差异(R5/R7)按各自 `started_at` 解释,不要求两次相同。
|
||||||
|
3. 对账过程中向 WeKnora 发出的写请求数为 0(以测试中的 HTTP 桩记录为证)。
|
||||||
|
4. 扫描中途注入错误后,批次为 `failed`,没有写入任何 finding。
|
||||||
|
5. 合法的"同字节多台账收养"不被报为 R8。
|
||||||
|
6. `cancelled`、`deleting` 有显式映射,并有测试覆盖。
|
||||||
|
7. 接口响应和日志中不出现 Key、Authorization 等密钥(有测试断言)。
|
||||||
|
8. 并发触发同一库,第二个请求返回 409。
|
||||||
|
9. OpenAPI 契约测试通过,`make verify` 全绿。
|
||||||
|
10. `window_overlapped` 批次:R1/R2 的 `confirmation_state='pending'`,其他类型不受影响;接口和页面都能看到。
|
||||||
|
11. 保留策略:第 31 批或超过 90 天的 findings 被按 run 整体删除,runs 与 previous_counts 保留;清理重复执行无副作用。
|
||||||
|
12. 状态矩阵用表驱动测试覆盖 7×7,`cancelled`/`deleting` 有显式归一值,没有“其他”分支。
|
||||||
|
13. R5 回写:`completed` 不可降级;禁止的迁移返回 409 且台账不变;重复回写幂等且不重复写审计。
|
||||||
|
14. 已移除的行(`retrieval_state in ('disabling','disabled')`)不报 R1。
|
||||||
|
15. R6 与 `/monitor/overview` 的「需下架」计数由同一实现产出,测试断言两处数字一致。
|
||||||
|
16. 扫描请求的 `page_size=1000`(HTTP 桩断言),不再出现 100。
|
||||||
|
17. 扫描期间在途请求数恒为 1(桩记录并发峰值),确认阶段不超过 `reconciliation_confirm_concurrency`。
|
||||||
|
18. R1 重排:清空 `knowledge_id`、置 `pending`、入队上传,旧 knowledge 不存在时也能成功;R4 先删旧 knowledge,删除失败时动作返回错误且台账不变。
|
||||||
|
19. R2 删除:按 `knowledge_id` 删除,404 视为成功,重复点击幂等。
|
||||||
|
20. 僵死批次:`running` 超过阈值自动置 `failed`,之后可以再触发。
|
||||||
|
|
||||||
|
**前端(T6b)**
|
||||||
|
1. 每个页签和抽屉都有加载、空、错误、无权限四种状态,并有组件测试覆盖。
|
||||||
|
2. 只读角色看不到「立即对账」和处置按钮。
|
||||||
|
3. progress 返回 503 时降级展示,页面不报错。
|
||||||
|
4. 在 1440 / 1024 / 768 宽度下没有页面级横向溢出。
|
||||||
|
5. `npm run build` 和前端测试通过,`make verify` 全绿。
|
||||||
|
|
||||||
|
## 10. 决策记录
|
||||||
|
|
||||||
|
| # | 问题 | 默认建议 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Q1 | 是否为平台在**测试** WeKnora 开一个 `system_runtime_read` 平台级只读 Key | **已裁定:开**(只开在测试环境) |
|
||||||
|
| Q2 | 历史上传里没有 metadata 的条数 | T6a 开发时先统计,结果写进工单评论 |
|
||||||
|
| Q3 | 对账频率、R5 宽限期、R7 阈值 | 未裁定,按默认值执行:每天 02:00;30 分钟;2 小时(可配置) |
|
||||||
|
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||||
|
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||||
|
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||||
|
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||||
|
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加“距上次发布 N 天” |
|
||||||
|
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||||
|
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受并发增删造成的个别漏项在下一批补上,不引入游标 |
|
||||||
|
| Q11 | 僵死 `running` 批次 | **已裁定**:超过 6 小时(可配)自动置 `failed` |
|
||||||
@@ -70,13 +70,11 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
|
|||||||
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
|
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
|
||||||
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
|
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
|
||||||
|
|
||||||
**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET
|
**页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。
|
||||||
`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
|
|
||||||
`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以
|
**保存留审计。** 每次保存成功,`weknora_environment_binding_history` 在同一事务写入
|
||||||
录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台
|
操作人、时间、环境、客户端地址(`source_address`)与控制台来源(`source_origin`)。来源字段
|
||||||
自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传
|
只用于事后取证,不参与放行;地址解析不出来就留空,不用推测值填充。
|
||||||
`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。
|
|
||||||
先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
|
|
||||||
|
|
||||||
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
||||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||||
|
|||||||
@@ -96,6 +96,25 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
|||||||
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
||||||
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
|
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
|
||||||
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
|
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
|
||||||
|
- **配额(按字节,硬上限)**:`/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES`
|
||||||
|
约束**备份根累计占用**(默认 `53687091200` = 50 GiB,`backup_layout.sh` 写入,重跑不覆盖已有值)。
|
||||||
|
采集器把同一份配额与根占用写进快照,页面/告警只读该值,不再看归档库。
|
||||||
|
- dump 前预检:预留最近一份完整批次大小,从最旧开始计划删批次,**永不删最新一份**;
|
||||||
|
空间仍不够 → **一个都不删**、非 0 退出,本次备份取消。
|
||||||
|
- dump 后复查:保护本次新批次,允许删旧(含上一份);仍超限则保留新备份并告警退出。
|
||||||
|
- 只删 `rds-logical/<UTC>` 完整批次(含常规 `MANIFEST.json`、非符号链接);
|
||||||
|
`es-snapshots`/`target-kb-snapshots`/`logs` 与 `*.incomplete` 永不删。
|
||||||
|
- **删除分三段(预检 → 改名隔离 → 真删)**:`rmtree` 会先删内容、最后删目录,父目录只读时
|
||||||
|
失败发生在内容已清空之后,调用方只看得到非 0 退出。所以先逐目录检查可写性并对每个计划内
|
||||||
|
批次做同父目录改名探针(只验证父目录可写,不动内容),再全部改名成 `.prune-<pid>-<戳>`
|
||||||
|
(原子、不进批次候选),最后才真删。任一预检失败或改名失败 ⇒ **零删除**;真删阶段才失败时
|
||||||
|
报隔离路径(`mv` 回原名即可恢复剩余内容)。
|
||||||
|
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)与配额清理走同一份实现(`--rotate`),不再有第二份内联
|
||||||
|
`rmtree`。
|
||||||
|
- 退出码:`0` 已满足(可能删过)、`2` du/路径错误、`3` 空间仍不够、`4` 真删阶段失败、
|
||||||
|
`5` 预检未通过(零删除)。
|
||||||
|
- 现场对账:`du -sB1 -- $KB_BACKUP_ROOT` 与页面「备份占用」应一致(≤1%);
|
||||||
|
`bash scripts/install_backup_schedule.sh --show` 也会打印根占用/配额。
|
||||||
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
||||||
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
||||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
||||||
|
|||||||
@@ -19,11 +19,15 @@
|
|||||||
```sh
|
```sh
|
||||||
python3 collect_backup_metadata.py \
|
python3 collect_backup_metadata.py \
|
||||||
--root /srv/kb-backups/rds-logical \
|
--root /srv/kb-backups/rds-logical \
|
||||||
|
--usage-root /srv/kb-backups \
|
||||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||||
--source weknora-test:/srv/kb-backups/rds-logical
|
--source weknora-test:/srv/kb-backups/rds-logical
|
||||||
```
|
```
|
||||||
|
|
||||||
- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
|
- 备份根与配额来自 `/etc/knowledge-governance/backup.env`(`backup_layout.sh` 生成):
|
||||||
|
`KB_BACKUP_ROOT`(默认 `/srv/kb-backups`)与 `KB_BACKUP_QUOTA_BYTES`(默认 `53687091200` = 50 GiB)。
|
||||||
|
`--usage-root` / `--quota-bytes` 可显式覆盖;`--config` 换配置文件路径。
|
||||||
|
- 退出码:`0` 完整且配额可用;`2` 已写快照但批次/根占用不完整或配额非法;`1` 连快照都没写成。
|
||||||
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
|
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
|
||||||
**不打开任何 `.dat/.gz` 数据文件**。
|
**不打开任何 `.dat/.gz` 数据文件**。
|
||||||
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
||||||
@@ -47,6 +51,8 @@ python3 collect_backup_metadata.py \
|
|||||||
```
|
```
|
||||||
|
|
||||||
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
||||||
|
采集器自己读 `/etc/knowledge-governance/backup.env` 拿 `KB_BACKUP_ROOT`/`KB_BACKUP_QUOTA_BYTES`,
|
||||||
|
所以配额调整不需要改 cron;只想临时覆盖时再加 `--usage-root`/`--quota-bytes`。
|
||||||
|
|
||||||
### 快照 schema(version 1)
|
### 快照 schema(version 1)
|
||||||
|
|
||||||
@@ -58,6 +64,10 @@ python3 collect_backup_metadata.py \
|
|||||||
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
||||||
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
||||||
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
|
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
|
||||||
|
| `backup_root` | 宿主上的备份根(`KB_BACKUP_ROOT`);API 要求等于 `BACKUP_HOST_ROOT` |
|
||||||
|
| `usage` | 备份根整棵树的累计占用:`root/complete/actual_bytes/apparent_bytes/file_count/dir_count/errors`;`complete=false` 时字节必须为 `null` |
|
||||||
|
| `quota_bytes` | 备份根累计占用硬上限(字节);非法/缺失时为 `null`,原因写 `quota_error` |
|
||||||
|
| `quota_error` | 配额不可用的原因(例如 `KB_BACKUP_QUOTA_BYTES` 不是正整数) |
|
||||||
| `complete` | 全局完整;权限失败/截断/有错误时为 false |
|
| `complete` | 全局完整;权限失败/截断/有错误时为 false |
|
||||||
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
||||||
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
||||||
@@ -87,8 +97,16 @@ python3 collect_backup_metadata.py \
|
|||||||
},
|
},
|
||||||
"root": "/srv/kb-backups/rds-logical",
|
"root": "/srv/kb-backups/rds-logical",
|
||||||
"host_root": "/srv/kb-backups/rds-logical",
|
"host_root": "/srv/kb-backups/rds-logical",
|
||||||
|
"backup_root": "/srv/kb-backups",
|
||||||
"source": "weknora-test:/srv/kb-backups/rds-logical",
|
"source": "weknora-test:/srv/kb-backups/rds-logical",
|
||||||
"measurement": "host_collector",
|
"measurement": "host_collector",
|
||||||
|
"usage": {
|
||||||
|
"root": "/srv/kb-backups", "complete": true,
|
||||||
|
"actual_bytes": 24318382080, "apparent_bytes": 23000000000,
|
||||||
|
"file_count": 900, "dir_count": 30, "errors": []
|
||||||
|
},
|
||||||
|
"quota_bytes": 53687091200,
|
||||||
|
"quota_error": "",
|
||||||
"mount": {
|
"mount": {
|
||||||
"mount_verified": true, "read_only": false,
|
"mount_verified": true, "read_only": false,
|
||||||
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
||||||
@@ -135,8 +153,11 @@ python3 collect_backup_metadata.py \
|
|||||||
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
||||||
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
||||||
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
|
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
|
||||||
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
|
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有批次 `*_bytes=null` | 列出路径与清单状态;批次/容量“未知”,不画色带;根占用若自身完整仍可显示 |
|
||||||
| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
|
| 根占用遍历失败 | `metadata.valid=true`;`usage.actual_bytes=null`、`usage.error` 给原因 | 「备份占用 —」并显示原因;批次表与磁盘剩余不受影响 |
|
||||||
|
| 旧采集器无 `usage/quota` | 字段缺省,API 返回显式「未上报」原因 | 「备份占用 —」「配额未上报」,绝不用批次和冒充 |
|
||||||
|
| `usage.root` 与 `BACKUP_HOST_ROOT` 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑占用 |
|
||||||
|
| 完整且新鲜 | 批次/子库字节、根占用与配额按快照 | 色带、批次、`备份占用 X / 配额 50 GB` |
|
||||||
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
||||||
|
|
||||||
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
||||||
@@ -187,7 +208,13 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
|||||||
|
|
||||||
字段核对(以现场为准,示例值不写死):
|
字段核对(以现场为准,示例值不写死):
|
||||||
|
|
||||||
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
|
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看批次字节与容量。
|
||||||
|
- `usage.complete=true` 时,`usage.actual_bytes` 必须与宿主 `du -sB1 -- /srv/kb-backups` 一致
|
||||||
|
(误差 ≤1%);`quota_bytes` 与 `/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES` 相同。
|
||||||
|
- `usage.actual_bytes` **不是** `totals.actual_bytes`:后者只累加 `rds-logical` 批次,
|
||||||
|
前者还包含 `es-snapshots`/`target-kb-snapshots`/`logs`。
|
||||||
|
- 根占用遍历失败:`usage.complete=false`、`usage.actual_bytes=null`,同时批次仍应可用;
|
||||||
|
**不要**用批次和代替根占用。
|
||||||
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
|
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
|
||||||
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
||||||
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
|
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
|
||||||
@@ -218,7 +245,7 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
|||||||
|
|
||||||
## 6. 还需单独确认的后端写能力
|
## 6. 还需单独确认的后端写能力
|
||||||
|
|
||||||
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
|
1. 配额 / 磁盘预留的持久化:配额已按部署配置(`backup.env`)执行并上报;**平台页面编辑/下发**仍未实现(需 DB 字段与写接口)。
|
||||||
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
||||||
3. 备份目录迁移/切换。
|
3. 备份目录迁移/切换。
|
||||||
4. 单库备份/单库恢复(现有 run 是整批)。
|
4. 单库备份/单库恢复(现有 run 是整批)。
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
# 本期计划:WeKnora 升级 v0.9.1 + 导入对账
|
||||||
|
|
||||||
|
> 状态:v0.4(2026-11-30),用户已裁定 D0 / D1 / Q1 / Q5 / Q6 / Q7 / Q9 / Q10 / Q11,可以开工。不建 Gitea 工单,本文即任务书。
|
||||||
|
> 基线:`origin/main` `ca87056`;上游 WeKnora v0.9.1 源码 `~/weknora-explore/WeKnora-v0.9.1`。
|
||||||
|
> 导入对账的需求正文见 [IMPORT_RECONCILIATION_REQUIREMENTS.md](IMPORT_RECONCILIATION_REQUIREMENTS.md)。
|
||||||
|
|
||||||
|
## 0. 目标
|
||||||
|
|
||||||
|
1. 测试、生产 WeKnora 从 v0.9.0 升级到 v0.9.1,升级后整库发布照常可用。
|
||||||
|
2. 「解析监控」重构为「导入对账」一期(台账 ↔ 测试库)。
|
||||||
|
|
||||||
|
发布架构保持不变(2026-11-30 与用户确认):**测试环境负责解析、人工加工和新功能验证;生产环境只做推理,不跑 MinerU、不做解析;内容只通过平台整库发布(直接读写 WeKnora 的 PG/ES)从测试搬运到生产。**
|
||||||
|
|
||||||
|
## 1. 分工
|
||||||
|
|
||||||
|
| 角色 | 负责 | 不做 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| **用户** | 批准需求与工单;执行现场运维(升级、备份);授权生产发布;回答各工单里的决策项 | — |
|
||||||
|
| **DeepSeek(开发)** | T1、T6a、T6b 的开发、测试、迁移和项目文档;T3 演练的脚本和命令准备 | 不改验收标准;不部署;不执行生产写操作 |
|
||||||
|
| **验收工作流** | 按本文验收矩阵逐项判定 PASS / FAIL,结论绑定提交 SHA(由用户指派) | 不修代码 |
|
||||||
|
|
||||||
|
交接证据和验收结论的格式沿用 [three-agent-handoff-workflow.md](architecture/three-agent-handoff-workflow.md) §6 的模板(只借格式,不再有三个角色)。
|
||||||
|
|
||||||
|
**交付流程(D0,已裁定:走 PR)**:按 `AGENTS.md` 执行。每个工单从最新 `origin/main` 拉一个短分支,通过 PR 合入;CI `build` 通过,且验收工作流 PASS 后才合并;合并后读回 `merged=true` 和 `merge_commit_sha`。`three-agent-handoff-workflow.md` §2 中"main 直推、不走 PR"的口径作废,由 DeepSeek 在 T1 的 PR 里顺手把该节改成与 AGENTS.md 一致。
|
||||||
|
|
||||||
|
**不建 Gitea 工单**:本文就是任务书。交接证据(起止 SHA、测试命令与真实输出)和验收结论写在对应 PR 的描述和评论里,格式沿用上面提到的 §6 模板。
|
||||||
|
|
||||||
|
**串行规则**:T1、T6a、T6b 全部由 DeepSeek 开发,串行进行(T1 → T6a 契约 → T6a 实现 → T6b)。T6b 只改 `web/`,与 T6a 交错时不动后端文件,避免冲突。
|
||||||
|
|
||||||
|
## 2. 工单总览与依赖
|
||||||
|
|
||||||
|
```
|
||||||
|
T1 libraryprofile v0.9.1 + 漏表门禁 ──合并并部署──► T2 升级测试 WeKnora ──► T3 测试整库导出演练
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
T4 升级生产 WeKnora ◄── T3 通过
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
T5 整库发布 + 读回
|
||||||
|
|
||||||
|
T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端(按契约并行,联调需 T2 完成)
|
||||||
|
```
|
||||||
|
|
||||||
|
| 工单 | 内容 | 执行 | 验收 | 前置 |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| T1 | libraryprofile 补 v0.9.1 + 漏表门禁 | DeepSeek | 验收工作流 | 无 |
|
||||||
|
| T2 | 升级测试 WeKnora | 用户(按 §4 清单) | 用户 + 验收工作流 | T1 已合并并部署到平台 |
|
||||||
|
| T3 | 测试整库导出演练 | DeepSeek 准备命令,用户授权执行 | 验收工作流 | T2 |
|
||||||
|
| T4 | 升级生产 WeKnora | 用户(按 §4 清单) | 用户 + 验收工作流 | T3 PASS |
|
||||||
|
| T5 | 整库发布到生产 + 读回 | 用户在平台授权发布 | 验收工作流(读回证据) | T4 |
|
||||||
|
| T6a | 导入对账后端 | DeepSeek | 验收工作流 | 无(联调需 T2) |
|
||||||
|
| T6b | 导入对账前端 | DeepSeek | 验收工作流 | T6a 契约提交 |
|
||||||
|
|
||||||
|
**需求单落库口径(6 张)**:T1、T2、T3、T4、T5、T6。T6 把上面的 T6a 与 T6b 合成一张,契约仍是第一个提交;下面保留 T6a/T6b 只是写清先后顺序。
|
||||||
|
|
||||||
|
## 3. T1:libraryprofile 补 v0.9.1 + 漏表门禁
|
||||||
|
|
||||||
|
### 3.1 背景(已核实)
|
||||||
|
|
||||||
|
- 整库导出和导入按目标库 `schema_migrations` 的版本,从 `internal/libraryprofile/profile.go` 选中一份声明;目前只有 74(v0.7.1)和 134(v0.9.0)。v0.9.1 的版本是 137,`libraryprofile.For(137)` 会失败,**升级后整库发布会被拒绝**。
|
||||||
|
- 上游 135–137 号迁移(已逐个读过):135 加宽 `audit_logs.actor_user_id`;136 新建 `credential_vault_items`(只有 tenant_id/user_id,与知识库无关);137 重建 `im_channel_sessions` 的唯一索引。**三个都不涉及知识相关的表、列或触发器**。`chunk_images_sync` 触发器只在 000113 中定义,之后没有被修改。
|
||||||
|
- **已有缺口(与升级无关,0.9.0 起就存在)**:现有的 schema 探测只检查"声明过的表是否存在"(`releaseadapter/v071/schema_profile.go:111`),不会发现"有本库数据、但没有声明"的表。按上游迁移文件统计,0.9.x 中带 `knowledge_base_id` 或 `knowledge_id` 列、却不在 v090 声明里的表有:
|
||||||
|
|
||||||
|
| 表 | 内容 | 建议归类 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `chunk_images` | 由 chunks 上的触发器维护的派生表 | 派生(已在 v090 的触发器声明中覆盖) |
|
||||||
|
| `chunk_revisions` | 切片编辑历史(000078) | **搬运(D1 已裁定)** |
|
||||||
|
| `wiki_page_revisions` | Wiki 页面编辑历史(000075) | **搬运(D1 已裁定)** |
|
||||||
|
| `knowledge_processing_spans` | 解析流水线的阶段遥测(000055) | 排除:处理过程数据,生产不解析 |
|
||||||
|
| `sessions`、`messages` | 对话数据 | 排除:生产自己的运行数据,不能被覆盖 |
|
||||||
|
| `memory_doc_affinity` | 记忆与文档的关联 | 排除:运行数据 |
|
||||||
|
| `user_kb_pins`、`kb_shares`、`im_channels`、`data_sources` | 用户置顶、共享、IM 渠道、数据源配置 | 排除:各环境自己的配置 |
|
||||||
|
|
||||||
|
### 3.2 需求
|
||||||
|
|
||||||
|
1. **新增 v0.9.1 声明**:版本 137,`WeKnoraVersion: "v0.9.1"`。表、列、部件、触发器与 v090 相同,**必须复用 v090 的声明来构造,不能复制一份**(硬约束 1)。`Supported()` 加入 137,`For` 的错误信息同步更新。
|
||||||
|
2. **每张关联表都要归类**:在 profile 中为每个版本维护「关联表分类」:`copied`(搬运,即现有的 Required/Optional)、`derived`(由触发器或应用派生)、`excluded`(不搬,必须写明原因)。分类只写在 profile 这一处。
|
||||||
|
3. **漏表门禁**:在测试端导出前、生产端导入前各执行一次。从 information_schema 找出 public 下所有带 `knowledge_base_id`、`knowledge_id` 或 `kb_id` 列的表:
|
||||||
|
- 已分类的表:放行。
|
||||||
|
- 未分类的表:若含有**本次发布范围内**的数据,拒绝并返回 `release_undeclared_kb_table`,错误信息列出表名和行数,不可重试;若没有数据,放行,但在发布记录里写一条警告。
|
||||||
|
4. **搬运编辑历史(D1 已裁定:搬)**:`chunk_revisions`、`wiki_page_revisions` 加入 v0.9.0 和 v0.9.1 两份声明的 copied 表与归档部件(v0.7.1 中没有这两张表,不动)。它们必须和现有表走**同一套**范围改写与 ID 映射,不能另写一条路径:
|
||||||
|
|
||||||
|
| 表 | 身份 | 范围改写 | 引用映射 | 不改写 |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `chunk_revisions` | id | tenant_id、knowledge_base_id | knowledge_id、chunk_id | revision、content、editor_id、edit_source、时间列 |
|
||||||
|
| `wiki_page_revisions` | id | tenant_id、knowledge_base_id | page_id | slug、version、正文类字段、aliases、editor_id、时间列 |
|
||||||
|
|
||||||
|
- **写入顺序**:在父表(chunks、wiki_pages)之后写入;删除和回滚时先删这两张表。两张表在上游都没有外键,但存在逻辑引用。
|
||||||
|
- **悬挂引用**:沿用现有规则,指向未登记身份的引用一律拒绝,不静默跳过。上游删除切片或页面时会同步硬删除对应的历史记录(`repository/chunk.go:726`、`repository/wiki_page.go:261-285`),所以正常情况下不应出现悬挂引用;T3 演练要实测确认。
|
||||||
|
- **editor_id 原样保留**:测试环境的用户 ID 在生产上可能查不到,生产页面上会显示为未知编辑者。这是已知且可以接受的代价,要在 `docs/library-target-id-mapping.md` 中写明。
|
||||||
|
- **ES**:两张表不进检索索引。DeepSeek 需要读上游代码确认这一点,并把结论写进 PR 描述。
|
||||||
|
- **唯一索引**:`chunk_revisions(chunk_id, revision)` 是唯一索引,chunk_id 映射后仍然唯一,需要有测试覆盖。
|
||||||
|
- **同步更新文档**:`docs/library-target-id-mapping.md` 的映射表、`docs/library-data-contract.md`(如果其中列了表清单)。
|
||||||
|
|
||||||
|
### 3.3 验收(验收工作流)
|
||||||
|
|
||||||
|
1. `libraryprofile.For(137)` 返回 v0.9.1 声明;v090 与 v091 的声明除版本号外完全一致(用测试断言,而不是两份复制的常量)。
|
||||||
|
2. 门禁测试:未分类表有数据 → 拒绝,错误码和表名都正确;未分类表为空 → 放行并有警告;`derived`/`excluded` 表 → 放行。
|
||||||
|
3. 现有的 74 / 134 测试全部保持通过。
|
||||||
|
4. `make verify` 全绿;提交符合 AGENTS.md 规范。
|
||||||
|
5. 编辑历史两张表:有测试覆盖范围改写、ID 映射、写入/删除顺序、悬挂引用拒绝、唯一索引;导出 → 写入 → 校验 → 回滚的整轮测试中,两张表的行数和内容摘要都一致。
|
||||||
|
6. PR 描述附上:对上游 135–137 号迁移的审查结论;如果开发会话能访问测试 WeKnora,附上对真实 0.9.0 库 information_schema 的只读查询结果。
|
||||||
|
|
||||||
|
## 4. T2 / T4:升级 WeKnora(用户执行的清单)
|
||||||
|
|
||||||
|
依据上游 `website-docs/07-releases/v0.9.1.md#upgrade-notes`。测试和生产各执行一遍,**生产必须等 T3 PASS 之后再做**。
|
||||||
|
|
||||||
|
**升级前**
|
||||||
|
- [ ] 平台已部署包含 T1 的版本(在平台入口查看版本号)
|
||||||
|
- [ ] 备份 PostgreSQL、文件存储、部署配置(`.env`、compose 覆盖文件)
|
||||||
|
- [ ] 生产额外执行:`bash scripts/target_kb_snapshot.sh` 留档,并用 `go run ./cmd/guardcheck <快照根> <kb_id>` 核验
|
||||||
|
- [ ] 记录升级前状态:`SELECT version, dirty FROM schema_migrations;`,应为 `134, false`
|
||||||
|
- [ ] 生产额外确认:MinerU 和解析 worker 处于关闭状态(生产只做推理)
|
||||||
|
|
||||||
|
**升级**
|
||||||
|
- [ ] `.env` 中设置 `WEKNORA_VERSION=v0.9.1`;检查是否有单独覆盖过的组件镜像标签
|
||||||
|
- [ ] `docker compose pull && docker compose up -d`
|
||||||
|
|
||||||
|
**升级后**
|
||||||
|
- [ ] `schema_migrations` 应为 `137, false`
|
||||||
|
- [ ] 抽查原有知识库的检索、问答是否正常
|
||||||
|
- [ ] 测试环境额外检查:平台走一轮「取件 → 上传 → 解析 → 完成」
|
||||||
|
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 创建平台级 API Key,只授予 `system_runtime_read` 能力,以 secret 文件形式交给平台(不写进 Git 或 compose),然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。生产不需要这个 Key
|
||||||
|
- [ ] 生产额外检查:平台发布通道只读预检(`release-diag`)通过
|
||||||
|
|
||||||
|
**回退**:不能直接换回旧镜像。向下迁移会删除凭据表、截短审计字段。正确做法是停止写入后,用升级前的备份恢复数据库、存储和配置,再切回 v0.9.0 镜像。
|
||||||
|
|
||||||
|
## 5. T3:测试整库导出演练
|
||||||
|
|
||||||
|
- **目的**:在升级到 0.9.1 的测试库上,证明新声明和门禁在真实库上可用;同时作为 T4 的放行条件。
|
||||||
|
- **DeepSeek**:根据 `docs/library-capture.md`、`docs/library-sync-acceptance.md`、`docs/library-migration-contract.md` 和 `libraryctl` 的现有子命令,整理出逐条执行的命令清单(只读或只写测试侧),写进工单,由用户授权后执行。
|
||||||
|
- **验收(验收工作流)**:快照清单里的 schema 版本是 137;`chunk_revisions`、`wiki_page_revisions` 两个部件存在,行数与源库一致,没有悬挂引用;所有部件齐全,哈希可以复算(`libraryctl snapshot-verify`);漏表门禁实际执行过,并对真实库输出了分类结果;与上一次 0.9.0 快照相比,表计数没有异常变化。
|
||||||
|
|
||||||
|
## 6. T5:整库发布到生产 + 读回
|
||||||
|
|
||||||
|
- 按 `docs/RELEASE_RUNBOOK.md` 和 OPERATIONS_RUNBOOK §5–6 执行:发布前留档门禁 → 授权发布 → 读回。
|
||||||
|
- **验收(验收工作流)**:发布记录为成功;读回一致;用 `librarydiff` 对比测试快照与生产,差异为 0(`excluded` 表除外,并列明);生产抽样 10 个问题检索正常;漏表门禁在生产端也执行过。
|
||||||
|
|
||||||
|
## 7. T6a / T6b:导入对账
|
||||||
|
|
||||||
|
需求、接口契约和验收标准都在 [IMPORT_RECONCILIATION_REQUIREMENTS.md](IMPORT_RECONCILIATION_REQUIREMENTS.md):
|
||||||
|
|
||||||
|
- T6a 的第一个提交只包含 §7 的 OpenAPI 契约,先由验收工作流审契约并冻结,再继续实现。
|
||||||
|
- 本期 T6a 范围内加入"上传时记录上传字节的 MD5":需要一个台账迁移(`upload_md5`),以及上传流程的改动。
|
||||||
|
- 新建 `reconciliation_runs` / `reconciliation_findings` 两张表:`runs` 永久保留;`findings` 按 `run_id` 整批清理,保留最近 30 批且不超过 90 天(Q5)。同一测试库的 `running` 批次用部分唯一索引约束(`WHERE state='running'`)。
|
||||||
|
- 对账扫描使用 `page_size=1000`:要把 `internal/platform/weknora/client.go` 的 `validPage` 上限从 100 放开(或给对账单独一条扫描路径),不能沿用上传恢复的 100。扫描全程串行(在途 1 个请求),R1/R2 确认可用 `reconciliation_confirm_concurrency`(默认 1、上限 8),不复用 `ingestion_concurrency`。
|
||||||
|
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `window_overlapped=true`,该批 R1/R2 的 `confirmation_state='pending'`(Q6)。
|
||||||
|
- 平台级只读 Key 走 `WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,启动读取一次,不做热加载);未配置或文件不可读时 `runtime/*` 返回 503 `runtime_read_unavailable`,对账不受影响(Q7)。
|
||||||
|
- 状态映射只写在服务端一处,接口返回 `normalized_state`;R5 回写按迁移矩阵校验,`completed` 不可降级。
|
||||||
|
- 处置动作:新增 finding 级 `requeue`(R1/R4)与 `remove`(R2);R6 复用现有 `removal-retry`。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
|
||||||
|
- 扫描保留 offset 翻页,不引入游标;并发增删造成的个别漏项在下一批补上(Q10)。
|
||||||
|
- 僵死 `running` 超过 6 小时(可配)自动置 `failed`,释放并发位(Q11)。
|
||||||
|
- 一期只对测试库。生产的下架依赖"测试移除 + 下一轮整库发布",这段空窗期不在对账范围内,必须写进页面范围说明(Q8 未裁定是否再加"距上次发布 N 天"提示)。
|
||||||
|
- T6b 先用契约桩数据开发,T2 完成后再和真实后端联调。
|
||||||
|
|
||||||
|
## 8. 决策记录
|
||||||
|
|
||||||
|
| # | 问题 | 结论(2026-11-30 用户裁定) |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| D0 | 交付流程 | 按 AGENTS.md 走分支 + PR |
|
||||||
|
| D1 | 编辑历史(`chunk_revisions`、`wiki_page_revisions`)是否搬到生产 | 搬 |
|
||||||
|
| Q1 | 是否在测试 WeKnora 为平台开 `system_runtime_read` 只读 Key | 开 |
|
||||||
|
| Q3 | 对账频率、R5 宽限期、R7 阈值 | 未裁定,按默认值执行:每天 02:00;30 分钟;2 小时(做成可配置项) |
|
||||||
|
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||||
|
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||||
|
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||||
|
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||||
|
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加"距上次发布 N 天" |
|
||||||
|
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||||
|
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受个别漏项下一批补上,不引入游标 |
|
||||||
|
| Q11 | 僵死 `running` 批次 | **已裁定**:超过 6 小时(可配)自动置 `failed` |
|
||||||
|
|
||||||
|
## 9. 执行顺序速览
|
||||||
|
|
||||||
|
1. DeepSeek 做 T1,提 PR → 验收工作流 → 合并 → 部署到平台(按现有发布流程)。
|
||||||
|
2. DeepSeek 在 T1 合并后开始 T6a,第一个提交是 OpenAPI 契约;契约经验收工作流冻结后,继续 T6a 实现和 T6b。
|
||||||
|
3. 你执行 T2(升级测试)并创建只读 Key → DeepSeek 准备 T3 命令,你授权执行 → 验收工作流。
|
||||||
|
4. T3 通过后,你执行 T4(升级生产)→ 在平台授权 T5 发布 → 验收工作流读回证据。
|
||||||
|
5. T6 和测试环境联调 → 验收工作流 → 合并 → 部署。
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
| 合同条目 | 本文位置 |
|
| 合同条目 | 本文位置 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 1 三角色职责 | §1 |
|
| 1 三角色职责 | §1 |
|
||||||
| 2 main 单线、串行修改 | §2 |
|
| 2 分支 + PR、串行修改 | §2 |
|
||||||
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
|
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
|
||||||
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
|
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
|
||||||
| 5 不可变与回退规则 | §5 |
|
| 5 不可变与回退规则 | §5 |
|
||||||
@@ -30,11 +30,12 @@
|
|||||||
角色约束是**流程约束**,不是技术 ACL 隔离:本机共用 Gitea 管理员凭据,谁也拦不住谁越权,
|
角色约束是**流程约束**,不是技术 ACL 隔离:本机共用 Gitea 管理员凭据,谁也拦不住谁越权,
|
||||||
所以每个角色都要靠"读回核实"而非"相信对方自述"来交付。
|
所以每个角色都要靠"读回核实"而非"相信对方自述"来交付。
|
||||||
|
|
||||||
## 2. main 单线、单仓库串行
|
## 2. 分支 + PR 单线、单仓库串行
|
||||||
|
|
||||||
- 只使用 `main` 一条线:**不创建分支、不建 worktree、不走 PR、不做合并**(通用引擎规范里 PR 是可选姿态,
|
- 只使用受保护的 `main` 作为集成目标:**不直推 main**;每个工单从最新 `origin/main` 拉一个短命分支,
|
||||||
本仓沿用"以直推为主"的口径)。
|
通过 PR 合入,合并前 CI `build`(`make verify`)必须通过。口径以 `AGENTS.md` 为准,本节不再保留
|
||||||
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有。
|
“main 直推”的旧做法。
|
||||||
|
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有;PR 完成后短命分支删除。
|
||||||
- **review 期间开发停止修改代码**:工单进入 `status:review` 后,除按 `rework` 要求修复外不再改动。
|
- **review 期间开发停止修改代码**:工单进入 `status:review` 后,除按 `rework` 要求修复外不再改动。
|
||||||
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
|
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
|
||||||
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
|
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
|
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
|
||||||
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
|
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
|
||||||
4. 从持久数据推出兼容契约:迁移版本、dirty、租户、Embedding 模型与维度、检索引擎、索引名、索引映射摘要(`text-embedding-v4` / 1024 维 / schema 74)。
|
4. 从持久数据推出兼容契约:迁移版本、dirty、租户、Embedding 模型与维度、检索引擎、索引名、索引映射摘要(`text-embedding-v4` / 1024 维 / schema 74)。
|
||||||
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),导出 PostgreSQL 十表 + Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
|
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),按来源 schema profile 导出知识域表(0.7.1 十表;0.9.x 另含 `chunk_revisions`、`wiki_page_revisions`)+ Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
|
||||||
6. 无论成败都恢复写入者并等到 healthy;崩溃留下的日志用 `libraryctl recover` 收尾。
|
6. 无论成败都恢复写入者并等到 healthy;崩溃留下的日志用 `libraryctl recover` 收尾。
|
||||||
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
|
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,21 @@
|
|||||||
|
|
||||||
既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。
|
既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。
|
||||||
|
|
||||||
|
## 2.1 0.9.x 追加:编辑历史两表(T1)
|
||||||
|
|
||||||
|
0.7.1 没有这两张表;0.9.0(134)与 0.9.1(137)起整库发布按 `libraryprofile` 声明搬运:
|
||||||
|
|
||||||
|
| 表 | 身份 | 范围/引用 | 保真边界 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `chunk_revisions` | `id`(varchar 36) | 范围改写 `tenant_id`/`knowledge_base_id`;映射 `knowledge_id`、`chunk_id` | `revision`/`content`/`is_enabled`/`editor_id`/`edit_source`/时间列原样;唯一索引 `(chunk_id, revision)` 映射后仍唯一 |
|
||||||
|
| `wiki_page_revisions` | `id`(varchar 36) | 范围改写 `tenant_id`/`knowledge_base_id`;映射 `page_id` | `slug`/`version`/正文类字段/`aliases`/`editor_id`/时间列原样;唯一索引 `(page_id, version)` 映射后仍唯一 |
|
||||||
|
|
||||||
|
- 写入在父表(`chunks` / `wiki_pages`)之后;删除/回滚先删两表。
|
||||||
|
- 只导出**活跃父行**的修订:父行软删属于本次范围外;父行完全不存在属于数据异常,导出即拒绝。
|
||||||
|
- 修订正文里的 `resource://` 按历史事实原样保留,不参与资源发现(人类裁定 Q2=B)。
|
||||||
|
- `editor_id` 不映射:目标可能查不到来源用户,页面显示未知编辑者;这是已接受代价。
|
||||||
|
- 两表不进 Elasticsearch;整库校验比对行数 + 逐行内容摘要(时间戳类字段按既有规则豁免)。
|
||||||
|
|
||||||
## 3. 资源引用的实际格式
|
## 3. 资源引用的实际格式
|
||||||
|
|
||||||
只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。
|
只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 var
|
|||||||
| wiki_folders | id | parent_id |
|
| wiki_folders | id | parent_id |
|
||||||
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
|
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
|
||||||
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
|
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
|
||||||
|
| chunk_revisions | id | knowledge_id, chunk_id |
|
||||||
|
| wiki_page_revisions | id | page_id |
|
||||||
| resource_bindings | id | owner_id(按 owner_type) |
|
| resource_bindings | id | owner_id(按 owner_type) |
|
||||||
| resources | **不映射** | resource_id 保持共享身份 |
|
| resources | **不映射** | resource_id 保持共享身份 |
|
||||||
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
|
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
|
||||||
@@ -40,6 +42,20 @@ target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 var
|
|||||||
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
|
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
|
||||||
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
|
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
|
||||||
|
|
||||||
|
### 0.9.x 编辑历史(v090 / v091)
|
||||||
|
|
||||||
|
- `chunk_revisions`:身份 `id`;范围改写 `tenant_id`、`knowledge_base_id`;引用映射
|
||||||
|
`knowledge_id → knowledges`、`chunk_id → chunks`;`revision`、`content`、`is_enabled`、
|
||||||
|
`editor_id`、`edit_source`、时间列不改写。
|
||||||
|
- `wiki_page_revisions`:身份 `id`;范围改写 `tenant_id`、`knowledge_base_id`;引用映射
|
||||||
|
`page_id → wiki_pages`;`slug`、`version`、正文类字段、`aliases`、`editor_id`、时间列不改写。
|
||||||
|
- 两表在父表(`chunks` / `wiki_pages`)之后写入;删除与回滚先删这两张表。
|
||||||
|
- 唯一索引 `(chunk_id, revision)` / `(page_id, version)` 在映射后仍唯一(有测试)。
|
||||||
|
- `editor_id` 原样保留:测试环境的用户 ID 在生产上可能查不到,生产页面会显示为未知编辑者。
|
||||||
|
这是已知且可接受的代价,写在这里避免被当成缺陷重复排查。
|
||||||
|
- 两表不进检索索引;修订正文里的 `resource://` 文本按历史事实原样保留,不参与资源发现
|
||||||
|
(Q2=B,2026-11-30 人类裁定)。
|
||||||
|
|
||||||
## 一致性边界
|
## 一致性边界
|
||||||
|
|
||||||
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
|
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package backuphost
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 配额清理工具是唯一会删历史备份的代码。它的 self-test 覆盖「最旧优先 / 预检保留最新 /
|
||||||
|
// 空间不够零删除 / 非批次日录与符号链接不动 / dump 后保护新批次」,必须随 Go 测试一起跑。
|
||||||
|
func TestPruneBackupBatchesSelfTest(t *testing.T) {
|
||||||
|
python, err := exec.LookPath("python3")
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("python3 not available")
|
||||||
|
}
|
||||||
|
command := exec.Command(python, "../../scripts/prune_backup_batches.py", "--self-test")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("prune self-test failed: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(output), "self-test ok") {
|
||||||
|
t.Fatalf("prune self-test output unexpected: %s", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,9 @@ type Config struct {
|
|||||||
MetadataPath string
|
MetadataPath string
|
||||||
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
||||||
HostRoot string
|
HostRoot string
|
||||||
|
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
|
||||||
|
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
|
||||||
|
BackupRoot string
|
||||||
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
||||||
Source string
|
Source string
|
||||||
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
||||||
@@ -85,6 +88,19 @@ type Capacity struct {
|
|||||||
Error string `json:"error,omitempty"`
|
Error string `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Usage 是**备份根累计占用**(配额约束的对象),不是 rds-logical 批次之和。
|
||||||
|
// Measured=false 时所有字节为 null:部分遍历永远不能当占盘。
|
||||||
|
type Usage struct {
|
||||||
|
Root string `json:"root"`
|
||||||
|
Measured bool `json:"measured"`
|
||||||
|
Complete bool `json:"complete"`
|
||||||
|
ActualBytes *int64 `json:"actual_bytes"`
|
||||||
|
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||||
|
FileCount *int `json:"file_count"`
|
||||||
|
DirCount *int `json:"dir_count"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type Database struct {
|
type Database struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
DirName string `json:"dir_name"`
|
DirName string `json:"dir_name"`
|
||||||
@@ -138,12 +154,16 @@ type Snapshot struct {
|
|||||||
Metadata MetadataInfo `json:"metadata"`
|
Metadata MetadataInfo `json:"metadata"`
|
||||||
Root string `json:"root"`
|
Root string `json:"root"`
|
||||||
HostRoot string `json:"host_root"`
|
HostRoot string `json:"host_root"`
|
||||||
|
BackupRoot string `json:"backup_root"`
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
ObservedAt string `json:"observed_at"`
|
ObservedAt string `json:"observed_at"`
|
||||||
Error string `json:"error,omitempty"`
|
Error string `json:"error,omitempty"`
|
||||||
Measurement string `json:"measurement"`
|
Measurement string `json:"measurement"`
|
||||||
Mount MountInfo `json:"mount"`
|
Mount MountInfo `json:"mount"`
|
||||||
Capacity Capacity `json:"capacity"`
|
Capacity Capacity `json:"capacity"`
|
||||||
|
Usage Usage `json:"usage"`
|
||||||
|
QuotaBytes *int64 `json:"quota_bytes"`
|
||||||
|
QuotaError string `json:"quota_error,omitempty"`
|
||||||
Batches []Batch `json:"batches"`
|
Batches []Batch `json:"batches"`
|
||||||
Totals Totals `json:"totals"`
|
Totals Totals `json:"totals"`
|
||||||
IncompleteCount int `json:"incomplete_count"`
|
IncompleteCount int `json:"incomplete_count"`
|
||||||
@@ -181,6 +201,10 @@ type metadata struct {
|
|||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
Root string `json:"root"`
|
Root string `json:"root"`
|
||||||
|
BackupRoot string `json:"backup_root"`
|
||||||
|
Usage metadataUsage `json:"usage"`
|
||||||
|
QuotaBytes *int64 `json:"quota_bytes"`
|
||||||
|
QuotaError string `json:"quota_error"`
|
||||||
Complete bool `json:"complete"`
|
Complete bool `json:"complete"`
|
||||||
Errors []string `json:"errors"`
|
Errors []string `json:"errors"`
|
||||||
Filesystem metadataFilesystem `json:"filesystem"`
|
Filesystem metadataFilesystem `json:"filesystem"`
|
||||||
@@ -190,6 +214,16 @@ type metadata struct {
|
|||||||
Batches []metadataBatch `json:"batches"`
|
Batches []metadataBatch `json:"batches"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type metadataUsage struct {
|
||||||
|
Root string `json:"root"`
|
||||||
|
Complete bool `json:"complete"`
|
||||||
|
ActualBytes *int64 `json:"actual_bytes"`
|
||||||
|
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||||
|
FileCount *int `json:"file_count"`
|
||||||
|
DirCount *int `json:"dir_count"`
|
||||||
|
Errors []string `json:"errors"`
|
||||||
|
}
|
||||||
|
|
||||||
type metadataFilesystem struct {
|
type metadataFilesystem struct {
|
||||||
MountPoint string `json:"mount_point"`
|
MountPoint string `json:"mount_point"`
|
||||||
MountSource string `json:"mount_source"`
|
MountSource string `json:"mount_source"`
|
||||||
@@ -313,6 +347,14 @@ func (r *Reader) Snapshot(ctx context.Context) Snapshot {
|
|||||||
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
|
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
|
||||||
}
|
}
|
||||||
snapshot.Root = root
|
snapshot.Root = root
|
||||||
|
backupRoot, usage, quotaBytes, quotaError, err := projectUsageAndQuota(r.config.BackupRoot, root, file)
|
||||||
|
if err != nil {
|
||||||
|
return invalid(snapshot, err.Error())
|
||||||
|
}
|
||||||
|
snapshot.BackupRoot = backupRoot
|
||||||
|
snapshot.Usage = usage
|
||||||
|
snapshot.QuotaBytes = quotaBytes
|
||||||
|
snapshot.QuotaError = quotaError
|
||||||
if err := validateBatches(root, file.Batches); err != nil {
|
if err := validateBatches(root, file.Batches); err != nil {
|
||||||
return invalid(snapshot, err.Error())
|
return invalid(snapshot, err.Error())
|
||||||
}
|
}
|
||||||
@@ -366,6 +408,66 @@ func (r *Reader) observedAt() string {
|
|||||||
return r.now().UTC().Format(time.RFC3339)
|
return r.now().UTC().Format(time.RFC3339)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// projectUsageAndQuota 校验「备份根占用」与「配额」并把它们投影给页面。
|
||||||
|
//
|
||||||
|
// 三条独立边界:
|
||||||
|
// 1. 旧采集器没有 usage/quota —— 批次照旧可用,占用与配额显式「未上报」,绝不用批次和冒充;
|
||||||
|
// 2. 路径必须与部署配置的备份根完全一致,批次根必须在其下 —— 否则整份快照拒绝;
|
||||||
|
// 3. 遍历不完整/配额非法 —— 只把对应字段降为未知,不牵连批次表与磁盘容量。
|
||||||
|
func projectUsageAndQuota(configuredRoot, batchRoot string, file metadata) (string, Usage, *int64, string, error) {
|
||||||
|
expected := path.Clean(strings.TrimSpace(configuredRoot))
|
||||||
|
reported := strings.TrimSpace(file.Usage.Root)
|
||||||
|
declared := strings.TrimSpace(file.BackupRoot)
|
||||||
|
usageReported := reported != "" || declared != "" || file.Usage.Complete ||
|
||||||
|
file.Usage.ActualBytes != nil || len(file.Usage.Errors) > 0
|
||||||
|
if !usageReported {
|
||||||
|
quotaError := strings.TrimSpace(file.QuotaError)
|
||||||
|
if quotaError == "" {
|
||||||
|
quotaError = "采集器未上报备份配额(需要升级采集器)"
|
||||||
|
}
|
||||||
|
return expected, Usage{Error: "采集器未上报备份根占用(需要升级采集器)"}, nil, quotaError, nil
|
||||||
|
}
|
||||||
|
if expected == "" || !path.IsAbs(expected) {
|
||||||
|
return "", Usage{}, nil, "", errors.New("备份根未配置:无法校验快照里的根占用")
|
||||||
|
}
|
||||||
|
if reported != expected || declared != expected {
|
||||||
|
return "", Usage{}, nil, "", fmt.Errorf("快照 backup_root=%q/usage.root=%q 与配置 %q 不一致", declared, reported, expected)
|
||||||
|
}
|
||||||
|
if batchRoot != expected && !strings.HasPrefix(batchRoot, expected+"/") {
|
||||||
|
return "", Usage{}, nil, "", fmt.Errorf("批次根 %s 不在备份根 %s 下", batchRoot, expected)
|
||||||
|
}
|
||||||
|
usage := Usage{Root: reported, Complete: file.Usage.Complete}
|
||||||
|
if file.Usage.Complete && file.Usage.ActualBytes != nil {
|
||||||
|
usage.Measured = true
|
||||||
|
usage.ActualBytes = file.Usage.ActualBytes
|
||||||
|
usage.ApparentBytes = file.Usage.ApparentBytes
|
||||||
|
usage.FileCount = file.Usage.FileCount
|
||||||
|
usage.DirCount = file.Usage.DirCount
|
||||||
|
} else {
|
||||||
|
usage.Complete = false
|
||||||
|
usage.ActualBytes = nil
|
||||||
|
usage.ApparentBytes = nil
|
||||||
|
usage.FileCount = nil
|
||||||
|
usage.DirCount = nil
|
||||||
|
reasons := limit(file.Usage.Errors, 3)
|
||||||
|
if len(reasons) == 0 {
|
||||||
|
usage.Error = "备份根占用未知:采集器未给出完整字节"
|
||||||
|
} else {
|
||||||
|
usage.Error = "备份根占用未知:" + strings.Join(reasons, ";")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
quota := file.QuotaBytes
|
||||||
|
quotaError := strings.TrimSpace(file.QuotaError)
|
||||||
|
if quota != nil && *quota <= 0 {
|
||||||
|
quota = nil
|
||||||
|
quotaError = fmt.Sprintf("备份配额必须为正整数:%d", *file.QuotaBytes)
|
||||||
|
}
|
||||||
|
if quota == nil && quotaError == "" {
|
||||||
|
quotaError = "采集器未上报备份配额(需要升级采集器)"
|
||||||
|
}
|
||||||
|
return expected, usage, quota, quotaError, nil
|
||||||
|
}
|
||||||
|
|
||||||
func invalid(snapshot Snapshot, reason string) Snapshot {
|
func invalid(snapshot Snapshot, reason string) Snapshot {
|
||||||
snapshot.Metadata.Valid = false
|
snapshot.Metadata.Valid = false
|
||||||
snapshot.Metadata.Complete = false
|
snapshot.Metadata.Complete = false
|
||||||
@@ -374,6 +476,8 @@ func invalid(snapshot Snapshot, reason string) Snapshot {
|
|||||||
snapshot.Batches = []Batch{}
|
snapshot.Batches = []Batch{}
|
||||||
snapshot.Capacity = Capacity{Error: reason}
|
snapshot.Capacity = Capacity{Error: reason}
|
||||||
snapshot.Totals = Totals{}
|
snapshot.Totals = Totals{}
|
||||||
|
snapshot.Usage = Usage{Error: reason}
|
||||||
|
snapshot.QuotaBytes = nil
|
||||||
return snapshot
|
return snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,12 @@ func validMetadata() metadata {
|
|||||||
Host: "weknora-test",
|
Host: "weknora-test",
|
||||||
Source: "weknora-test:" + hostRoot,
|
Source: "weknora-test:" + hostRoot,
|
||||||
Root: hostRoot,
|
Root: hostRoot,
|
||||||
|
BackupRoot: "/srv/kb-backups",
|
||||||
|
Usage: metadataUsage{
|
||||||
|
Root: "/srv/kb-backups", Complete: true,
|
||||||
|
ActualBytes: int64p(20000), ApparentBytes: int64p(18000), FileCount: intp(12), DirCount: intp(4),
|
||||||
|
},
|
||||||
|
QuotaBytes: int64p(53687091200),
|
||||||
Complete: true,
|
Complete: true,
|
||||||
Errors: []string{},
|
Errors: []string{},
|
||||||
Filesystem: metadataFilesystem{
|
Filesystem: metadataFilesystem{
|
||||||
@@ -108,7 +114,7 @@ func writeMetadata(t *testing.T, value metadata) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func readerAt(filename string, now time.Time) *Reader {
|
func readerAt(filename string, now time.Time) *Reader {
|
||||||
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
|
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, BackupRoot: "/srv/kb-backups", Source: "configured", MaxAge: 15 * time.Minute})
|
||||||
reader.now = func() time.Time { return now }
|
reader.now = func() time.Time { return now }
|
||||||
return reader
|
return reader
|
||||||
}
|
}
|
||||||
@@ -156,7 +162,82 @@ func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
|
|||||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||||
}
|
}
|
||||||
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
|
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
|
||||||
t.Fatalf("来源/测量方式不对: %+v", snapshot)
|
t.Fatalf("来源/测量方式不对: %+v", snapshot.Source)
|
||||||
|
}
|
||||||
|
if snapshot.BackupRoot != "/srv/kb-backups" || !snapshot.Usage.Measured || snapshot.Usage.ActualBytes == nil || *snapshot.Usage.ActualBytes != 20000 {
|
||||||
|
t.Fatalf("备份根占用没有投影: %+v", snapshot.Usage)
|
||||||
|
}
|
||||||
|
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
|
||||||
|
t.Fatalf("配额没有投影: %v", snapshot.QuotaBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSnapshotLegacyMetadataKeepsBatchesButOccupancyUnknown(t *testing.T) {
|
||||||
|
value := validMetadata()
|
||||||
|
value.BackupRoot = ""
|
||||||
|
value.Usage = metadataUsage{}
|
||||||
|
value.QuotaBytes = nil
|
||||||
|
value.QuotaError = ""
|
||||||
|
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("旧快照仍应可用: %+v", snapshot.Metadata)
|
||||||
|
}
|
||||||
|
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil {
|
||||||
|
t.Fatalf("旧快照的批次不能丢: %+v", snapshot.Batches)
|
||||||
|
}
|
||||||
|
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || snapshot.Usage.Error == "" {
|
||||||
|
t.Fatalf("缺少 usage 必须显式未上报: %+v", snapshot.Usage)
|
||||||
|
}
|
||||||
|
if snapshot.QuotaBytes != nil || snapshot.QuotaError == "" {
|
||||||
|
t.Fatalf("缺少配额必须显式未上报: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSnapshotRejectsUsageRootMismatch(t *testing.T) {
|
||||||
|
value := validMetadata()
|
||||||
|
value.Usage.Root = "/data/kb-backups"
|
||||||
|
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 || snapshot.Usage.Measured {
|
||||||
|
t.Fatalf("占用根与配置不一致必须整块拒绝: %+v", snapshot)
|
||||||
|
}
|
||||||
|
if !strings.Contains(snapshot.Error, "不一致") {
|
||||||
|
t.Fatalf("不一致原因不清: %q", snapshot.Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSnapshotIncompleteUsageDoesNotBlankBatches(t *testing.T) {
|
||||||
|
value := validMetadata()
|
||||||
|
value.Usage.Complete = false
|
||||||
|
value.Usage.ActualBytes = int64p(123) // 部分计数:必须被丢弃
|
||||||
|
value.Usage.Errors = []string{"遍历失败:PermissionError: Permission denied"}
|
||||||
|
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("根占用不完整不能牵连整份快照: %+v", snapshot.Metadata)
|
||||||
|
}
|
||||||
|
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil || !snapshot.Capacity.Measured {
|
||||||
|
t.Fatalf("批次与磁盘容量必须保留: %+v", snapshot)
|
||||||
|
}
|
||||||
|
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || !strings.Contains(snapshot.Usage.Error, "Permission") {
|
||||||
|
t.Fatalf("占用必须为 null 并带原因: %+v", snapshot.Usage)
|
||||||
|
}
|
||||||
|
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
|
||||||
|
t.Fatalf("配额是配置事实,应保留: %v", snapshot.QuotaBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSnapshotRejectsInvalidQuota(t *testing.T) {
|
||||||
|
value := validMetadata()
|
||||||
|
value.QuotaBytes = int64p(0)
|
||||||
|
filename := writeMetadata(t, value)
|
||||||
|
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||||
|
if snapshot.QuotaBytes != nil || !strings.Contains(snapshot.QuotaError, "正整数") {
|
||||||
|
t.Fatalf("非法配额必须降为未知: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
|
||||||
|
}
|
||||||
|
if !snapshot.Metadata.Valid {
|
||||||
|
t.Fatalf("配额非法不应否掉批次: %+v", snapshot.Metadata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
|||||||
HostRoot: "/srv/kb-backups/rds-logical",
|
HostRoot: "/srv/kb-backups/rds-logical",
|
||||||
Source: "weknora-test:/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},
|
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
|
||||||
|
BackupRoot: "/srv/kb-backups",
|
||||||
|
Usage: backupinventory.Usage{
|
||||||
|
Root: "/srv/kb-backups", Measured: true, Complete: true, ActualBytes: &actual,
|
||||||
|
},
|
||||||
|
QuotaBytes: func() *int64 { value := int64(53687091200); return &value }(),
|
||||||
Mount: backupinventory.MountInfo{
|
Mount: backupinventory.MountInfo{
|
||||||
MountVerified: true,
|
MountVerified: true,
|
||||||
ReadOnly: true,
|
ReadOnly: true,
|
||||||
@@ -70,6 +75,13 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
|||||||
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
|
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
|
||||||
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
||||||
}
|
}
|
||||||
|
if payload.Data.BackupRoot != "/srv/kb-backups" || !payload.Data.Usage.Measured ||
|
||||||
|
payload.Data.Usage.ActualBytes == nil || *payload.Data.Usage.ActualBytes != 1024 {
|
||||||
|
t.Fatalf("备份根占用字段丢失: %+v", payload.Data.Usage)
|
||||||
|
}
|
||||||
|
if payload.Data.QuotaBytes == nil || *payload.Data.QuotaBytes != 53687091200 {
|
||||||
|
t.Fatalf("配额字段丢失: %v", payload.Data.QuotaBytes)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
|
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package httpapi
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -37,9 +39,6 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||||
"environments": views,
|
"environments": views,
|
||||||
"storage_ready": storageReady,
|
"storage_ready": storageReady,
|
||||||
// The page cannot test the server's transport rule from the browser URL
|
|
||||||
// alone (a TLS proxy and an untrusted proxy look identical there).
|
|
||||||
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
|
|
||||||
}})
|
}})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,10 +61,6 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque
|
|||||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||||
return
|
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)
|
catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeKBBindingError(w, err)
|
writeKBBindingError(w, err)
|
||||||
@@ -93,10 +88,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
|
|||||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
|
input.SourceAddress, input.SourceOrigin = requestAuditSource(r)
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeKBBindingError(w, err)
|
writeKBBindingError(w, err)
|
||||||
@@ -125,3 +117,43 @@ func writeKBBindingError(w http.ResponseWriter, err error) {
|
|||||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// requestAuditSource records the two facts the save audit needs: which console
|
||||||
|
// origin the admin used and the client address behind it. Audit only — nothing
|
||||||
|
// here decides whether a key may be typed or saved.
|
||||||
|
//
|
||||||
|
// The nearest proxy appends its peer to the END of X-Forwarded-For, so that hop
|
||||||
|
// is the trustworthy one; earlier entries are whatever the browser sent. A
|
||||||
|
// forwarded chain is honoured only when the direct peer is private/loopback
|
||||||
|
// (the deployment's own nginx), so a request that reaches the API directly
|
||||||
|
// cannot launder its address through a forged header.
|
||||||
|
func requestAuditSource(r *http.Request) (address, origin string) {
|
||||||
|
peer := r.RemoteAddr
|
||||||
|
if host, _, err := net.SplitHostPort(peer); err == nil {
|
||||||
|
peer = host
|
||||||
|
}
|
||||||
|
ip := net.ParseIP(strings.Trim(peer, "[]"))
|
||||||
|
if ip != nil {
|
||||||
|
address = ip.String()
|
||||||
|
if ip.IsLoopback() || ip.IsPrivate() {
|
||||||
|
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
|
||||||
|
if last := net.ParseIP(strings.TrimSpace(hops[len(hops)-1])); last != nil {
|
||||||
|
address = last.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed, err := url.Parse(strings.TrimSpace(r.Header.Get("Origin"))); err == nil &&
|
||||||
|
(parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" {
|
||||||
|
origin = parsed.Scheme + "://" + parsed.Host
|
||||||
|
return address, origin
|
||||||
|
}
|
||||||
|
if r.Host != "" {
|
||||||
|
scheme := "http"
|
||||||
|
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
|
||||||
|
scheme = "https"
|
||||||
|
}
|
||||||
|
origin = scheme + "://" + r.Host
|
||||||
|
}
|
||||||
|
return address, origin
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package httpapi
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -88,34 +87,37 @@ func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
|
func TestKBBindingCatalogAndSaveAcceptTypedKeysOnPlainHTTP(t *testing.T) {
|
||||||
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}}
|
store := &fakeKBBindings{
|
||||||
|
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
|
||||||
|
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
|
||||||
|
}
|
||||||
config := kbBindingHandler(t, store)
|
config := kbBindingHandler(t, store)
|
||||||
body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
|
catalogBody := `{"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 := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
|
||||||
request.SetPathValue("environment", "test")
|
request.SetPathValue("environment", "test")
|
||||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||||
response := httptest.NewRecorder()
|
response := httptest.NewRecorder()
|
||||||
config.handleKBBindingCatalog(response, request)
|
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 {
|
if response.Code != http.StatusOK {
|
||||||
t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String())
|
t.Fatalf("plain HTTP 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") {
|
if strings.Contains(response.Body.String(), "typed-key") {
|
||||||
t.Fatal("catalog response echoed the typed key")
|
t.Fatal("catalog response echoed the typed key")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
saveBody := `{"base_revision":1,"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
||||||
|
request = httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
|
||||||
|
request.SetPathValue("environment", "test")
|
||||||
|
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||||
|
response = httptest.NewRecorder()
|
||||||
|
config.handleKBBindingSave(response, request)
|
||||||
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("plain HTTP save status=%d body=%s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if store.lastSave.APIKey != "typed-key" {
|
||||||
|
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
||||||
@@ -129,95 +131,112 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
|
func TestKBBindingsReadDoesNotReportTransportCapability(t *testing.T) {
|
||||||
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
|
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
host string
|
|
||||||
allow bool
|
|
||||||
want bool
|
|
||||||
}{
|
|
||||||
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true},
|
|
||||||
{name: "private console without toggle", host: "172.29.151.11:28188", want: false},
|
|
||||||
{name: "loopback console", host: "127.0.0.1:8080", want: true},
|
|
||||||
} {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
config := kbBindingHandler(t, store)
|
config := kbBindingHandler(t, store)
|
||||||
config.WeKnoraAllowPrivateHTTP = tc.allow
|
|
||||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
|
||||||
request.Host = tc.host
|
request.Host = "172.29.151.11:28188"
|
||||||
response := httptest.NewRecorder()
|
response := httptest.NewRecorder()
|
||||||
config.handleKBBindings(response, request)
|
config.handleKBBindings(response, request)
|
||||||
if response.Code != http.StatusOK {
|
if response.Code != http.StatusOK {
|
||||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||||
}
|
}
|
||||||
var payload struct {
|
if strings.Contains(response.Body.String(), "secret_entry_allowed") {
|
||||||
Data struct {
|
t.Fatalf("read response still reports the removed capability: %s", response.Body.String())
|
||||||
SecretEntryAllowed bool `json:"secret_entry_allowed"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if payload.Data.SecretEntryAllowed != tc.want {
|
|
||||||
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
|
func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) {
|
||||||
const (
|
const (
|
||||||
privateHost = "172.29.151.11:28188"
|
saveBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
||||||
origin = "http://172.29.151.11:28188"
|
catalogBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
|
||||||
)
|
)
|
||||||
store := &fakeKBBindings{
|
store := &fakeKBBindings{
|
||||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
|
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
|
||||||
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
|
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
|
||||||
}
|
}
|
||||||
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
for _, allow := range []bool{false, true} {
|
||||||
|
config := kbBindingHandler(t, store)
|
||||||
|
config.WeKnoraAllowPrivateHTTP = allow
|
||||||
|
|
||||||
save := func(config *Config) *httptest.ResponseRecorder {
|
request := httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
|
||||||
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
|
|
||||||
request.Host = privateHost
|
|
||||||
request.SetPathValue("environment", "test")
|
request.SetPathValue("environment", "test")
|
||||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
|
||||||
request.Header.Set("Origin", origin)
|
|
||||||
response := httptest.NewRecorder()
|
response := httptest.NewRecorder()
|
||||||
config.handleKBBindingSave(response, request)
|
config.handleKBBindingSave(response, request)
|
||||||
return response
|
if response.Code != http.StatusOK {
|
||||||
}
|
t.Fatalf("save with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
|
||||||
catalog := func(config *Config) *httptest.ResponseRecorder {
|
|
||||||
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog",
|
|
||||||
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`))
|
|
||||||
request.Host = privateHost
|
|
||||||
request.SetPathValue("environment", "test")
|
|
||||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
|
||||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
|
||||||
request.Header.Set("Origin", origin)
|
|
||||||
response := httptest.NewRecorder()
|
|
||||||
config.handleKBBindingCatalog(response, request)
|
|
||||||
return response
|
|
||||||
}
|
|
||||||
|
|
||||||
enabled := kbBindingHandler(t, store)
|
|
||||||
enabled.WeKnoraAllowPrivateHTTP = true
|
|
||||||
if response := save(enabled); response.Code != http.StatusOK {
|
|
||||||
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String())
|
|
||||||
}
|
}
|
||||||
if store.lastSave.APIKey != "typed-key" {
|
if store.lastSave.APIKey != "typed-key" {
|
||||||
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
|
t.Fatalf("save with toggle=%v did not forward the typed key: %q", allow, store.lastSave.APIKey)
|
||||||
}
|
|
||||||
if response := catalog(enabled); response.Code != http.StatusOK {
|
|
||||||
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
disabled := kbBindingHandler(t, store)
|
request = httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
|
||||||
if response := save(disabled); response.Code != http.StatusBadRequest {
|
request.SetPathValue("environment", "test")
|
||||||
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String())
|
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||||
}
|
response = httptest.NewRecorder()
|
||||||
if response := catalog(disabled); response.Code != http.StatusBadRequest {
|
config.handleKBBindingCatalog(response, request)
|
||||||
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String())
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("catalog with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKBBindingSaveAuditSourcePrefersTheProxyAppendedHop(t *testing.T) {
|
||||||
|
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}}}
|
||||||
|
config := kbBindingHandler(t, store)
|
||||||
|
body := `{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
remote string
|
||||||
|
forwarded string
|
||||||
|
origin string
|
||||||
|
proto string
|
||||||
|
host string
|
||||||
|
wantAddress string
|
||||||
|
wantOrigin string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "private proxy appends the real client after a forged hop",
|
||||||
|
remote: "10.0.0.5:41234", forwarded: "6.6.6.6, 172.29.151.11",
|
||||||
|
origin: "http://172.29.151.11:8088", host: "172.29.151.11:8088",
|
||||||
|
wantAddress: "172.29.151.11", wantOrigin: "http://172.29.151.11:8088",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "direct peer cannot launder its address through a forged chain",
|
||||||
|
remote: "203.0.113.9:41234", forwarded: "6.6.6.6",
|
||||||
|
host: "console.example",
|
||||||
|
wantAddress: "203.0.113.9", wantOrigin: "http://console.example",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "trusted proxy scheme fills in for a missing Origin",
|
||||||
|
remote: "10.0.0.5:41234", proto: "https", host: "kb.example",
|
||||||
|
wantAddress: "10.0.0.5", wantOrigin: "https://kb.example",
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest(http.MethodPut, "http://"+tc.host+"/api/v1/kb-bindings/test", strings.NewReader(body))
|
||||||
|
request.SetPathValue("environment", "test")
|
||||||
|
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||||
|
request.RemoteAddr = tc.remote
|
||||||
|
if tc.forwarded != "" {
|
||||||
|
request.Header.Set("X-Forwarded-For", tc.forwarded)
|
||||||
|
}
|
||||||
|
if tc.origin != "" {
|
||||||
|
request.Header.Set("Origin", tc.origin)
|
||||||
|
}
|
||||||
|
if tc.proto != "" {
|
||||||
|
request.Header.Set("X-Forwarded-Proto", tc.proto)
|
||||||
|
}
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
config.handleKBBindingSave(response, request)
|
||||||
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if store.lastSave.SourceAddress != tc.wantAddress || store.lastSave.SourceOrigin != tc.wantOrigin {
|
||||||
|
t.Fatalf("audit source = %q/%q, want %q/%q",
|
||||||
|
store.lastSave.SourceAddress, store.lastSave.SourceOrigin, tc.wantAddress, tc.wantOrigin)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// secretTransportAllowed is the single rule for typing a secret into the
|
// secretTransportAllowed is the strict rule for QA AI model keys: a real TLS
|
||||||
// console: a real TLS connection, a loopback request, or a same-origin HTTPS
|
// connection, a loopback request, or a same-origin HTTPS request that a trusted
|
||||||
// request that a trusted reverse proxy forwarded. The browser's origin scheme
|
// reverse proxy forwarded. The browser's origin scheme must agree, so a
|
||||||
// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit
|
// plain-HTTP page behind a misconfigured proxy cannot submit a key even if it
|
||||||
// a key even if it spoofs X-Forwarded-Proto.
|
// spoofs X-Forwarded-Proto. Knowledge base keys deliberately do not use it.
|
||||||
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||||
if r.TLS != nil {
|
if r.TLS != nil {
|
||||||
return true
|
return true
|
||||||
@@ -26,47 +26,6 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
|
|
||||||
// fetch from the operator console itself when it is served over plain http on a
|
|
||||||
// private address. That is the only non-TLS shape this deployment needs, and it
|
|
||||||
// still requires an exact Origin/Host match. It deliberately does not require
|
|
||||||
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
|
|
||||||
// http console on a private address never carries that header.
|
|
||||||
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
|
|
||||||
if secretTransportAllowed(r, trustTLSProxy) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if !allowPrivateHTTP {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
|
||||||
if origin == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
parsed, err := url.Parse(origin)
|
|
||||||
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
host := parsed.Hostname()
|
|
||||||
return privateAddressHost(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
|
|
||||||
// it cannot simply call secretTransportAllowed: that gate guards a write and
|
|
||||||
// therefore insists on a same-origin Origin header, which a GET navigation
|
|
||||||
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
|
|
||||||
// browsers cannot set it and the deployment already declares the proxy
|
|
||||||
// trusted; a forged header still cannot make the write gate accept anything.
|
|
||||||
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
|
|
||||||
if r.TLS != nil || loopbackHost(r.Host) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return allowPrivateHTTP && privateAddressHost(r.Host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// requestHostname strips the optional port and IPv6 brackets. Brackets come
|
// requestHostname strips the optional port and IPv6 brackets. Brackets come
|
||||||
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
|
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
|
||||||
// ported forms are not address spellings the server or a browser ever emits,
|
// ported forms are not address spellings the server or a browser ever emits,
|
||||||
@@ -103,15 +62,3 @@ func loopbackHost(host string) bool {
|
|||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
return ip != nil && ip.IsLoopback()
|
return ip != nil && ip.IsLoopback()
|
||||||
}
|
}
|
||||||
|
|
||||||
// privateAddressHost accepts loopback and private addresses. Names other than
|
|
||||||
// localhost are rejected because the deployment toggle is about addresses,
|
|
||||||
// not about trusting whatever DNS resolves to.
|
|
||||||
func privateAddressHost(host string) bool {
|
|
||||||
host = requestHostname(host)
|
|
||||||
if strings.EqualFold(host, "localhost") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
ip := net.ParseIP(host)
|
|
||||||
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,60 +1,11 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
host string
|
|
||||||
tls bool
|
|
||||||
xfp string
|
|
||||||
trust bool
|
|
||||||
allow bool
|
|
||||||
want bool
|
|
||||||
}{
|
|
||||||
{name: "direct TLS", host: "console.example", tls: true, want: true},
|
|
||||||
{name: "loopback name", host: "localhost:8080", want: true},
|
|
||||||
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
|
|
||||||
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
|
|
||||||
{name: "loopback v6 without port", host: "[::1]", want: true},
|
|
||||||
// Bracketed non-IPv6 hosts are not address spellings; they must not
|
|
||||||
// borrow loopback trust from the bracket stripper.
|
|
||||||
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
|
|
||||||
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
|
|
||||||
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
|
|
||||||
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
|
|
||||||
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
|
|
||||||
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
|
|
||||||
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
|
|
||||||
{name: "public name with toggle", host: "console.example", allow: true, want: false},
|
|
||||||
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
|
|
||||||
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
|
|
||||||
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
|
|
||||||
// A forged header must not beat the address rule when the proxy is not trusted.
|
|
||||||
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
|
|
||||||
request.Host = tc.host
|
|
||||||
if tc.tls {
|
|
||||||
request.TLS = &tls.ConnectionState{}
|
|
||||||
}
|
|
||||||
if tc.xfp != "" {
|
|
||||||
request.Header.Set("X-Forwarded-Proto", tc.xfp)
|
|
||||||
}
|
|
||||||
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
|
|
||||||
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
|
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
|
||||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||||
request.Host = "[::1]"
|
request.Host = "[::1]"
|
||||||
@@ -67,25 +18,6 @@ func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Plain-http consoles are not secure contexts, so Chrome never sends
|
|
||||||
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
|
|
||||||
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
|
|
||||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
|
|
||||||
request.Host = "192.168.50.134:18093"
|
|
||||||
request.Header.Set("Origin", "http://192.168.50.134:18093")
|
|
||||||
if !secretTransportAllowedForPrivateConsole(request, false, true) {
|
|
||||||
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
|
|
||||||
}
|
|
||||||
request.Header.Set("Origin", "http://evil.example")
|
|
||||||
if secretTransportAllowedForPrivateConsole(request, false, true) {
|
|
||||||
t.Fatal("cross-origin request was accepted as a private console")
|
|
||||||
}
|
|
||||||
request.Header.Set("Origin", "http://192.168.50.134:18093")
|
|
||||||
if secretTransportAllowedForPrivateConsole(request, false, false) {
|
|
||||||
t.Fatal("private console was accepted with the deployment toggle off")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
|
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
|
||||||
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
|
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
|
||||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||||
@@ -93,11 +25,6 @@ func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
|
|||||||
if secretTransportAllowed(request, false) {
|
if secretTransportAllowed(request, false) {
|
||||||
t.Fatalf("Host %q was accepted as a loopback transport", host)
|
t.Fatalf("Host %q was accepted as a loopback transport", host)
|
||||||
}
|
}
|
||||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
|
||||||
request.Header.Set("Origin", "http://"+host)
|
|
||||||
if secretTransportAllowedForPrivateConsole(request, false, true) {
|
|
||||||
t.Fatalf("Host %q was accepted as a private console", host)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -142,8 +142,8 @@ type Config struct {
|
|||||||
// internal/external bindings saved together. Nil keeps the page read-only
|
// internal/external bindings saved together. Nil keeps the page read-only
|
||||||
// and reports unavailable, never a fake success.
|
// and reports unavailable, never a fake success.
|
||||||
KBBindings KBBindingStore
|
KBBindings KBBindingStore
|
||||||
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key;
|
// WeKnoraAllowPrivateHTTP 决定客户端/探活是否放行同网段 http(生产 18093 反代);
|
||||||
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。
|
// 不再参与控制台密钥录入判定。
|
||||||
WeKnoraAllowPrivateHTTP bool
|
WeKnoraAllowPrivateHTTP bool
|
||||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||||
// enumerates the production-side bases the operator can bind.
|
// enumerates the production-side bases the operator can bind.
|
||||||
|
|||||||
@@ -112,6 +112,10 @@ type SaveInput struct {
|
|||||||
APIKey string `json:"api_key"`
|
APIKey string `json:"api_key"`
|
||||||
InternalKBID string `json:"internal_kb_id"`
|
InternalKBID string `json:"internal_kb_id"`
|
||||||
ExternalKBID string `json:"external_kb_id"`
|
ExternalKBID string `json:"external_kb_id"`
|
||||||
|
// 审计用:由 HTTP 层按连接事实填充,不属于请求体(严格解码下客户端
|
||||||
|
// 提交同名字段会被拒绝)。只是事后取证,不参与任何放行判定。
|
||||||
|
SourceAddress string `json:"-"`
|
||||||
|
SourceOrigin string `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Target is what consumers (readiness, upload, listing, monitoring) need to
|
// Target is what consumers (readiness, upload, listing, monitoring) need to
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
@@ -209,3 +210,14 @@ func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
|
|||||||
t.Fatalf("bound view must not claim a fallback: %+v", bound)
|
t.Fatalf("bound view must not claim a fallback: %+v", bound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAuditTextBoundsWithoutSplittingUTF8(t *testing.T) {
|
||||||
|
// 恶意 Origin 可能带非 ASCII:截断若切开跑码点,PostgreSQL text 会拒收整条保存。
|
||||||
|
got := auditText(strings.Repeat("密钥", 100), 10)
|
||||||
|
if len(got) > 10 || !utf8.ValidString(got) || got == "" {
|
||||||
|
t.Fatalf("auditText = %q (%d bytes)", got, len(got))
|
||||||
|
}
|
||||||
|
if auditText(" ", 10) != "" {
|
||||||
|
t.Fatal("blank audit source must stay empty, never a placeholder")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -286,6 +286,8 @@ func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) {
|
|||||||
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||||
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||||
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
|
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
|
||||||
|
// 非 HTTPS 控制台保存:审计行必须能还原当时的入口与客户端地址。
|
||||||
|
SourceAddress: "172.29.151.11", SourceOrigin: "http://172.29.151.11:8088",
|
||||||
}, "admin", now.Add(time.Minute))
|
}, "admin", now.Add(time.Minute))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("clear Save() error = %v", err)
|
t.Fatalf("clear Save() error = %v", err)
|
||||||
@@ -364,6 +366,17 @@ WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil {
|
|||||||
if keyConfigured {
|
if keyConfigured {
|
||||||
t.Fatal("history still says the cleared key is configured")
|
t.Fatal("history still says the cleared key is configured")
|
||||||
}
|
}
|
||||||
|
var sourceAddress, sourceOrigin, sourceActor string
|
||||||
|
var sourceEnv string
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT source_address,source_origin,actor,environment FROM weknora_environment_binding_history
|
||||||
|
WHERE environment='test' AND revision=2`).Scan(&sourceAddress, &sourceOrigin, &sourceActor, &sourceEnv); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if sourceAddress != "172.29.151.11" || sourceOrigin != "http://172.29.151.11:8088" ||
|
||||||
|
sourceActor != "admin" || sourceEnv != "test" {
|
||||||
|
t.Fatalf("save audit = %q/%q actor=%q env=%q", sourceAddress, sourceOrigin, sourceActor, sourceEnv)
|
||||||
|
}
|
||||||
var secretColumns int
|
var secretColumns int
|
||||||
if err := pool.QueryRow(ctx, `
|
if err := pool.QueryRow(ctx, `
|
||||||
SELECT COUNT(*) FROM information_schema.columns
|
SELECT COUNT(*) FROM information_schema.columns
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
@@ -206,9 +207,11 @@ ON CONFLICT(environment) DO UPDATE SET
|
|||||||
}
|
}
|
||||||
if _, err := tx.Exec(ctx, `
|
if _, err := tx.Exec(ctx, `
|
||||||
INSERT INTO weknora_environment_binding_history(
|
INSERT INTO weknora_environment_binding_history(
|
||||||
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at)
|
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at,
|
||||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
source_address,source_origin)
|
||||||
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil {
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
|
||||||
|
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC(),
|
||||||
|
auditText(input.SourceAddress, 128), auditText(input.SourceOrigin, 300)); err != nil {
|
||||||
return View{}, ErrStorage
|
return View{}, ErrStorage
|
||||||
}
|
}
|
||||||
replan := postgresstore.RoutingBindingReplanResult{}
|
replan := postgresstore.RoutingBindingReplanResult{}
|
||||||
@@ -353,3 +356,19 @@ func shortID(value string) string {
|
|||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// auditText bounds one audit column. An empty value stays empty: the audit row
|
||||||
|
// must never present a guessed address as fact. Truncation stops on a rune
|
||||||
|
// boundary because PostgreSQL text refuses invalid UTF-8 (a hostile Origin
|
||||||
|
// header must not turn a save into a storage error).
|
||||||
|
func auditText(value string, limit int) string {
|
||||||
|
value = strings.ToValidUTF8(strings.TrimSpace(value), "")
|
||||||
|
if len(value) <= limit {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
value = value[:limit]
|
||||||
|
for len(value) > 0 && !utf8.ValidString(value) {
|
||||||
|
value = value[:len(value)-1]
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,6 +18,27 @@ const LegacyVersion = 74
|
|||||||
// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。
|
// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。
|
||||||
const V090Version = 134
|
const V090Version = 134
|
||||||
|
|
||||||
|
// V091Version 是 0.9.1 的 schema_migrations 版本号(上游 tag v0.9.1,最大迁移 137)。
|
||||||
|
// 135–137 只改审计列宽/凭据表/IM 唯一索引,不碰知识域表、列或触发器,因此 v091
|
||||||
|
// 由 v090 克隆后只改版本字段,不复制一份表/列/触发器常量。
|
||||||
|
const V091Version = 137
|
||||||
|
|
||||||
|
// RelatedTableClass 是知识域关联表的搬运归类。copied = 随整库搬运(即该版本的
|
||||||
|
// Required/Optional 表);derived = 由触发器/应用派生,不单独搬运;excluded =
|
||||||
|
// 明确不搬,必须写明原因。分类只写在 profile 这一处,门禁按它放行。
|
||||||
|
type RelatedTableClass string
|
||||||
|
|
||||||
|
const (
|
||||||
|
RelatedCopied RelatedTableClass = "copied"
|
||||||
|
RelatedDerived RelatedTableClass = "derived"
|
||||||
|
RelatedExcluded RelatedTableClass = "excluded"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RelatedTable struct {
|
||||||
|
Class RelatedTableClass
|
||||||
|
Reason string
|
||||||
|
}
|
||||||
|
|
||||||
// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。
|
// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。
|
||||||
type PartRequirement struct {
|
type PartRequirement struct {
|
||||||
Kind string
|
Kind string
|
||||||
@@ -41,6 +62,9 @@ type Profile struct {
|
|||||||
ReviewedTriggers []string
|
ReviewedTriggers []string
|
||||||
RequiredParts []PartRequirement
|
RequiredParts []PartRequirement
|
||||||
OptionalParts []PartRequirement
|
OptionalParts []PartRequirement
|
||||||
|
// RelatedTables 是该版本全部知识域关联表的归类(copied/derived/excluded)。
|
||||||
|
// 漏表门禁按它判定:未归类且有本库数据的表一律拒绝。
|
||||||
|
RelatedTables map[string]RelatedTable
|
||||||
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
|
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
|
||||||
// 不允许回退成空串去匹配任何索引。
|
// 不允许回退成空串去匹配任何索引。
|
||||||
IndexContractSource string
|
IndexContractSource string
|
||||||
@@ -93,6 +117,9 @@ var profiles = map[int]Profile{
|
|||||||
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
|
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
|
||||||
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
|
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
|
||||||
"wiki_page_issues",
|
"wiki_page_issues",
|
||||||
|
// 编辑历史随内容搬运(D1)。放在父表之后:importRows 按本序插入、
|
||||||
|
// 倒序删除,两张历史表因此在 chunks/wiki_pages 之后写、在它们之前删。
|
||||||
|
"chunk_revisions", "wiki_page_revisions",
|
||||||
},
|
},
|
||||||
// 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。
|
// 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。
|
||||||
OptionalTables: []string{"wiki_log_entries"},
|
OptionalTables: []string{"wiki_log_entries"},
|
||||||
@@ -106,12 +133,15 @@ var profiles = map[int]Profile{
|
|||||||
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
|
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
|
||||||
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
|
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
|
||||||
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
|
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
|
||||||
|
"chunk_revisions": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "chunk_id"},
|
||||||
|
"wiki_page_revisions": {"id", "tenant_id", "knowledge_base_id", "page_id"},
|
||||||
},
|
},
|
||||||
RequiredParts: []PartRequirement{
|
RequiredParts: []PartRequirement{
|
||||||
{"database", "knowledges"}, {"database", "chunks"},
|
{"database", "knowledges"}, {"database", "chunks"},
|
||||||
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
|
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
|
||||||
{"database", "resources"}, {"database", "resource_bindings"},
|
{"database", "resources"}, {"database", "resource_bindings"},
|
||||||
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"},
|
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"},
|
||||||
|
{"database", "chunk_revisions"}, {"wiki", "wiki_page_revisions"},
|
||||||
{"index", "chunks"},
|
{"index", "chunks"},
|
||||||
},
|
},
|
||||||
OptionalParts: []PartRequirement{
|
OptionalParts: []PartRequirement{
|
||||||
@@ -130,19 +160,74 @@ var profiles = map[int]Profile{
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// init 在一次声明上补齐两件事,避免复制常量:
|
||||||
|
// 1. 每个版本的知识域关联表分类(copied 由该版本的 Required/Optional 表派生);
|
||||||
|
// 2. v0.9.1 = v0.9.0 的克隆,只改版本字段。135–137 不碰知识域,表/列/触发器/
|
||||||
|
// 部件必须与 v090 完全一致,任何分叉都会被测试抓住。
|
||||||
|
func init() {
|
||||||
|
for version, profile := range profiles {
|
||||||
|
profile.RelatedTables = classifyKnowledgeTables(profile)
|
||||||
|
profiles[version] = profile
|
||||||
|
}
|
||||||
|
v090 := profiles[V090Version]
|
||||||
|
v091 := v090
|
||||||
|
v091.Name, v091.SchemaVersion, v091.WeKnoraVersion = "v091", V091Version, "v0.9.1"
|
||||||
|
profiles[V091Version] = v091
|
||||||
|
}
|
||||||
|
|
||||||
|
// classifyKnowledgeTables 把该版本声明过的表标成 copied,并补上派生/排除表。
|
||||||
|
// 分类键覆盖真实 0.9.x 中所有带 knowledge_base_id/knowledge_id/kb_id 的表:
|
||||||
|
// 漏一张,漏表门禁就会在该表有数据时拒绝发布。
|
||||||
|
func classifyKnowledgeTables(profile Profile) map[string]RelatedTable {
|
||||||
|
tables := make(map[string]RelatedTable, len(profile.RequiredTables)+len(profile.OptionalTables)+len(excludedKnowledgeTables)+1)
|
||||||
|
for name, reason := range excludedKnowledgeTables {
|
||||||
|
tables[name] = RelatedTable{Class: RelatedExcluded, Reason: reason}
|
||||||
|
}
|
||||||
|
// 派生表:由触发器维护,随父表重算;不单独搬运。
|
||||||
|
tables["chunk_images"] = RelatedTable{Class: RelatedDerived,
|
||||||
|
Reason: "chunks 上的 chunk_images_sync 触发器维护的图片投影表,随 chunks 重算"}
|
||||||
|
for _, name := range profile.RequiredTables {
|
||||||
|
tables[name] = RelatedTable{Class: RelatedCopied, Reason: "知识库内容表,随整库搬运并做范围改写与目标身份映射"}
|
||||||
|
}
|
||||||
|
for _, name := range profile.OptionalTables {
|
||||||
|
tables[name] = RelatedTable{Class: RelatedCopied, Reason: "知识库内容表(可选),存在时随整库搬运并做范围改写与目标身份映射"}
|
||||||
|
}
|
||||||
|
return tables
|
||||||
|
}
|
||||||
|
|
||||||
|
// excludedKnowledgeTables 是明确不搬的知识域关联表及原因。原因必须解释
|
||||||
|
// "为什么生产不需要它/为什么覆盖会破坏目标",不能只写"不搬"。
|
||||||
|
var excludedKnowledgeTables = map[string]string{
|
||||||
|
"knowledge_processing_spans": "解析流水线的阶段遥测;生产只做推理、不解析,搬运会把测试侧处理过程当成生产内容",
|
||||||
|
"sessions": "对话会话属于各环境自己的运行数据,搬运会覆盖/污染目标用户会话",
|
||||||
|
"messages": "对话消息属于各环境自己的运行数据,不能从测试库覆盖生产",
|
||||||
|
"memory_doc_affinity": "记忆与文档的运行期关联,生产会自行建立,搬运会造成跨环境语义错配",
|
||||||
|
"user_kb_pins": "用户置顶是各环境自己的偏好配置,生产用户 ID 在测试侧不存在",
|
||||||
|
"kb_shares": "组织共享关系绑定本实例的组织/用户,跨环境搬运会产生无效授权",
|
||||||
|
"im_channels": "IM 渠道配置属于各环境的接入配置,含环境专属凭据/回调",
|
||||||
|
"data_sources": "数据源配置属于各环境的接入配置,生产不复用测试侧连接",
|
||||||
|
"embeddings": "仅 PG 检索模式(条件迁移)创建的向量表;本平台契约固定 elasticsearch_v8,检索不读它",
|
||||||
|
}
|
||||||
|
|
||||||
|
// RelatedTableClass 返回某张关联表的分类与理由;未分类时 ok=false。
|
||||||
|
func (p Profile) RelatedTableClass(name string) (RelatedTable, bool) {
|
||||||
|
table, ok := p.RelatedTables[name]
|
||||||
|
return table, ok
|
||||||
|
}
|
||||||
|
|
||||||
// For 按版本号选中 profile。未知版本一律失败:版本号是"选哪份声明"的索引,
|
// For 按版本号选中 profile。未知版本一律失败:版本号是"选哪份声明"的索引,
|
||||||
// 不是"能不能放行"的依据,所以绝不返回默认 profile。
|
// 不是"能不能放行"的依据,所以绝不返回默认 profile。
|
||||||
func For(version int) (Profile, error) {
|
func For(version int) (Profile, error) {
|
||||||
profile, ok := profiles[version]
|
profile, ok := profiles[version]
|
||||||
if !ok {
|
if !ok {
|
||||||
return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071) and 134 (v090)", version)
|
return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071), 134 (v090) and 137 (v091)", version)
|
||||||
}
|
}
|
||||||
return profile, nil
|
return profile, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
|
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
|
||||||
func Supported() []int {
|
func Supported() []int {
|
||||||
return []int{LegacyVersion, V090Version}
|
return []int{LegacyVersion, V090Version, V091Version}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TableSet 是"可能出现的表"集合:必需表 + 可选表。
|
// TableSet 是"可能出现的表"集合:必需表 + 可选表。
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package libraryprofile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestForV091IsDeclaredAndSharesV090Contract(t *testing.T) {
|
||||||
|
profile, err := For(V091Version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("For(137): %v", err)
|
||||||
|
}
|
||||||
|
if profile.SchemaVersion != 137 || profile.Name != "v091" || profile.WeKnoraVersion != "v0.9.1" {
|
||||||
|
t.Fatalf("unexpected v0.9.1 profile: %+v", profile)
|
||||||
|
}
|
||||||
|
supported := Supported()
|
||||||
|
if !reflect.DeepEqual(supported, []int{74, 134, 137}) {
|
||||||
|
t.Fatalf("Supported()=%v", supported)
|
||||||
|
}
|
||||||
|
v090, err := For(V090Version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// 除了版本三字段,v091 必须与 v090 完全一致;任何分叉都意味着表/列/触发器
|
||||||
|
// 被复制或漂移,升级后会与真实 schema 对不上。
|
||||||
|
v091 := profile
|
||||||
|
v091.Name, v091.SchemaVersion, v091.WeKnoraVersion = v090.Name, v090.SchemaVersion, v090.WeKnoraVersion
|
||||||
|
if !reflect.DeepEqual(v090, v091) {
|
||||||
|
t.Fatal("v0.9.1 must be a version-only clone of v0.9.0")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredTablesAreAllClassifiedCopied(t *testing.T) {
|
||||||
|
for _, version := range Supported() {
|
||||||
|
profile, err := For(version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, table := range append(append([]string{}, profile.RequiredTables...), profile.OptionalTables...) {
|
||||||
|
class, ok := profile.RelatedTableClass(table)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s: declared table %s has no classification", profile.Name, table)
|
||||||
|
}
|
||||||
|
if class.Class != RelatedCopied || strings.TrimSpace(class.Reason) == "" {
|
||||||
|
t.Fatalf("%s: declared table %s must be copied with a reason, got %+v", profile.Name, table, class)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEveryRealKnowledgeScopedTableIsClassified(t *testing.T) {
|
||||||
|
// 真实测试 WeKnora 0.9.0 的只读 information_schema 结果(2026-11-30):
|
||||||
|
// 带 knowledge_base_id/knowledge_id/kb_id 的 public 表共 18 张。漏一张,
|
||||||
|
// 漏表门禁就会在该表有数据时拒绝发布;这里把它锁成契约。
|
||||||
|
realTables := []string{
|
||||||
|
"chunk_images", "chunk_revisions", "chunks", "data_sources", "im_channels",
|
||||||
|
"knowledge_processing_spans", "knowledge_tag_relations", "knowledge_tags",
|
||||||
|
"knowledges", "kb_shares", "memory_doc_affinity", "messages", "sessions",
|
||||||
|
"user_kb_pins", "wiki_folders", "wiki_page_issues", "wiki_page_revisions", "wiki_pages",
|
||||||
|
}
|
||||||
|
// embeddings 是条件迁移(仅 PG 检索模式)创建的,真实测试库不存在,也必须
|
||||||
|
// 预置分类,避免未来启用后被误判为未声明表。
|
||||||
|
optionalRealTables := []string{"embeddings"}
|
||||||
|
for _, version := range []int{V090Version, V091Version} {
|
||||||
|
profile, err := For(version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, table := range append(append([]string{}, realTables...), optionalRealTables...) {
|
||||||
|
class, ok := profile.RelatedTableClass(table)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s: real knowledge-scoped table %s is unclassified", profile.Name, table)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(class.Reason) == "" {
|
||||||
|
t.Fatalf("%s: %s has an empty classification reason", profile.Name, table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if class, _ := profile.RelatedTableClass("chunk_images"); class.Class != RelatedDerived {
|
||||||
|
t.Fatalf("chunk_images must be derived, got %+v", class)
|
||||||
|
}
|
||||||
|
for _, table := range []string{"sessions", "messages", "knowledge_processing_spans", "data_sources"} {
|
||||||
|
if class, _ := profile.RelatedTableClass(table); class.Class != RelatedExcluded {
|
||||||
|
t.Fatalf("%s must be excluded, got %+v", table, class)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionTablesAreCopiedAndOrderedAfterParents(t *testing.T) {
|
||||||
|
profile, err := For(V091Version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
position := func(table string) int {
|
||||||
|
for index, name := range profile.RequiredTables {
|
||||||
|
if name == table {
|
||||||
|
return index
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("required table %s missing", table)
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
if position("chunk_revisions") < position("chunks") {
|
||||||
|
t.Fatal("chunk_revisions must be written after chunks")
|
||||||
|
}
|
||||||
|
if position("wiki_page_revisions") < position("wiki_pages") {
|
||||||
|
t.Fatal("wiki_page_revisions must be written after wiki_pages")
|
||||||
|
}
|
||||||
|
if !profile.RequiresPart("database/chunk_revisions") || !profile.RequiresPart("wiki/wiki_page_revisions") {
|
||||||
|
t.Fatal("both revision parts must be required archive parts")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -119,6 +119,9 @@ type WriteSet struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
Rows []WriteSetRow `json:"rows"`
|
Rows []WriteSetRow `json:"rows"`
|
||||||
Universe map[string]TableFingerprint `json:"universe"`
|
Universe map[string]TableFingerprint `json:"universe"`
|
||||||
|
// Warnings 是放行但需要留痕的契约警告(例如未分类但为空的表)。omitempty:
|
||||||
|
// 空警告不改变历史计划的规范字节/摘要,旧记录读回仍然一致。
|
||||||
|
Warnings []string `json:"warnings,omitempty"`
|
||||||
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
|
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
|
||||||
// 记录被改一个字节就对不上。
|
// 记录被改一个字节就对不上。
|
||||||
Digest string `json:"digest"`
|
Digest string `json:"digest"`
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package libraryrelease
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 空警告必须不改变历史 V2 计划的规范字节:omitempty 是兼容边界,不是装饰。
|
||||||
|
func TestWriteSetWarningsAreOmittedWhenEmpty(t *testing.T) {
|
||||||
|
base := WriteSet{
|
||||||
|
Version: MigrationWriteSetVersion, ContractVersion: 1,
|
||||||
|
JobID: "job-1", Target: "internal", TenantID: 1, KnowledgeBaseID: "kb-1",
|
||||||
|
BackupSnapshotID: "backup-1", TargetSnapshotID: "snapshot-1",
|
||||||
|
CreatedAt: time.Unix(1700000000, 0).UTC(),
|
||||||
|
Rows: []WriteSetRow{{Table: "knowledges", ID: "doc-1"}},
|
||||||
|
Universe: map[string]TableFingerprint{"knowledges": {Count: 1, Digest: "digest"}},
|
||||||
|
TargetIDMode: TargetIDModeScoped,
|
||||||
|
}
|
||||||
|
seal := func(set WriteSet) string {
|
||||||
|
t.Helper()
|
||||||
|
if err := set.Seal(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return set.Digest
|
||||||
|
}
|
||||||
|
withoutWarnings := seal(base)
|
||||||
|
withEmptyWarnings := base
|
||||||
|
withEmptyWarnings.Warnings = []string{}
|
||||||
|
if got := seal(withEmptyWarnings); got != withoutWarnings {
|
||||||
|
t.Fatalf("empty warnings changed the canonical digest: %s != %s", got, withoutWarnings)
|
||||||
|
}
|
||||||
|
withWarning := base
|
||||||
|
withWarning.Warnings = []string{"release_undeclared_kb_table: 未分类空表已放行"}
|
||||||
|
if got := seal(withWarning); got == withoutWarnings {
|
||||||
|
t.Fatal("a real warning must be part of the durable record")
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(withWarning)
|
||||||
|
if err != nil || !json.Valid(raw) {
|
||||||
|
t.Fatalf("warning record must serialize: %v", err)
|
||||||
|
}
|
||||||
|
if !containsJSONField(raw, "warnings") {
|
||||||
|
t.Fatal("warning must be persisted in the release record")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsJSONField(raw []byte, key string) bool {
|
||||||
|
var object map[string]json.RawMessage
|
||||||
|
if json.Unmarshal(raw, &object) != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, ok := object[key]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
@@ -7,18 +7,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries,
|
// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries,
|
||||||
// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。
|
// 但必须有编辑历史两表;0.7.1 没有两表、缺 wiki_log_entries 就是残包。
|
||||||
func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
||||||
part := func(kind, name string) Part {
|
part := func(kind, name string) Part {
|
||||||
return Part{Kind: kind, Name: name, SHA256: strings.Repeat("a", 64), Count: 1}
|
return Part{Kind: kind, Name: name, SHA256: strings.Repeat("a", 64), Count: 1}
|
||||||
}
|
}
|
||||||
parts := []Part{
|
legacyParts := []Part{
|
||||||
part("database", "knowledges"), part("database", "chunks"), part("database", "resources"),
|
part("database", "knowledges"), part("database", "chunks"), part("database", "resources"),
|
||||||
part("database", "resource_bindings"), part("database", "knowledge_tags"),
|
part("database", "resource_bindings"), part("database", "knowledge_tags"),
|
||||||
part("database", "knowledge_tag_relations"),
|
part("database", "knowledge_tag_relations"),
|
||||||
part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"),
|
part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"),
|
||||||
part("index", "chunks"),
|
part("index", "chunks"),
|
||||||
}
|
}
|
||||||
|
v090Parts := append(append([]Part{}, legacyParts...),
|
||||||
|
part("database", "chunk_revisions"), part("wiki", "wiki_page_revisions"))
|
||||||
manifest := func(version int, weknora string, parts []Part) Manifest {
|
manifest := func(version int, weknora string, parts []Part) Manifest {
|
||||||
return Manifest{
|
return Manifest{
|
||||||
ValidationPolicy: ArtifactAcceptancePolicy,
|
ValidationPolicy: ArtifactAcceptancePolicy,
|
||||||
@@ -36,23 +38,30 @@ func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := encodeManifest(manifest(134, "v0.9.0", parts)); err != nil {
|
if _, err := encodeManifest(manifest(134, "v0.9.0", v090Parts)); err != nil {
|
||||||
t.Fatalf("0.9.0 manifest without wiki_log_entries must be complete: %v", err)
|
t.Fatalf("0.9.0 manifest must be complete without wiki_log_entries: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := encodeManifest(manifest(74, "v0.7.1", parts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
|
if _, err := encodeManifest(manifest(137, "v0.9.1", v090Parts)); err != nil {
|
||||||
|
t.Fatalf("0.9.1 must share the 0.9.0 part set: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := encodeManifest(manifest(134, "v0.9.0", legacyParts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
|
||||||
|
t.Fatalf("0.9.0 manifest missing revision parts must be refused, got %v", err)
|
||||||
|
}
|
||||||
|
if _, err := encodeManifest(manifest(74, "v0.7.1", legacyParts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
|
||||||
t.Fatalf("0.7.1 manifest missing wiki_log_entries must be refused, got %v", err)
|
t.Fatalf("0.7.1 manifest missing wiki_log_entries must be refused, got %v", err)
|
||||||
}
|
}
|
||||||
withLog := append(append([]Part{}, parts...), part("wiki", "wiki_log_entries"))
|
legacyWithLog := append(append([]Part{}, legacyParts...), part("wiki", "wiki_log_entries"))
|
||||||
if _, err := encodeManifest(manifest(74, "v0.7.1", withLog)); err != nil {
|
if _, err := encodeManifest(manifest(74, "v0.7.1", legacyWithLog)); err != nil {
|
||||||
t.Fatalf("0.7.1 manifest with wiki_log_entries must pass: %v", err)
|
t.Fatalf("0.7.1 manifest with wiki_log_entries must pass: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := encodeManifest(manifest(134, "v0.9.0", withLog)); err != nil {
|
v090WithLog := append(append([]Part{}, v090Parts...), part("wiki", "wiki_log_entries"))
|
||||||
|
if _, err := encodeManifest(manifest(134, "v0.9.0", v090WithLog)); err != nil {
|
||||||
t.Fatalf("0.9.0 manifest may still carry an optional wiki_log_entries part: %v", err)
|
t.Fatalf("0.9.0 manifest may still carry an optional wiki_log_entries part: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := encodeManifest(manifest(74, "v0.9.0", withLog)); err == nil {
|
if _, err := encodeManifest(manifest(74, "v0.9.0", legacyWithLog)); err == nil {
|
||||||
t.Fatal("version string and profile version must agree")
|
t.Fatal("version string and profile version must agree")
|
||||||
}
|
}
|
||||||
if _, err := encodeManifest(manifest(135, "v0.9.0", parts)); err == nil {
|
if _, err := encodeManifest(manifest(135, "v0.9.0", v090Parts)); err == nil {
|
||||||
t.Fatal("unknown schema version must be refused")
|
t.Fatal("unknown schema version must be refused")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE weknora_environment_binding_history
|
||||||
|
DROP COLUMN IF EXISTS source_origin,
|
||||||
|
DROP COLUMN IF EXISTS source_address;
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- 「知识库绑定」保存审计需要回答“从哪个地址录入的”:管理员可能在非 HTTPS
|
||||||
|
-- 控制台录入明文密钥,事后只能靠这条记录还原当时的访问入口。来源地址只做
|
||||||
|
-- 审计,不参与任何放行/拒绝判定;空串表示无法可靠解析,不用猜测值填充。
|
||||||
|
ALTER TABLE weknora_environment_binding_history
|
||||||
|
ADD COLUMN IF NOT EXISTS source_address TEXT NOT NULL DEFAULT '',
|
||||||
|
ADD COLUMN IF NOT EXISTS source_origin TEXT NOT NULL DEFAULT '';
|
||||||
@@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("loadMigrations() error = %v", err)
|
t.Fatalf("loadMigrations() error = %v", err)
|
||||||
}
|
}
|
||||||
if len(migrations) != 82 {
|
if len(migrations) != 83 {
|
||||||
t.Fatalf("migration count = %d, want 82", len(migrations))
|
t.Fatalf("migration count = %d, want 83", len(migrations))
|
||||||
|
}
|
||||||
|
// 83 是密钥保存审计的来源列:只追加取证字段,来源解析不出时留空。
|
||||||
|
if source := migrations[82]; source.Version != 83 ||
|
||||||
|
!strings.Contains(source.UpSQL, "source_address") ||
|
||||||
|
!strings.Contains(source.UpSQL, "source_origin") ||
|
||||||
|
!strings.Contains(source.DownSQL, "DROP COLUMN IF EXISTS source_address") {
|
||||||
|
t.Fatalf("migration 83 = %#v", source)
|
||||||
}
|
}
|
||||||
// 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
|
// 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
|
||||||
// 实际实例身份;克隆实例同名/同 ID 不能冒充。
|
// 实际实例身份;克隆实例同名/同 ID 不能冒充。
|
||||||
|
|||||||
@@ -274,8 +274,10 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
|||||||
}
|
}
|
||||||
var bodies []json.RawMessage
|
var bodies []json.RawMessage
|
||||||
for _, table := range pg.Tables {
|
for _, table := range pg.Tables {
|
||||||
|
if libraryResourceBodyTable(table.Name) {
|
||||||
bodies = append(bodies, table.Rows...)
|
bodies = append(bodies, table.Rows...)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
references, err := libraryResourceHandles(bodies)
|
references, err := libraryResourceHandles(bodies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
|
|||||||
return PostgresSnapshot{}, err
|
return PostgresSnapshot{}, err
|
||||||
}
|
}
|
||||||
rowsByTable[table] = rows
|
rowsByTable[table] = rows
|
||||||
if table != "resource_bindings" && table != "knowledge_tag_relations" {
|
if libraryResourceBodyTable(table) {
|
||||||
bodies = append(bodies, rows...)
|
bodies = append(bodies, rows...)
|
||||||
}
|
}
|
||||||
if table == "resource_bindings" {
|
if table == "resource_bindings" {
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package v071
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"knowledge-governance/internal/libraryprofile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 漏表门禁:profile 只声明"必须存在什么",不声明"存在但没见过的表怎么办"。
|
||||||
|
// 于是 0.9.0 起 chunk_revisions / wiki_page_revisions 一直被静默跳过。这里用
|
||||||
|
// information_schema 反向扫描所有带知识列的表,按 profile 分类放行;未分类且
|
||||||
|
// 本次范围内有数据就拒绝,空表放行但留下警告。导出前(源库)与导入前(目标库)
|
||||||
|
// 各执行一次。
|
||||||
|
//
|
||||||
|
// 为什么错误不可重试:表没分类是契约缺口,重试不会让分类长出来;必须补 profile
|
||||||
|
// 或明确排除。错误里带表名与行数,运维不用再猜是哪张表。
|
||||||
|
|
||||||
|
const ReleaseUndeclaredKBTableCode = "release_undeclared_kb_table"
|
||||||
|
|
||||||
|
type UndeclaredKBTable struct {
|
||||||
|
Table string
|
||||||
|
Rows int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type UndeclaredKBTableError struct {
|
||||||
|
Tables []UndeclaredKBTable
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *UndeclaredKBTableError) Error() string {
|
||||||
|
parts := make([]string, 0, len(e.Tables))
|
||||||
|
for _, table := range e.Tables {
|
||||||
|
if table.Rows < 0 {
|
||||||
|
parts = append(parts, table.Table+"(行数无法判定)")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parts = append(parts, fmt.Sprintf("%s(%d 行)", table.Table, table.Rows))
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s: 未声明的知识域表在本次发布范围内仍有数据:%v;先补 profile 关联表分类并接入整库搬运,或明确排除并写明理由。此错误不可重试。",
|
||||||
|
ReleaseUndeclaredKBTableCode, parts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// knowledgeTableGateMarker 让测试夹具能区分"门禁探测"与"能力探测":两者都查
|
||||||
|
// information_schema.columns,但回答的列形状不同(表+列集合 vs 表+列)。
|
||||||
|
const knowledgeTableGateMarker = "/* knowledge-table-gate */"
|
||||||
|
|
||||||
|
const knowledgeScopedColumnsSQL = knowledgeTableGateMarker + `
|
||||||
|
SELECT c.table_name, array_agg(c.column_name ORDER BY c.column_name)
|
||||||
|
FROM information_schema.columns c
|
||||||
|
JOIN (
|
||||||
|
SELECT DISTINCT table_name
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema='public' AND column_name IN ('knowledge_base_id','knowledge_id','kb_id')
|
||||||
|
) k ON k.table_name = c.table_name
|
||||||
|
WHERE c.table_schema='public'
|
||||||
|
GROUP BY c.table_name
|
||||||
|
ORDER BY c.table_name`
|
||||||
|
|
||||||
|
// verifyDeclaredKnowledgeTables 返回放行警告(未分类但为空的表);有未分类且
|
||||||
|
// 非空的表时返回 UndeclaredKBTableError。identity 是本知识库范围。
|
||||||
|
func verifyDeclaredKnowledgeTables(ctx context.Context, db schemaProbeDB, identity PostgresIdentity,
|
||||||
|
profile libraryprofile.Profile) ([]string, error) {
|
||||||
|
if identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) {
|
||||||
|
return nil, errors.New("漏表门禁缺少有效的知识库范围身份")
|
||||||
|
}
|
||||||
|
// 没有分类的 profile 不允许"静默跳过门禁":那等于把契约缺口藏起来。
|
||||||
|
if len(profile.RelatedTables) == 0 {
|
||||||
|
return nil, fmt.Errorf("profile %s 没有关联表分类,拒绝跳过漏表门禁", profile.Name)
|
||||||
|
}
|
||||||
|
rows, err := db.Query(ctx, knowledgeScopedColumnsSQL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("读取知识域表清单失败: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
unclassified := make([]string, 0, 4)
|
||||||
|
columnsByTable := map[string]map[string]bool{}
|
||||||
|
for rows.Next() {
|
||||||
|
var table string
|
||||||
|
var columns []string
|
||||||
|
if err := rows.Scan(&table, &columns); err != nil {
|
||||||
|
return nil, fmt.Errorf("解析知识域表清单失败: %w", err)
|
||||||
|
}
|
||||||
|
if _, ok := profile.RelatedTableClass(table); ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
set := make(map[string]bool, len(columns))
|
||||||
|
for _, column := range columns {
|
||||||
|
set[column] = true
|
||||||
|
}
|
||||||
|
columnsByTable[table] = set
|
||||||
|
unclassified = append(unclassified, table)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("遍历知识域表清单失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
blocked := make([]UndeclaredKBTable, 0, len(unclassified))
|
||||||
|
warnings := make([]string, 0, len(unclassified))
|
||||||
|
for _, table := range unclassified {
|
||||||
|
count, ok := scopedKnowledgeTableCountSQL(table, columnsByTable[table], identity)
|
||||||
|
if !ok {
|
||||||
|
// 候选表却没有可用的范围列:无法证明"本次范围内有没有数据",
|
||||||
|
// 只能按有数据处理,避免把范围外的表误放行。
|
||||||
|
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: -1})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
if err := db.QueryRow(ctx, count.sql, count.args...).Scan(&total); err != nil {
|
||||||
|
return nil, fmt.Errorf("统计未声明表 %s 失败: %w", table, err)
|
||||||
|
}
|
||||||
|
if total > 0 {
|
||||||
|
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: total})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
warnings = append(warnings, fmt.Sprintf(
|
||||||
|
"%s: 未分类表 %q 在本次范围内为空,已放行;请补 profile 关联表分类", ReleaseUndeclaredKBTableCode, table))
|
||||||
|
}
|
||||||
|
sort.Slice(blocked, func(i, j int) bool { return blocked[i].Table < blocked[j].Table })
|
||||||
|
sort.Strings(warnings)
|
||||||
|
if len(blocked) > 0 {
|
||||||
|
return nil, &UndeclaredKBTableError{Tables: blocked}
|
||||||
|
}
|
||||||
|
return warnings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type scopedCount struct {
|
||||||
|
sql string
|
||||||
|
args []any
|
||||||
|
}
|
||||||
|
|
||||||
|
// scopedKnowledgeTableCountSQL 按"这张表实际有的范围列"构造计数:有
|
||||||
|
// knowledge_base_id 优先按 tenant+kb;有 kb_id 按 tenant+kb_id;只有
|
||||||
|
// knowledge_id 时走 knowledges 子查询。没有 tenant_id 的表(如 kb_shares)
|
||||||
|
// 只能按知识库身份过滤,不能硬塞一个不存在的列。
|
||||||
|
func scopedKnowledgeTableCountSQL(table string, columns map[string]bool,
|
||||||
|
identity PostgresIdentity) (scopedCount, bool) {
|
||||||
|
quoted := pgx.Identifier{"public", table}.Sanitize()
|
||||||
|
hasTenant := columns["tenant_id"]
|
||||||
|
var where string
|
||||||
|
var args []any
|
||||||
|
switch {
|
||||||
|
case columns["knowledge_base_id"]:
|
||||||
|
if hasTenant {
|
||||||
|
where, args = "tenant_id=$1 AND knowledge_base_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||||
|
} else {
|
||||||
|
where, args = "knowledge_base_id=$1", []any{identity.KnowledgeBaseID}
|
||||||
|
}
|
||||||
|
case columns["kb_id"]:
|
||||||
|
if hasTenant {
|
||||||
|
where, args = "tenant_id=$1 AND kb_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||||
|
} else {
|
||||||
|
where, args = "kb_id=$1", []any{identity.KnowledgeBaseID}
|
||||||
|
}
|
||||||
|
case columns["knowledge_id"]:
|
||||||
|
where = "knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)"
|
||||||
|
args = []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||||
|
default:
|
||||||
|
return scopedCount{}, false
|
||||||
|
}
|
||||||
|
return scopedCount{sql: "/* knowledge-table-gate-count */ SELECT count(*) FROM " + quoted + " WHERE " + where, args: args}, true
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
package v071
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
|
||||||
|
"knowledge-governance/internal/libraryprofile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// gateRows 回答门禁的 information_schema 探测:table → 列集合。
|
||||||
|
type gateRows struct {
|
||||||
|
tables [][2]any
|
||||||
|
index int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *gateRows) Close() {}
|
||||||
|
func (r *gateRows) Err() error { return nil }
|
||||||
|
func (r *gateRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} }
|
||||||
|
func (r *gateRows) FieldDescriptions() []pgconn.FieldDescription { return nil }
|
||||||
|
func (r *gateRows) RawValues() [][]byte { return nil }
|
||||||
|
func (r *gateRows) Conn() *pgx.Conn { return nil }
|
||||||
|
func (r *gateRows) Next() bool {
|
||||||
|
if r.index >= len(r.tables) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
r.index++
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func (r *gateRows) Scan(dest ...any) error {
|
||||||
|
*dest[0].(*string) = r.tables[r.index-1][0].(string)
|
||||||
|
*dest[1].(*[]string) = r.tables[r.index-1][1].([]string)
|
||||||
|
_ = dest
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *gateRows) Values() ([]any, error) { return nil, nil }
|
||||||
|
|
||||||
|
type gateCountRow struct{ value *int64 }
|
||||||
|
|
||||||
|
func (r gateCountRow) Scan(dest ...any) error { *dest[0].(*int64) = *r.value; return nil }
|
||||||
|
|
||||||
|
// gateDB 只实现门禁需要的两个入口:探测表/列 + 按表计数。
|
||||||
|
type gateDB struct {
|
||||||
|
candidates []struct {
|
||||||
|
table string
|
||||||
|
columns []string
|
||||||
|
}
|
||||||
|
counts map[string]int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d gateDB) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
|
||||||
|
if !strings.Contains(sql, "knowledge-table-gate") {
|
||||||
|
return nil, errors.New("unexpected query: " + sql)
|
||||||
|
}
|
||||||
|
rows := &gateRows{}
|
||||||
|
for _, candidate := range d.candidates {
|
||||||
|
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
|
||||||
|
}
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d gateDB) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
|
||||||
|
for table, count := range d.counts {
|
||||||
|
if strings.Contains(sql, `"public"."`+table+`"`) {
|
||||||
|
value := count
|
||||||
|
return gateCountRow{value: &value}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return gateCountRow{value: new(int64)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gateProfile(t *testing.T) libraryprofile.Profile {
|
||||||
|
t.Helper()
|
||||||
|
profile, err := libraryprofile.For(libraryprofile.V091Version)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return profile
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredTableGateRejectsUnclassifiedTableWithRows(t *testing.T) {
|
||||||
|
profile := gateProfile(t)
|
||||||
|
db := gateDB{
|
||||||
|
candidates: []struct {
|
||||||
|
table string
|
||||||
|
columns []string
|
||||||
|
}{
|
||||||
|
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
|
||||||
|
},
|
||||||
|
counts: map[string]int64{"mystery_kb_table": 7},
|
||||||
|
}
|
||||||
|
_, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||||
|
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||||
|
var blocked *UndeclaredKBTableError
|
||||||
|
if !errors.As(err, &blocked) {
|
||||||
|
t.Fatalf("unclassified table with rows must be refused, got %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) ||
|
||||||
|
!strings.Contains(err.Error(), "mystery_kb_table") || !strings.Contains(err.Error(), "7 行") {
|
||||||
|
t.Fatalf("error must name code/table/rows, got %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "不可重试") {
|
||||||
|
t.Fatalf("error must state non-retryable, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredTableGateAllowsEmptyUnclassifiedTableWithWarning(t *testing.T) {
|
||||||
|
profile := gateProfile(t)
|
||||||
|
db := gateDB{
|
||||||
|
candidates: []struct {
|
||||||
|
table string
|
||||||
|
columns []string
|
||||||
|
}{
|
||||||
|
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
|
||||||
|
},
|
||||||
|
counts: map[string]int64{"mystery_kb_table": 0},
|
||||||
|
}
|
||||||
|
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||||
|
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("empty unclassified table must pass: %v", err)
|
||||||
|
}
|
||||||
|
if len(warnings) != 1 || !strings.Contains(warnings[0], "mystery_kb_table") ||
|
||||||
|
!strings.Contains(warnings[0], ReleaseUndeclaredKBTableCode) {
|
||||||
|
t.Fatalf("expected one persisted warning naming the table, got %v", warnings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredTableGateAllowsClassifiedTables(t *testing.T) {
|
||||||
|
profile := gateProfile(t)
|
||||||
|
db := gateDB{
|
||||||
|
candidates: []struct {
|
||||||
|
table string
|
||||||
|
columns []string
|
||||||
|
}{
|
||||||
|
{"chunk_images", []string{"knowledge_base_id", "knowledge_id"}},
|
||||||
|
{"sessions", []string{"knowledge_base_id", "tenant_id"}},
|
||||||
|
{"messages", []string{"knowledge_id", "tenant_id"}},
|
||||||
|
{"data_sources", []string{"knowledge_base_id"}},
|
||||||
|
{"chunks", []string{"knowledge_base_id", "knowledge_id"}},
|
||||||
|
},
|
||||||
|
counts: map[string]int64{"sessions": 27, "messages": 90, "chunk_images": 3},
|
||||||
|
}
|
||||||
|
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||||
|
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||||
|
if err != nil || len(warnings) != 0 {
|
||||||
|
t.Fatalf("derived/excluded/copied tables must pass silently, got %v/%v", warnings, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredTableGateRefusesProfileWithoutClassification(t *testing.T) {
|
||||||
|
_, err := verifyDeclaredKnowledgeTables(context.Background(), gateDB{},
|
||||||
|
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, libraryprofile.Profile{Name: "bare"})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "分类") {
|
||||||
|
t.Fatalf("a profile without classification must not skip the gate, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScopedKnowledgeTableCountSQLUsesExistingColumns(t *testing.T) {
|
||||||
|
identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
columns map[string]bool
|
||||||
|
wantSQL string
|
||||||
|
want []any
|
||||||
|
}{
|
||||||
|
{"kb+tenant", map[string]bool{"knowledge_base_id": true, "tenant_id": true},
|
||||||
|
`tenant_id=$1 AND knowledge_base_id=$2`, []any{uint64(10000), "kb-safe"}},
|
||||||
|
{"kb without tenant", map[string]bool{"knowledge_base_id": true},
|
||||||
|
`knowledge_base_id=$1`, []any{"kb-safe"}},
|
||||||
|
{"kb_id+tenant", map[string]bool{"kb_id": true, "tenant_id": true},
|
||||||
|
`tenant_id=$1 AND kb_id=$2`, []any{uint64(10000), "kb-safe"}},
|
||||||
|
{"kb_id without tenant", map[string]bool{"kb_id": true},
|
||||||
|
`kb_id=$1`, []any{"kb-safe"}},
|
||||||
|
{"knowledge only", map[string]bool{"knowledge_id": true},
|
||||||
|
`knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`,
|
||||||
|
[]any{uint64(10000), "kb-safe"}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
count, ok := scopedKnowledgeTableCountSQL("t", tc.columns, identity)
|
||||||
|
if !ok || !strings.Contains(count.sql, tc.wantSQL) {
|
||||||
|
t.Fatalf("sql=%q ok=%v, want fragment %q", count.sql, ok, tc.wantSQL)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(count.args, tc.want) {
|
||||||
|
t.Fatalf("args=%v, want %v", count.args, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if _, ok := scopedKnowledgeTableCountSQL("t", map[string]bool{"id": true}, identity); ok {
|
||||||
|
t.Fatal("a table without any scope column must not be treated as countable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出路径必须真的执行门禁:候选表有数据时在封存前就失败。
|
||||||
|
type gateExportDB struct {
|
||||||
|
candidates []struct {
|
||||||
|
table string
|
||||||
|
columns []string
|
||||||
|
}
|
||||||
|
counts map[string]int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d gateExportDB) BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error) {
|
||||||
|
return &gateExportTx{db: d}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type gateExportTx struct {
|
||||||
|
pgx.Tx
|
||||||
|
db gateExportDB
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tx *gateExportTx) Commit(context.Context) error { return nil }
|
||||||
|
func (tx *gateExportTx) Rollback(context.Context) error { return nil }
|
||||||
|
func (tx *gateExportTx) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
|
||||||
|
if strings.Contains(sql, "schema_migrations") {
|
||||||
|
return gateSchemaRow{}
|
||||||
|
}
|
||||||
|
for table, count := range tx.db.counts {
|
||||||
|
if strings.Contains(sql, `"public"."`+table+`"`) {
|
||||||
|
value := count
|
||||||
|
return gateCountRow{value: &value}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return gateCountRow{value: new(int64)}
|
||||||
|
}
|
||||||
|
func (tx *gateExportTx) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
|
||||||
|
if strings.Contains(sql, "knowledge-table-gate") {
|
||||||
|
rows := &gateRows{}
|
||||||
|
for _, candidate := range tx.db.candidates {
|
||||||
|
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
|
||||||
|
}
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
|
return legacySchemaProbeRows(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type gateSchemaRow struct{}
|
||||||
|
|
||||||
|
func (gateSchemaRow) Scan(dest ...any) error {
|
||||||
|
*dest[0].(*int) = 74
|
||||||
|
*dest[1].(*bool) = false
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExportRunsDeclaredTableGateBeforeSealing(t *testing.T) {
|
||||||
|
db := gateExportDB{candidates: []struct {
|
||||||
|
table string
|
||||||
|
columns []string
|
||||||
|
}{{"mystery_kb_table", []string{"knowledge_base_id", "tenant_id"}}},
|
||||||
|
counts: map[string]int64{"mystery_kb_table": 2}}
|
||||||
|
_, err := ExportLibrary(context.Background(), db,
|
||||||
|
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) {
|
||||||
|
t.Fatalf("export must fail closed on undeclared table data, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -34,6 +38,17 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return PostgresSnapshot{}, err
|
return PostgresSnapshot{}, err
|
||||||
}
|
}
|
||||||
|
// 漏表门禁:在同一个只读快照事务里做,避免"检查完又长出未声明表"。
|
||||||
|
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx, identity, profile.Profile)
|
||||||
|
if err != nil {
|
||||||
|
return PostgresSnapshot{}, err
|
||||||
|
}
|
||||||
|
for _, warning := range gateWarnings {
|
||||||
|
log.Printf("library export declared-table gate: %s", warning)
|
||||||
|
}
|
||||||
|
if err := verifyRevisionParentClosure(ctx, tx, identity, profile); err != nil {
|
||||||
|
return PostgresSnapshot{}, err
|
||||||
|
}
|
||||||
var graph bool
|
var graph bool
|
||||||
if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil {
|
if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil {
|
||||||
return PostgresSnapshot{}, errors.New("source library unavailable")
|
return PostgresSnapshot{}, errors.New("source library unavailable")
|
||||||
@@ -85,7 +100,7 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
|||||||
// The latter includes Wiki manual pages, which document bundles used to miss.
|
// The latter includes Wiki manual pages, which document bundles used to miss.
|
||||||
var bodies []json.RawMessage
|
var bodies []json.RawMessage
|
||||||
for _, table := range snapshot.Tables {
|
for _, table := range snapshot.Tables {
|
||||||
if table.Name == "resource_bindings" || table.Name == "knowledge_tag_relations" {
|
if !libraryResourceBodyTable(table.Name) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
bodies = append(bodies, table.Rows...)
|
bodies = append(bodies, table.Rows...)
|
||||||
@@ -147,13 +162,62 @@ const librarySettlementSQL = `SELECT
|
|||||||
(SELECT count(*) FROM task_pending_ops WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)))),
|
(SELECT count(*) FROM task_pending_ops WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)))),
|
||||||
(SELECT count(*) FROM task_dead_letters WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2))))`
|
(SELECT count(*) FROM task_dead_letters WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2))))`
|
||||||
|
|
||||||
|
// verifyRevisionParentClosure 只拒绝"父行完全不存在/父关系错乱"的修订行;
|
||||||
|
// 父行被软删的修订属于本次范围外(整库只发活跃内容),随父行一起不导出。
|
||||||
|
// 这与"历史日志按展示事实保留"不同:修订行的 chunk_id/page_id 是结构引用,
|
||||||
|
// 真缺失只可能是数据异常,不能静默跳过。
|
||||||
|
func verifyRevisionParentClosure(ctx context.Context, db schemaProbeDB, identity PostgresIdentity, profile SchemaProfile) error {
|
||||||
|
checks := make([]string, 0, 3)
|
||||||
|
labels := make([]string, 0, 3)
|
||||||
|
if profile.HasTable("chunk_revisions") {
|
||||||
|
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id))`)
|
||||||
|
labels = append(labels, "chunk_revisions 缺少 chunk 父行")
|
||||||
|
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
|
||||||
|
AND EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND (c.knowledge_id<>r.knowledge_id OR c.knowledge_base_id<>r.knowledge_base_id)))`)
|
||||||
|
labels = append(labels, "chunk_revisions 与父 chunk 的 knowledge_id/knowledge_base_id 不一致")
|
||||||
|
}
|
||||||
|
if profile.HasTable("wiki_page_revisions") {
|
||||||
|
checks = append(checks, `(SELECT count(*) FROM wiki_page_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM wiki_pages p WHERE p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id))`)
|
||||||
|
labels = append(labels, "wiki_page_revisions 缺少 page 父行")
|
||||||
|
}
|
||||||
|
if len(checks) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var counts = make([]int64, len(checks))
|
||||||
|
dest := make([]any, len(checks))
|
||||||
|
for index := range counts {
|
||||||
|
dest[index] = &counts[index]
|
||||||
|
}
|
||||||
|
if err := db.QueryRow(ctx, "/* library-revision-closure */ SELECT "+strings.Join(checks, ", "),
|
||||||
|
identity.TenantID, identity.KnowledgeBaseID).Scan(dest...); err != nil {
|
||||||
|
return fmt.Errorf("读取编辑历史父关系失败: %w", err)
|
||||||
|
}
|
||||||
|
problems := make([]string, 0, len(counts))
|
||||||
|
for index, count := range counts {
|
||||||
|
if count > 0 {
|
||||||
|
problems = append(problems, fmt.Sprintf("%s:%d 行", labels[index], count))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return fmt.Errorf("编辑历史存在无法解析的父引用,拒绝整库发布:%v", problems)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
var libraryContentQueries = []struct{ name, sql string }{
|
var libraryContentQueries = []struct{ name, sql string }{
|
||||||
{"knowledges", `SELECT to_jsonb(k) FROM knowledges k WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL ORDER BY k.id`},
|
{"knowledges", `SELECT to_jsonb(k) FROM knowledges k WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL ORDER BY k.id`},
|
||||||
{"chunks", `SELECT to_jsonb(c) FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND c.deleted_at IS NULL ORDER BY c.id`},
|
{"chunks", `SELECT to_jsonb(c) FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND c.deleted_at IS NULL ORDER BY c.id`},
|
||||||
|
// 编辑历史:只随活跃父行发布。父行被软删(不在本次范围)时不搬它的历史;
|
||||||
|
// 父行完全缺失属于数据异常,由 verifyRevisionParentClosure 拒绝,不静默跳过。
|
||||||
|
{"chunk_revisions", `SELECT to_jsonb(r) FROM chunk_revisions r JOIN chunks c ON c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND c.knowledge_base_id=r.knowledge_base_id JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND r.knowledge_id=c.knowledge_id AND c.deleted_at IS NULL AND k.deleted_at IS NULL ORDER BY r.id`},
|
||||||
{"knowledge_tags", `SELECT to_jsonb(t) FROM knowledge_tags t WHERE t.tenant_id=$1 AND t.knowledge_base_id=$2 AND t.deleted_at IS NULL ORDER BY t.id`},
|
{"knowledge_tags", `SELECT to_jsonb(t) FROM knowledge_tags t WHERE t.tenant_id=$1 AND t.knowledge_base_id=$2 AND t.deleted_at IS NULL ORDER BY t.id`},
|
||||||
{"knowledge_tag_relations", `SELECT to_jsonb(r) FROM knowledge_tag_relations r JOIN knowledges k ON k.id=r.knowledge_id JOIN knowledge_tags t ON t.id=r.tag_id AND t.tenant_id=k.tenant_id AND t.knowledge_base_id=k.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY r.knowledge_id,r.tag_id`},
|
{"knowledge_tag_relations", `SELECT to_jsonb(r) FROM knowledge_tag_relations r JOIN knowledges k ON k.id=r.knowledge_id JOIN knowledge_tags t ON t.id=r.tag_id AND t.tenant_id=k.tenant_id AND t.knowledge_base_id=k.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY r.knowledge_id,r.tag_id`},
|
||||||
{"resource_bindings", `SELECT to_jsonb(b) FROM resource_bindings b WHERE b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))) ORDER BY b.id`},
|
{"resource_bindings", `SELECT to_jsonb(b) FROM resource_bindings b WHERE b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))) ORDER BY b.id`},
|
||||||
{"wiki_pages", `SELECT to_jsonb(w) FROM wiki_pages w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
{"wiki_pages", `SELECT to_jsonb(w) FROM wiki_pages w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
||||||
|
// 编辑历史:与 chunk_revisions 同一规则(活跃父行 + 真悬挂由守卫拒绝)。
|
||||||
|
{"wiki_page_revisions", `SELECT to_jsonb(r) FROM wiki_page_revisions r JOIN wiki_pages p ON p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND p.deleted_at IS NULL ORDER BY r.id`},
|
||||||
{"wiki_folders", `SELECT to_jsonb(w) FROM wiki_folders w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
{"wiki_folders", `SELECT to_jsonb(w) FROM wiki_folders w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
||||||
{"wiki_page_issues", `SELECT to_jsonb(w) FROM wiki_page_issues w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
{"wiki_page_issues", `SELECT to_jsonb(w) FROM wiki_page_issues w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
||||||
{"wiki_log_entries", `SELECT to_jsonb(w) FROM wiki_log_entries w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 ORDER BY w.id`},
|
{"wiki_log_entries", `SELECT to_jsonb(w) FROM wiki_log_entries w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 ORDER BY w.id`},
|
||||||
|
|||||||
@@ -103,6 +103,11 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row
|
|||||||
if d.queryError {
|
if d.queryError {
|
||||||
return nil, errors.New("fixture failure")
|
return nil, errors.New("fixture failure")
|
||||||
}
|
}
|
||||||
|
// 漏表门禁也查 information_schema,但回答形状是(表,列集合);与能力探测分开打桩,
|
||||||
|
// 否则会被当成两列结果扫描。74 夹具没有任何未分类的知识域表。
|
||||||
|
if strings.Contains(q, "knowledge-table-gate") {
|
||||||
|
return &jsonRows{}, nil
|
||||||
|
}
|
||||||
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
|
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
|
||||||
if strings.Contains(q, "information_schema.columns") {
|
if strings.Contains(q, "information_schema.columns") {
|
||||||
return legacySchemaProbeRows(), nil
|
return legacySchemaProbeRows(), nil
|
||||||
|
|||||||
@@ -31,6 +31,10 @@ var migrationIdentityContracts = map[string]rowIdentityContract{
|
|||||||
"wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"},
|
"wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||||
"wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"},
|
"wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||||
"wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"},
|
"wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||||
|
// 编辑历史:稳定字符串身份;id 是它自己的身份,chunk_id/page_id/knowledge_id
|
||||||
|
// 是引用(由 remapRow 显式映射)。两表都没有 deleted_at。
|
||||||
|
"chunk_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||||
|
"wiki_page_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -344,12 +345,16 @@ func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string)
|
|||||||
if name == "resources" {
|
if name == "resources" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// 只需正文表与绑定表;修订历史按 Q2=B 不参与资源发现,不为它做整表扫描。
|
||||||
|
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", fmt.Errorf("读取生产 %s 失败", table)
|
return 0, "", fmt.Errorf("读取生产 %s 失败", table)
|
||||||
}
|
}
|
||||||
if name != "resource_bindings" && name != "knowledge_tag_relations" {
|
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
|
||||||
bodies = append(bodies, items...)
|
bodies = append(bodies, items...)
|
||||||
}
|
}
|
||||||
if name == "resource_bindings" {
|
if name == "resource_bindings" {
|
||||||
@@ -479,6 +484,16 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra
|
|||||||
return errors.New("开启生产事务失败")
|
return errors.New("开启生产事务失败")
|
||||||
}
|
}
|
||||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||||
|
// 漏表门禁的最终判定:在写事务内、任何 DELETE 之前。放在事务外检查会留下
|
||||||
|
// "查完到写前"的窗口,未声明表的数据可能在这段时间被写进来。
|
||||||
|
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx,
|
||||||
|
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, warning := range gateWarnings {
|
||||||
|
log.Printf("library import declared-table gate: %s", warning)
|
||||||
|
}
|
||||||
for index := len(t.tables) - 1; index >= 0; index-- {
|
for index := len(t.tables) - 1; index >= 0; index-- {
|
||||||
table := t.tables[index]
|
table := t.tables[index]
|
||||||
if _, ok := parts[table]; !ok {
|
if _, ok := parts[table]; !ok {
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ func TestV090ProductionTargetPublishIsolated(t *testing.T) {
|
|||||||
t.Fatalf("fixture %s %s => %d, want %d", method, path, response.StatusCode, want)
|
t.Fatalf("fixture %s %s => %d, want %d", method, path, response.StatusCode, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
call("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200)
|
call("PUT", "/"+index, `{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200)
|
||||||
defer func() {
|
defer func() {
|
||||||
call("DELETE", "/"+index, "", 200)
|
call("DELETE", "/"+index, "", 200)
|
||||||
call("HEAD", "/"+index, "", 404)
|
call("HEAD", "/"+index, "", 404)
|
||||||
@@ -375,7 +375,7 @@ func v090PublishIndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA stri
|
|||||||
t.Fatalf("decode chunk: %v", err)
|
t.Fatalf("decode chunk: %v", err)
|
||||||
}
|
}
|
||||||
source, err := json.Marshal(map[string]any{
|
source, err := json.Marshal(map[string]any{
|
||||||
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
|
"chunk_id": chunk.ID,
|
||||||
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
||||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||||
"embedding": []float64{0.1, 0.2},
|
"embedding": []float64{0.1, 0.2},
|
||||||
|
|||||||
@@ -57,6 +57,10 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
|||||||
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
|
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
|
||||||
source.Table("chunks").RowCount, source.Table("knowledges").RowCount)
|
source.Table("chunks").RowCount, source.Table("knowledges").RowCount)
|
||||||
}
|
}
|
||||||
|
if source.Table("chunk_revisions").RowCount != 1 || source.Table("wiki_page_revisions").RowCount != 1 {
|
||||||
|
t.Fatalf("editing history must be exported: chunk_revisions=%d wiki_page_revisions=%d",
|
||||||
|
source.Table("chunk_revisions").RowCount, source.Table("wiki_page_revisions").RowCount)
|
||||||
|
}
|
||||||
|
|
||||||
es := v090IndexSnapshot(t, source, mappingSHA)
|
es := v090IndexSnapshot(t, source, mappingSHA)
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
@@ -90,6 +94,13 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
|||||||
t.Fatal("0.9.0 archive must not contain a wiki_log_entries part")
|
t.Fatal("0.9.0 archive must not contain a wiki_log_entries part")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
seenParts := map[string]bool{}
|
||||||
|
for _, part := range manifest.Parts {
|
||||||
|
seenParts[part.Kind+"/"+part.Name] = true
|
||||||
|
}
|
||||||
|
if !seenParts["database/chunk_revisions"] || !seenParts["wiki/wiki_page_revisions"] {
|
||||||
|
t.Fatalf("revision parts must be archived: %v", seenParts)
|
||||||
|
}
|
||||||
|
|
||||||
dst := v090Pool(t, "KG_V090_TARGET_DSN")
|
dst := v090Pool(t, "KG_V090_TARGET_DSN")
|
||||||
if err := seedV090Binding(t, ctx, dst); err != nil {
|
if err := seedV090Binding(t, ctx, dst); err != nil {
|
||||||
@@ -100,14 +111,21 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge}
|
document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge}
|
||||||
if err := importer.Replace(ctx, document, source); err != nil {
|
// 文档级 Replace 只写单文档相关表;编辑历史走整库 Apply(0.9.0 发布目标用例覆盖)。
|
||||||
|
documentSource := withoutRevisionTables(source)
|
||||||
|
if err := importer.Replace(ctx, document, documentSource); err != nil {
|
||||||
t.Fatalf("import 0.9.0 snapshot: %v", err)
|
t.Fatalf("import 0.9.0 snapshot: %v", err)
|
||||||
}
|
}
|
||||||
reloaded, err := ExportLibrary(ctx, dst, identity)
|
reloaded, err := ExportLibrary(ctx, dst, identity)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("re-export imported library: %v", err)
|
t.Fatalf("re-export imported library: %v", err)
|
||||||
}
|
}
|
||||||
compareSnapshotContent(t, source, reloaded)
|
compareSnapshotContent(t, documentSource, withoutRevisionTables(reloaded))
|
||||||
|
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
|
||||||
|
if reloaded.Table(table).RowCount != 0 {
|
||||||
|
t.Fatalf("document-level import must not invent %s rows", table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。
|
// 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。
|
||||||
var defaults int
|
var defaults int
|
||||||
@@ -130,7 +148,7 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
|
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
|
||||||
crossVersion := source
|
crossVersion := documentSource
|
||||||
crossVersion.SchemaVersion = 74
|
crossVersion.SchemaVersion = 74
|
||||||
crossVersion.Profile = "v071"
|
crossVersion.Profile = "v071"
|
||||||
err = importer.Replace(ctx, document, crossVersion)
|
err = importer.Replace(ctx, document, crossVersion)
|
||||||
@@ -139,6 +157,18 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func withoutRevisionTables(snapshot PostgresSnapshot) PostgresSnapshot {
|
||||||
|
tables := make([]TableSnapshot, 0, len(snapshot.Tables))
|
||||||
|
for _, table := range snapshot.Tables {
|
||||||
|
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tables = append(tables, table)
|
||||||
|
}
|
||||||
|
snapshot.Tables = tables
|
||||||
|
return snapshot
|
||||||
|
}
|
||||||
|
|
||||||
// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。
|
// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。
|
||||||
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
|
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
|
||||||
func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
||||||
@@ -147,6 +177,9 @@ func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
|||||||
t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables))
|
t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables))
|
||||||
}
|
}
|
||||||
for _, table := range source.Tables {
|
for _, table := range source.Tables {
|
||||||
|
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
want := tableDigests(t, table.Name, table.Rows)
|
want := tableDigests(t, table.Name, table.Rows)
|
||||||
got := tableDigests(t, table.Name, target.Table(table.Name).Rows)
|
got := tableDigests(t, table.Name, target.Table(table.Name).Rows)
|
||||||
if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) {
|
if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) {
|
||||||
|
|||||||
@@ -9,13 +9,26 @@ import (
|
|||||||
"knowledge-governance/internal/libraryrelease"
|
"knowledge-governance/internal/libraryrelease"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// libraryResourceBodyTable 报告该表是否参与"正文引用资源"的发现与作用域。
|
||||||
|
//
|
||||||
|
// 编辑历史按人类裁定(Q2=B)原样保留 resource:// 文本,不参与资源发现:历史版本
|
||||||
|
// 引用的对象可能早已删除,不能让它决定本次发布必须携带哪些对象。资源发现、目标
|
||||||
|
// 资源作用域、恢复保护三处必须用同一个判定,否则导出与校验会各算一套集合。
|
||||||
|
func libraryResourceBodyTable(table string) bool {
|
||||||
|
switch table {
|
||||||
|
case "resources", "resource_bindings", "knowledge_tag_relations", "chunk_revisions", "wiki_page_revisions":
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// Keep capture/verification and deletion protection on the same set of bodies.
|
// Keep capture/verification and deletion protection on the same set of bodies.
|
||||||
// predicate is an internal SQL fragment, never caller-supplied content; tables comes
|
// predicate is an internal SQL fragment, never caller-supplied content; tables comes
|
||||||
// from the resolved schema profile (0.9.0 has no wiki_log_entries to scan).
|
// from the resolved schema profile (0.9.0 has no wiki_log_entries to scan).
|
||||||
func libraryResourceBodyReferenceSQL(tables []string, predicate string) string {
|
func libraryResourceBodyReferenceSQL(tables []string, predicate string) string {
|
||||||
queries := []string{}
|
queries := []string{}
|
||||||
for _, table := range tables {
|
for _, table := range tables {
|
||||||
if table == "resources" || table == "resource_bindings" || table == "knowledge_tag_relations" {
|
if !libraryResourceBodyTable(table) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
queries = append(queries, fmt.Sprintf(`SELECT 1 FROM %s c WHERE (%s) AND coalesce(resources.handle,'')<>'' AND position('resource://'||resources.handle IN to_jsonb(c)::text)>0`, table, predicate))
|
queries = append(queries, fmt.Sprintf(`SELECT 1 FROM %s c WHERE (%s) AND coalesce(resources.handle,'')<>'' AND position('resource://'||resources.handle IN to_jsonb(c)::text)>0`, table, predicate))
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package v071
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func revisionMapper() *targetIDMapper {
|
||||||
|
mapper := newTargetIDMapper(10001, "kb-target", nil)
|
||||||
|
for table, ids := range map[string][]string{
|
||||||
|
"knowledges": {"doc-src"},
|
||||||
|
"chunks": {"chunk-src"},
|
||||||
|
"wiki_pages": {"page-src"},
|
||||||
|
"chunk_revisions": {"crev-src"},
|
||||||
|
"wiki_page_revisions": {"wrev-src"},
|
||||||
|
} {
|
||||||
|
for _, id := range ids {
|
||||||
|
mapper.registerSourceID(table, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mapper
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionRowsUseTheSameScopeAndIdentityMapping(t *testing.T) {
|
||||||
|
mapper := revisionMapper()
|
||||||
|
chunkRevision := map[string]json.RawMessage{
|
||||||
|
"id": json.RawMessage(`"crev-src"`),
|
||||||
|
"knowledge_id": json.RawMessage(`"doc-src"`),
|
||||||
|
"chunk_id": json.RawMessage(`"chunk-src"`),
|
||||||
|
"revision": json.RawMessage(`3`),
|
||||||
|
"content": json.RawMessage(`"edit history text"`),
|
||||||
|
"editor_id": json.RawMessage(`"user-9"`),
|
||||||
|
"knowledge_base_id": json.RawMessage(`"kb-source"`),
|
||||||
|
}
|
||||||
|
if err := mapper.remapRow("chunk_revisions", chunkRevision); err != nil {
|
||||||
|
t.Fatalf("chunk revision mapping: %v", err)
|
||||||
|
}
|
||||||
|
if string(chunkRevision["id"]) != `"`+mapper.mapID("chunk_revisions", "crev-src")+`"` {
|
||||||
|
t.Fatal("revision id must be target-mapped")
|
||||||
|
}
|
||||||
|
if string(chunkRevision["chunk_id"]) != `"`+mapper.mapID("chunks", "chunk-src")+`"` {
|
||||||
|
t.Fatal("chunk_id must map to the target chunk identity")
|
||||||
|
}
|
||||||
|
if string(chunkRevision["knowledge_id"]) != `"`+mapper.mapID("knowledges", "doc-src")+`"` {
|
||||||
|
t.Fatal("knowledge_id must map to the target knowledge identity")
|
||||||
|
}
|
||||||
|
// editor_id 是用户身份,原样保留(目标查不到显示未知编辑者)。
|
||||||
|
if string(chunkRevision["editor_id"]) != `"user-9"` {
|
||||||
|
t.Fatal("editor_id must be preserved")
|
||||||
|
}
|
||||||
|
|
||||||
|
pageRevision := map[string]json.RawMessage{
|
||||||
|
"id": json.RawMessage(`"wrev-src"`),
|
||||||
|
"page_id": json.RawMessage(`"page-src"`),
|
||||||
|
"slug": json.RawMessage(`"legacy-slug"`),
|
||||||
|
"version": json.RawMessage(`2`),
|
||||||
|
"content": json.RawMessage(`"wiki history"`),
|
||||||
|
"knowledge_base_id": json.RawMessage(`"kb-source"`),
|
||||||
|
}
|
||||||
|
if err := mapper.remapRow("wiki_page_revisions", pageRevision); err != nil {
|
||||||
|
t.Fatalf("wiki page revision mapping: %v", err)
|
||||||
|
}
|
||||||
|
if string(pageRevision["page_id"]) != `"`+mapper.mapID("wiki_pages", "page-src")+`"` {
|
||||||
|
t.Fatal("page_id must map to the target page identity")
|
||||||
|
}
|
||||||
|
if string(pageRevision["slug"]) != `"legacy-slug"` {
|
||||||
|
t.Fatal("slug is content, not identity; it must be preserved")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionDanglingReferencesAreRefused(t *testing.T) {
|
||||||
|
mapper := revisionMapper()
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
row map[string]json.RawMessage
|
||||||
|
}{
|
||||||
|
{"unknown chunk", map[string]json.RawMessage{
|
||||||
|
"id": json.RawMessage(`"crev-unknown"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||||
|
"chunk_id": json.RawMessage(`"chunk-other"`), "revision": json.RawMessage(`1`),
|
||||||
|
}},
|
||||||
|
{"unknown page", map[string]json.RawMessage{
|
||||||
|
"id": json.RawMessage(`"wrev-unknown"`), "page_id": json.RawMessage(`"page-other"`),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
table := "chunk_revisions"
|
||||||
|
if tc.name == "unknown page" {
|
||||||
|
table = "wiki_page_revisions"
|
||||||
|
}
|
||||||
|
err := mapper.remapRow(table, tc.row)
|
||||||
|
if !errors.Is(err, errUnmappedTargetReference) || !strings.Contains(err.Error(), "unmapped") {
|
||||||
|
t.Fatalf("dangling reference must be refused, got %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionUniqueIndexKeysStayUniqueAfterMapping(t *testing.T) {
|
||||||
|
mapper := revisionMapper()
|
||||||
|
// 同一 chunk 的两个 revision:chunk_id 映射后仍相同,revision 仍是 1/2,
|
||||||
|
// 因此 (chunk_id, revision) 唯一性不会被映射破坏。
|
||||||
|
rows := []map[string]json.RawMessage{
|
||||||
|
{"id": json.RawMessage(`"crev-src"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||||
|
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`1`)},
|
||||||
|
{"id": json.RawMessage(`"crev-src2"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||||
|
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`2`)},
|
||||||
|
}
|
||||||
|
mapper.registerSourceID("chunk_revisions", "crev-src2")
|
||||||
|
mapped := map[string]bool{}
|
||||||
|
for _, row := range rows {
|
||||||
|
if err := mapper.remapRow("chunk_revisions", row); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
key := string(row["chunk_id"]) + "/" + string(row["revision"])
|
||||||
|
if mapped[key] {
|
||||||
|
t.Fatalf("mapped unique key collided: %s", key)
|
||||||
|
}
|
||||||
|
mapped[key] = true
|
||||||
|
}
|
||||||
|
if len(mapped) != 2 {
|
||||||
|
t.Fatal("both revision keys must remain distinct")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionTablesAreDeletedBeforeParents(t *testing.T) {
|
||||||
|
position := map[string]int{}
|
||||||
|
for index, table := range jobCreatedRowDeleteOrder {
|
||||||
|
position[table] = index
|
||||||
|
}
|
||||||
|
for _, child := range []string{"wiki_page_revisions", "chunk_revisions"} {
|
||||||
|
if _, ok := position[child]; !ok {
|
||||||
|
t.Fatalf("%s missing from recovery delete order", child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if position["chunk_revisions"] > position["chunks"] {
|
||||||
|
t.Fatal("chunk_revisions must be deleted before chunks")
|
||||||
|
}
|
||||||
|
if position["wiki_page_revisions"] > position["wiki_pages"] {
|
||||||
|
t.Fatal("wiki_page_revisions must be deleted before wiki_pages")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionTablesAreNotResourceBodies(t *testing.T) {
|
||||||
|
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
|
||||||
|
if libraryResourceBodyTable(table) {
|
||||||
|
t.Fatalf("%s must not participate in resource discovery (Q2=B)", table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql := libraryResourceBodyReferenceSQL([]string{"chunks", "chunk_revisions", "wiki_page_revisions"}, "TRUE")
|
||||||
|
if strings.Contains(sql, "chunk_revisions") || strings.Contains(sql, "wiki_page_revisions") {
|
||||||
|
t.Fatalf("resource reference SQL must exclude revision tables: %s", sql)
|
||||||
|
}
|
||||||
|
if !strings.Contains(sql, "FROM chunks") {
|
||||||
|
t.Fatal("resource reference SQL must still scan live chunks")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructuredReferenceValidationCoversRevisions(t *testing.T) {
|
||||||
|
snapshot := PostgresSnapshot{Tables: []TableSnapshot{
|
||||||
|
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
|
||||||
|
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
|
||||||
|
newTableSnapshot("chunk_revisions", []json.RawMessage{
|
||||||
|
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-1"}`),
|
||||||
|
}),
|
||||||
|
newTableSnapshot("wiki_pages", []json.RawMessage{json.RawMessage(`{"id":"page-1"}`)}),
|
||||||
|
newTableSnapshot("wiki_page_revisions", []json.RawMessage{
|
||||||
|
json.RawMessage(`{"id":"wrev-1","page_id":"page-1"}`),
|
||||||
|
}),
|
||||||
|
}}
|
||||||
|
if err := validateLibraryStructuredReferences(snapshot); err != nil {
|
||||||
|
t.Fatalf("resolved revision references must pass: %v", err)
|
||||||
|
}
|
||||||
|
broken := snapshot
|
||||||
|
broken.Tables = []TableSnapshot{
|
||||||
|
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
|
||||||
|
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
|
||||||
|
newTableSnapshot("chunk_revisions", []json.RawMessage{
|
||||||
|
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-missing"}`),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
if err := validateLibraryStructuredReferences(broken); err == nil || !strings.Contains(err.Error(), "chunk_id") {
|
||||||
|
t.Fatalf("missing chunk parent must be refused, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@ import (
|
|||||||
var tablesWithKB = map[string]bool{
|
var tablesWithKB = map[string]bool{
|
||||||
"knowledges": true, "chunks": true, "knowledge_tags": true,
|
"knowledges": true, "chunks": true, "knowledge_tags": true,
|
||||||
"wiki_folders": true, "wiki_pages": true, "wiki_page_issues": true, "wiki_log_entries": true,
|
"wiki_folders": true, "wiki_pages": true, "wiki_page_issues": true, "wiki_log_entries": true,
|
||||||
|
"chunk_revisions": true, "wiki_page_revisions": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
// tableHasTenant 报告这张表是否自带租户列。
|
// tableHasTenant 报告这张表是否自带租户列。
|
||||||
|
|||||||
@@ -90,6 +90,21 @@ func validateLibraryStructuredReferences(pg PostgresSnapshot) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 编辑历史:chunk_id/page_id 是结构引用,不是展示事实。父行不在本快照里
|
||||||
|
// (软删父行按导出规则不出现)就拒绝;chunk 还必须与 revision.knowledge_id 同文档。
|
||||||
|
for _, r := range tables["chunk_revisions"] {
|
||||||
|
if e := ref(r, "knowledge_id", "knowledges", false); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if e := ref(r, "chunk_id", "chunks", true); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range tables["wiki_page_revisions"] {
|
||||||
|
if e := ref(r, "page_id", "wiki_pages", false); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, r := range tables["wiki_folders"] {
|
for _, r := range tables["wiki_folders"] {
|
||||||
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
|
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
|
||||||
return e
|
return e
|
||||||
|
|||||||
@@ -173,6 +173,26 @@ func (m *targetIDMapper) remapRow(table string, row map[string]json.RawMessage)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
case "chunk_revisions":
|
||||||
|
// 编辑历史与正文走同一套映射:自身身份 + 父文档/父分块引用。
|
||||||
|
// editor_id 是用户身份,原样保留(目标查不到就显示未知编辑者)。
|
||||||
|
if err := m.remapScalar(row, "id", table); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := m.remapScalar(row, "knowledge_id", "knowledges"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := m.remapScalar(row, "chunk_id", "chunks"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
case "wiki_page_revisions":
|
||||||
|
// 自身身份 + page 引用;slug/正文/版本号/aliases 原样保留。
|
||||||
|
if err := m.remapScalar(row, "id", table); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := m.remapScalar(row, "page_id", "wiki_pages"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
case "wiki_log_entries":
|
case "wiki_log_entries":
|
||||||
// id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档,
|
// id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档,
|
||||||
// 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。
|
// 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。
|
||||||
|
|||||||
@@ -80,12 +80,15 @@ func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, ta
|
|||||||
if name == "resources" {
|
if name == "resources" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err)
|
return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err)
|
||||||
}
|
}
|
||||||
if name != "resource_bindings" && name != "knowledge_tag_relations" {
|
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
|
||||||
bodies = append(bodies, items...)
|
bodies = append(bodies, items...)
|
||||||
}
|
}
|
||||||
if name == "resource_bindings" {
|
if name == "resource_bindings" {
|
||||||
|
|||||||
@@ -122,6 +122,13 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
|||||||
return libraryrelease.WriteSet{}, err
|
return libraryrelease.WriteSet{}, err
|
||||||
}
|
}
|
||||||
t.targetIDMode = libraryrelease.TargetIDModeScoped
|
t.targetIDMode = libraryrelease.TargetIDModeScoped
|
||||||
|
// 漏表门禁:写第一笔之前的预检。导入事务里还会再查一次(写前最终判定),
|
||||||
|
// 这里负责尽早失败,并把"空表放行"的警告写进持久发布记录。
|
||||||
|
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, t.pool,
|
||||||
|
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
|
||||||
|
if err != nil {
|
||||||
|
return libraryrelease.WriteSet{}, err
|
||||||
|
}
|
||||||
if err := validateArchivedLibraryClosure(archive, manifest); err != nil {
|
if err := validateArchivedLibraryClosure(archive, manifest); err != nil {
|
||||||
return libraryrelease.WriteSet{}, err
|
return libraryrelease.WriteSet{}, err
|
||||||
}
|
}
|
||||||
@@ -152,7 +159,8 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
|||||||
SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, JobID: plan.JobID, Target: plan.Target,
|
SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, JobID: plan.JobID, Target: plan.Target,
|
||||||
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
||||||
BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID,
|
BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID,
|
||||||
CreatedAt: t.now().UTC(), Universe: plan.Universe, TargetIDMode: libraryrelease.TargetIDModeScoped}
|
CreatedAt: t.now().UTC(), Universe: plan.Universe, Warnings: gateWarnings,
|
||||||
|
TargetIDMode: libraryrelease.TargetIDModeScoped}
|
||||||
for _, part := range manifest.Parts {
|
for _, part := range manifest.Parts {
|
||||||
if part.Kind != "database" && part.Kind != "wiki" {
|
if part.Kind != "database" && part.Kind != "wiki" {
|
||||||
continue
|
continue
|
||||||
@@ -350,6 +358,14 @@ func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner strin
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// jobCreatedRowDeleteOrder 是恢复清理的顺序契约:子表先删。编辑历史必须排在
|
||||||
|
// 父表 chunks/wiki_pages 之前;顺序写死在一处,并有单测防止新增表时漏改。
|
||||||
|
var jobCreatedRowDeleteOrder = []string{
|
||||||
|
"wiki_page_revisions", "chunk_revisions", "resource_bindings", "chunks", "knowledges",
|
||||||
|
"knowledge_tag_relations", "wiki_page_issues", "wiki_log_entries", "wiki_pages",
|
||||||
|
"wiki_folders", "knowledge_tags", "resources",
|
||||||
|
}
|
||||||
|
|
||||||
// clearJobCreatedRows 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份,
|
// clearJobCreatedRows 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份,
|
||||||
// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管
|
// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管
|
||||||
// 使用的资源不能删)。
|
// 使用的资源不能删)。
|
||||||
@@ -365,9 +381,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
|||||||
}
|
}
|
||||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||||
|
|
||||||
// 子表先删:resource_bindings → chunks/knowledges、wiki 子表 → wiki 页 → 资源。
|
for _, table := range jobCreatedRowDeleteOrder {
|
||||||
for _, table := range []string{"resource_bindings", "chunks", "knowledges", "knowledge_tag_relations",
|
|
||||||
"wiki_page_issues", "wiki_log_entries", "wiki_pages", "wiki_folders", "knowledge_tags", "resources"} {
|
|
||||||
ids := make([]string, 0, 8)
|
ids := make([]string, 0, 8)
|
||||||
for _, id := range set.CreatedIDs(table) {
|
for _, id := range set.CreatedIDs(table) {
|
||||||
if restored[table][id] {
|
if restored[table][id] {
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ const v090Folder = "wf-v090-1"
|
|||||||
const v090Page = "wp-v090-1"
|
const v090Page = "wp-v090-1"
|
||||||
const v090Tag = "tg-v090-1"
|
const v090Tag = "tg-v090-1"
|
||||||
const v090Resource = "rs-v090-1"
|
const v090Resource = "rs-v090-1"
|
||||||
|
const v090ChunkRevision = "cr-v090-1"
|
||||||
|
const v090PageRevision = "wr-v090-1"
|
||||||
|
|
||||||
// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。
|
// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。
|
||||||
// Wiki 必须非空:空表通过等于没有验证 wiki 部件。
|
// Wiki 必须非空:空表通过等于没有验证 wiki 部件。
|
||||||
@@ -99,6 +101,8 @@ func seedV090(t *testing.T, ctx context.Context, db *pgxpool.Pool) PostgresIdent
|
|||||||
`INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,name,path) VALUES ('` + v090Folder + `',$1,'` + v090KB + `','夹具目录','/fixture')`,
|
`INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,name,path) VALUES ('` + v090Folder + `',$1,'` + v090KB + `','夹具目录','/fixture')`,
|
||||||
`INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,title,content,source_refs,chunk_refs,folder_id) VALUES ('` + v090Page + `',$1,'` + v090KB + `','fixture-page','夹具页','wiki 正文','["` + v090Knowledge + `"]'::jsonb,'["` + v090ChunkOne + `"]'::jsonb,'` + v090Folder + `')`,
|
`INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,title,content,source_refs,chunk_refs,folder_id) VALUES ('` + v090Page + `',$1,'` + v090KB + `','fixture-page','夹具页','wiki 正文','["` + v090Knowledge + `"]'::jsonb,'["` + v090ChunkOne + `"]'::jsonb,'` + v090Folder + `')`,
|
||||||
`INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES ('` + v090Tag + `',$1,'` + v090KB + `','夹具标签')`,
|
`INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES ('` + v090Tag + `',$1,'` + v090KB + `','夹具标签')`,
|
||||||
|
`INSERT INTO chunk_revisions(id,tenant_id,knowledge_base_id,knowledge_id,chunk_id,revision,content,editor_id,edit_source) VALUES ('` + v090ChunkRevision + `',$1,'` + v090KB + `','` + v090Knowledge + `','` + v090ChunkOne + `',1,'第一段旧正文','editor-a','user')`,
|
||||||
|
`INSERT INTO wiki_page_revisions(id,tenant_id,knowledge_base_id,page_id,slug,version,title,content,edit_source,editor_id) VALUES ('` + v090PageRevision + `',$1,'` + v090KB + `','` + v090Page + `','fixture-page',1,'夹具页','旧 wiki 正文','pipeline','')`,
|
||||||
`INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`,
|
`INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`,
|
||||||
}
|
}
|
||||||
for _, statement := range statements {
|
for _, statement := range statements {
|
||||||
@@ -166,7 +170,7 @@ func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) Sea
|
|||||||
t.Fatalf("decode chunk: %v", err)
|
t.Fatalf("decode chunk: %v", err)
|
||||||
}
|
}
|
||||||
source, err := json.Marshal(map[string]any{
|
source, err := json.Marshal(map[string]any{
|
||||||
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
|
"chunk_id": chunk.ID,
|
||||||
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
||||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -22,10 +22,22 @@ set -euo pipefail
|
|||||||
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
||||||
CONFIG_FILE="${CONFIG_FILE:-/etc/knowledge-governance/backup.env}"
|
CONFIG_FILE="${CONFIG_FILE:-/etc/knowledge-governance/backup.env}"
|
||||||
SUBDIRS=(target-kb-snapshots rds-logical es-snapshots logs)
|
SUBDIRS=(target-kb-snapshots rds-logical es-snapshots logs)
|
||||||
|
# 配额与备份根写在同一份契约里:页面/采集器/备份脚本读的是同一个值。
|
||||||
|
# 重跑本脚本时沿用已有配额,避免把运维显式调过的值重置回默认。
|
||||||
|
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-}"
|
||||||
|
if [ -z "$QUOTA_BYTES" ] && [ -f "$CONFIG_FILE" ]; then
|
||||||
|
QUOTA_BYTES="$(sed -n 's/^[[:space:]]*KB_BACKUP_QUOTA_BYTES=//p' "$CONFIG_FILE" | tail -1 | tr -d "\"' \r")"
|
||||||
|
fi
|
||||||
|
QUOTA_BYTES="${QUOTA_BYTES:-53687091200}"
|
||||||
|
case "$QUOTA_BYTES" in
|
||||||
|
''|*[!0-9]*) echo "KB_BACKUP_QUOTA_BYTES 必须是正整数,收到 '$QUOTA_BYTES'" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
[ "$QUOTA_BYTES" -gt 0 ] || { echo "KB_BACKUP_QUOTA_BYTES 必须大于 0" >&2; exit 1; }
|
||||||
PRINT_ONLY=0
|
PRINT_ONLY=0
|
||||||
[ "${1:-}" = "--print" ] && PRINT_ONLY=1
|
[ "${1:-}" = "--print" ] && PRINT_ONLY=1
|
||||||
|
|
||||||
echo "备份根目录: $KB_BACKUP_ROOT"
|
echo "备份根目录: $KB_BACKUP_ROOT"
|
||||||
|
echo "备份配额 : $QUOTA_BYTES 字节"
|
||||||
echo "配置文件 : $CONFIG_FILE"
|
echo "配置文件 : $CONFIG_FILE"
|
||||||
echo "子目录 :"
|
echo "子目录 :"
|
||||||
total_bytes=0
|
total_bytes=0
|
||||||
@@ -52,6 +64,8 @@ mkdir -p "$(dirname "$CONFIG_FILE")"
|
|||||||
cat >"$CONFIG_FILE" <<EOF
|
cat >"$CONFIG_FILE" <<EOF
|
||||||
# 由 scripts/backup_layout.sh 生成:备份目录契约(换主机时只改这里)
|
# 由 scripts/backup_layout.sh 生成:备份目录契约(换主机时只改这里)
|
||||||
KB_BACKUP_ROOT=$KB_BACKUP_ROOT
|
KB_BACKUP_ROOT=$KB_BACKUP_ROOT
|
||||||
|
# 备份根累计占用硬上限(字节):采集器上报、logical-backup.sh 执行同一条线。
|
||||||
|
KB_BACKUP_QUOTA_BYTES=$QUOTA_BYTES
|
||||||
EOF
|
EOF
|
||||||
echo "已写入 $CONFIG_FILE"
|
echo "已写入 $CONFIG_FILE"
|
||||||
echo
|
echo
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import re
|
|||||||
import sys
|
import sys
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
|
|
||||||
|
import qa_report
|
||||||
import candidate_release as candidate
|
import candidate_release as candidate
|
||||||
import candidate_runtime as runtime
|
import candidate_runtime as runtime
|
||||||
import hifox_release_trigger as hfx
|
import hifox_release_trigger as hfx
|
||||||
@@ -114,11 +115,19 @@ def publish_candidate(plan, receipt, run):
|
|||||||
single = [item['task'] for item in plan['items']] == [plan['task']]
|
single = [item['task'] for item in plan['items']] == [plan['task']]
|
||||||
if single:
|
if single:
|
||||||
body = body.split('业务单记录用例')[0] + '请在本单逐项记录实测证据。在结构化报告加 cases 对象,business 和 regression 各列本轮通过的业务及同批回归用例编号,两组编号独立,合计等于 required。验收登记后,由负责人在本单切到待发布。'
|
body = body.split('业务单记录用例')[0] + '请在本单逐项记录实测证据。在结构化报告加 cases 对象,business 和 regression 各列本轮通过的业务及同批回归用例编号,两组编号独立,合计等于 required。验收登记后,由负责人在本单切到待发布。'
|
||||||
|
record = task(plan['task']) if single else {}
|
||||||
|
manual = (record.get('typeId') or (record.get('type') or {}).get('id')) == '1b7f1bb1-72c2-4106-b305-85604cf6d7e2'
|
||||||
|
if manual:
|
||||||
|
body += '\n候选已就绪。负责人可在本单切到「测试中」启动同包测试。'
|
||||||
|
if single:
|
||||||
|
body += '\nQA 请在测试机用 ~/.local/bin/kg-qa-report 从本轮用例清单生成报告,逐项填写结果和证据,正式候选无法登录时报告 blocked。'
|
||||||
key = 'ready ' + receipt['bundle']
|
key = 'ready ' + receipt['bundle']
|
||||||
add_comment(plan['task'], key, body)
|
add_comment(plan['task'], key, body)
|
||||||
for item in plan['items']:
|
for item in plan['items']:
|
||||||
item_id = item['task']
|
item_id = item['task']
|
||||||
status = (task(item_id).get('status') or {}).get('id')
|
status = (task(item_id).get('status') or {}).get('id')
|
||||||
|
if manual and status == WAIT_TEST:
|
||||||
|
continue
|
||||||
if status == TESTING:
|
if status == TESTING:
|
||||||
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
|
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
|
||||||
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
|
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
|
||||||
@@ -155,6 +164,27 @@ def summon_qa(plan, target, body):
|
|||||||
cd.record(path, {'state': 'sent', 'result': result})
|
cd.record(path, {'state': 'sent', 'result': result})
|
||||||
|
|
||||||
|
|
||||||
|
def acceptance_body(sha, bundle, tasks, reports, url_of, links):
|
||||||
|
"""State the registered verdict and its counts on the task itself, not only in metadata."""
|
||||||
|
lines = ['批次验收通过', '', f'提交 `{sha}`', '', f'归档 `{bundle}`', '']
|
||||||
|
single = len(tasks) == 1
|
||||||
|
for item in tasks:
|
||||||
|
row, result = reports[item]
|
||||||
|
if single:
|
||||||
|
lines.append(f'必测 {result["required"]} · 通过 {result["passed"]} · 失败 {result["failed"]} '
|
||||||
|
f'· 阻塞 {result["blocked"]} · 结论 {result["verdict"]}')
|
||||||
|
if result.get('url'):
|
||||||
|
lines.append(f'候选地址 {result["url"]}')
|
||||||
|
cases = result.get('cases') or {}
|
||||||
|
for group, label in (('business', '业务用例'), ('regression', '回归用例')):
|
||||||
|
if isinstance(cases.get(group), list) and cases[group]:
|
||||||
|
lines.append(f'{label}({len(cases[group])}):' + '、'.join(cases[group]))
|
||||||
|
else:
|
||||||
|
lines.append(f'{url_of(item)}#comment-{row["id"]}')
|
||||||
|
lines += ['', '需求验收与批次回归报告', links]
|
||||||
|
return '\n'.join(lines)
|
||||||
|
|
||||||
|
|
||||||
def register(task_id):
|
def register(task_id):
|
||||||
plan = owner_plan(task_id)
|
plan = owner_plan(task_id)
|
||||||
directory = STATE / cd.acceptance_digest(plan)
|
directory = STATE / cd.acceptance_digest(plan)
|
||||||
@@ -179,6 +209,13 @@ def register(task_id):
|
|||||||
row = reports[item_id][0]
|
row = reports[item_id][0]
|
||||||
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
||||||
'invalid QA evidence link')
|
'invalid QA evidence link')
|
||||||
|
if [item['task'] for item in plan['items']] == [task_id] and task_id in reports:
|
||||||
|
accepted = cd.metadata(task(task_id), 'cd_acceptance') or {}
|
||||||
|
if (accepted.get('sha'), accepted.get('bundle')) != (receipt['sha'], receipt['bundle']):
|
||||||
|
try:
|
||||||
|
qa_report.verify_report(reports[task_id][1])
|
||||||
|
except ValueError as error:
|
||||||
|
raise cd.CDError(f'QA 请在测试机提交逐项报告:{error}') from error
|
||||||
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
|
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
|
||||||
fresh = owner_plan(task_id)
|
fresh = owner_plan(task_id)
|
||||||
cd.require(fresh == plan, 'release plan changed during registration')
|
cd.require(fresh == plan, 'release plan changed during registration')
|
||||||
@@ -187,7 +224,7 @@ def register(task_id):
|
|||||||
'register QA before the owner moves the release task to 待发布')
|
'register QA before the owner moves the release task to 待发布')
|
||||||
sha, bundle = receipt['sha'], receipt['bundle']
|
sha, bundle = receipt['sha'], receipt['bundle']
|
||||||
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
||||||
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
|
body = acceptance_body(sha, bundle, tasks, reports, lambda item: task(item)['url'], links)
|
||||||
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
||||||
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
||||||
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Drain reviewed demand tasks through the shared candidate environment."""
|
||||||
|
import json
|
||||||
|
|
||||||
|
import release_handoff as h
|
||||||
|
|
||||||
|
cd = h.cd
|
||||||
|
coordinator = h.coordinator
|
||||||
|
|
||||||
|
|
||||||
|
def release_published_slot(compose):
|
||||||
|
directory = compose.parent
|
||||||
|
ready = cd.read_json(cd.immutable_file(directory / 'ready.json'))
|
||||||
|
task = h.assistant.task_record(ready['task'])
|
||||||
|
published = cd.metadata(task, 'cd_release') or {}
|
||||||
|
if task['status']['id'] != cd.PUBLISHED or not all(published.get(k) == ready[k] for k in ('sha', 'bundle')):
|
||||||
|
return False
|
||||||
|
project = 'kg-batch-' + ready['bundle'][:20]
|
||||||
|
cd.require(ready['mode'] == 'acceptance' and cd.hash_file(directory / 'bundle/release.json') == ready['bundle'],
|
||||||
|
'published QA archive changed')
|
||||||
|
cd.require(set(ready['containers']) == {'api', 'web', 'worker'}, 'unexpected candidate service set')
|
||||||
|
ids = []
|
||||||
|
for role, name in ready['containers'].items():
|
||||||
|
cd.require(name == project + '-' + role, 'candidate name mismatch')
|
||||||
|
info = json.loads(cd.run(['docker', 'inspect', name], 'inspect QA container'))[0]
|
||||||
|
labels = info['Config']['Labels']
|
||||||
|
cd.require(labels.get('com.docker.compose.project') == project and info['Image'] == ready['images'][role],
|
||||||
|
'candidate container identity changed')
|
||||||
|
ids.append(info['Id'])
|
||||||
|
cd.run(['docker', 'stop', *ids], 'retire published QA environment', timeout=90)
|
||||||
|
info = json.loads(cd.run(['docker', 'inspect', *ids], 'verify stopped QA containers'))
|
||||||
|
cd.require(len(info) == len(ids) and not any(row['State']['Running'] for row in info), 'QA slot still running')
|
||||||
|
compose.rename(directory / 'compose.released.json')
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def in_flight(state):
|
||||||
|
for path in state.glob('*.dispatch.json'):
|
||||||
|
claim = cd.read_json(cd.immutable_file(path))
|
||||||
|
key = path.name.split('.')[0]
|
||||||
|
if (state / key / 'ready.json').is_file():
|
||||||
|
continue
|
||||||
|
if claim['state'] != 'queued':
|
||||||
|
return True
|
||||||
|
run = h.candidate.read_forge(h.candidate.API + '/actions/runs/' + str(claim['run']))
|
||||||
|
if run['status'] != 'completed' or run.get('conclusion') == 'success':
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def drain():
|
||||||
|
state = coordinator.STATE
|
||||||
|
waiting = state / 'waiting'
|
||||||
|
waiting.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
with cd.deploy_lock(waiting / 'queue.lock'):
|
||||||
|
entries = sorted(waiting.glob('*.json'), key=lambda p: (p.stat().st_mtime_ns, p.name))
|
||||||
|
entries = [(p, cd.read_json(cd.immutable_file(p))) for p in entries]
|
||||||
|
entries = [(p, e) for p, e in entries if e['state'] == 'waiting_for_slot']
|
||||||
|
if not entries:
|
||||||
|
return 'idle'
|
||||||
|
with cd.deploy_lock(state / 'runtime.lock'):
|
||||||
|
for compose in state.glob('*/compose.json'):
|
||||||
|
if not release_published_slot(compose):
|
||||||
|
return 'occupied'
|
||||||
|
if in_flight(state):
|
||||||
|
return 'building'
|
||||||
|
path, entry = entries[0]
|
||||||
|
task = h.assistant.task_record(entry['task'])
|
||||||
|
try:
|
||||||
|
sha, _ = h.resolve(task, entry['event'])
|
||||||
|
cd.require(sha == entry['sha'], 'review changed before building')
|
||||||
|
live = h.assistant.worker.main_site_sha()
|
||||||
|
if h.candidate.git('merge-base', live, sha, cwd=h.assistant.SOURCE, allowed=(0, 1)) == sha:
|
||||||
|
notice = f'主站当前版本 `{live}` 已包含候选提交 `{sha}`。请核对该需求的发布与验收记录。'
|
||||||
|
entry.update(state='included_in_live')
|
||||||
|
else:
|
||||||
|
result = h.prepare_from_review(task, entry['event'])
|
||||||
|
entry.update(state='dispatched', result=result)
|
||||||
|
notice = '候选构建已排队。' + result['url']
|
||||||
|
except cd.CDError as exc:
|
||||||
|
entry.update(state='blocked', reason=str(exc))
|
||||||
|
notice = '候选准备已停止。' + str(exc)
|
||||||
|
cd.record(path, entry)
|
||||||
|
coordinator.add_comment(task['id'], 'queue-result ' + entry['event'], notice)
|
||||||
|
return entry['state']
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print(drain())
|
||||||
@@ -15,6 +15,8 @@ from urllib.parse import quote
|
|||||||
import production_cd as cd
|
import production_cd as cd
|
||||||
import qa_env
|
import qa_env
|
||||||
|
|
||||||
|
STATE = Path.home() / '.local/state/kg-candidate-release'
|
||||||
|
|
||||||
|
|
||||||
def isolated_subnet(exclude=()):
|
def isolated_subnet(exclude=()):
|
||||||
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
|
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
|
||||||
@@ -49,6 +51,29 @@ def qa_database(path):
|
|||||||
return url, cert
|
return url, cert
|
||||||
|
|
||||||
|
|
||||||
|
def qa_process_command(role):
|
||||||
|
if role not in ('api', 'worker'):
|
||||||
|
raise ValueError('unexpected QA process')
|
||||||
|
return ['/bin/sh', '-ec', 'export DATABASE_URL="$${DATABASE_URL}&pool_max_conns=2"; exec /app/' + role]
|
||||||
|
|
||||||
|
|
||||||
|
APP_UID = 65532
|
||||||
|
|
||||||
|
|
||||||
|
def qa_binding_key(image):
|
||||||
|
"""Give QA candidates one stable binding master key, readable by the application user."""
|
||||||
|
path = STATE / 'qa-binding-master.key'
|
||||||
|
if not path.exists():
|
||||||
|
cd.atomic_write(path, secrets.token_bytes(32), mode=0o600)
|
||||||
|
cd.run(['docker', 'run', '--rm', '--user', '0', '-v', f'{path.parent}:/run/kg-key', image,
|
||||||
|
'chown', f'{APP_UID}:{APP_UID}', f'/run/kg-key/{path.name}'],
|
||||||
|
'hand the QA binding master key to the application user', timeout=90)
|
||||||
|
info = path.lstat()
|
||||||
|
cd.require(info.st_mode & 0o777 == 0o600 and info.st_size == 32 and info.st_uid == APP_UID,
|
||||||
|
'QA binding master key must be a 32-byte file owned by the application user with mode 0600')
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
def ready(directory, bundle, test_database=None):
|
def ready(directory, bundle, test_database=None):
|
||||||
bundle = bundle.resolve()
|
bundle = bundle.resolve()
|
||||||
manifest = cd.read_json(bundle / 'release.json')
|
manifest = cd.read_json(bundle / 'release.json')
|
||||||
@@ -82,6 +107,9 @@ def ready(directory, bundle, test_database=None):
|
|||||||
url, cert = qa_database(test_database)
|
url, cert = qa_database(test_database)
|
||||||
env['DATA' + 'BASE_URL'] = url
|
env['DATA' + 'BASE_URL'] = url
|
||||||
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
|
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
|
||||||
|
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
|
||||||
|
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
|
||||||
|
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
|
||||||
app_env = directory / 'app.env'
|
app_env = directory / 'app.env'
|
||||||
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
||||||
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
||||||
@@ -90,15 +118,22 @@ def ready(directory, bundle, test_database=None):
|
|||||||
cd.verify_archive(archive, item['id'])
|
cd.verify_archive(archive, item['id'])
|
||||||
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
|
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
|
||||||
services[role] = {'image': item['id'], 'container_name': names[role]}
|
services[role] = {'image': item['id'], 'container_name': names[role]}
|
||||||
|
key = qa_binding_key(manifest['images']['api']['id']) if test_database is not None else None
|
||||||
for role in ('api', 'worker'):
|
for role in ('api', 'worker'):
|
||||||
services[role]['env_file'] = [str(app_env)]
|
services[role]['env_file'] = [str(app_env)]
|
||||||
if test_database is not None:
|
if test_database is not None:
|
||||||
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro']
|
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro',
|
||||||
|
f'{key}:/run/qa/binding-master.key:ro']
|
||||||
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
|
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
|
||||||
'interval': '2s', 'timeout': '3s', 'retries': 45}
|
'interval': '2s', 'timeout': '3s', 'retries': 45}
|
||||||
if test_database is None:
|
if test_database is None:
|
||||||
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
|
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
|
||||||
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
|
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||||
|
if test_database is not None:
|
||||||
|
# Apply the pgx budget to the application process. The independent libpq
|
||||||
|
# migration probe reads the original, TLS-verified DSN from Docker exec.
|
||||||
|
for role in ('api', 'worker'):
|
||||||
|
services[role]['command'] = qa_process_command(role)
|
||||||
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
|
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||||
internal_subnet = isolated_subnet()
|
internal_subnet = isolated_subnet()
|
||||||
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
|
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""把一次发布运行的结果上报 ci-bridge,与 build 的通知同一出口。
|
||||||
|
|
||||||
|
发布失败也必须上报:群里要知道是「发布失败」而不是没有消息。
|
||||||
|
上报失败只打印,不改变发布的结论。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
def env(name, default=''):
|
||||||
|
return (os.environ.get(name) or default).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def git(*args):
|
||||||
|
try:
|
||||||
|
return subprocess.check_output(['git', *args], text=True, stderr=subprocess.DEVNULL).strip()
|
||||||
|
except (OSError, subprocess.CalledProcessError):
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def result_status(value):
|
||||||
|
return {'success': 'success', 'failure': 'failure', 'cancelled': 'cancelled'}.get(value, 'failure')
|
||||||
|
|
||||||
|
|
||||||
|
def payload():
|
||||||
|
deploy_sha = env('DEPLOY_SHA') or env('GITHUB_SHA')
|
||||||
|
publish = result_status(env('PUBLISH_RESULT'))
|
||||||
|
guard = result_status(env('GUARD_RESULT'))
|
||||||
|
status = publish if publish != 'success' else guard
|
||||||
|
subject = git('log', '-1', '--format=%s', deploy_sha) if deploy_sha else ''
|
||||||
|
steps = []
|
||||||
|
for name, value in (('guard', env('GUARD_RESULT')), ('publish', env('PUBLISH_RESULT'))):
|
||||||
|
steps.append({'name': name, 'status': result_status(value), 'duration_s': ''})
|
||||||
|
return {
|
||||||
|
'repo': env('GITHUB_REPOSITORY', 'unknown/unknown'),
|
||||||
|
'sha': deploy_sha,
|
||||||
|
'branch': 'main',
|
||||||
|
'actor': env('GITHUB_ACTOR'),
|
||||||
|
'workflow': 'deploy-production',
|
||||||
|
'kind': 'deploy',
|
||||||
|
'site_url': env('DEPLOY_SITE_URL', 'http://100.85.111.121:8088/'),
|
||||||
|
'status': status,
|
||||||
|
'commit_subject': subject,
|
||||||
|
'commit_count': '1',
|
||||||
|
'duration_s': '',
|
||||||
|
'preview_url': '',
|
||||||
|
'steps': steps,
|
||||||
|
'manifest': ['guard', 'publish'],
|
||||||
|
'bundle': env('DEPLOY_BUNDLE'),
|
||||||
|
'task': env('DEPLOY_TASK'),
|
||||||
|
'run_id': env('GITHUB_RUN_ID'),
|
||||||
|
'run_number': env('GITHUB_RUN_NUMBER'),
|
||||||
|
'run_attempt': env('GITHUB_RUN_ATTEMPT', '1'),
|
||||||
|
'commit_url': f"{env('CI_PUBLIC_BASE_URL', env('GITHUB_SERVER_URL'))}/{env('GITHUB_REPOSITORY')}/commit/{deploy_sha}",
|
||||||
|
'run_url': f"{env('CI_PUBLIC_BASE_URL', env('GITHUB_SERVER_URL'))}/{env('GITHUB_REPOSITORY')}/actions/runs/{env('GITHUB_RUN_ID')}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def post(data, base, token):
|
||||||
|
body = json.dumps(data, ensure_ascii=False).encode()
|
||||||
|
req = urllib.request.Request(base.rstrip('/') + '/api/ci/report', data=body, method='POST',
|
||||||
|
headers={'Content-Type': 'application/json', 'X-CI-Token': token})
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as response:
|
||||||
|
return response.read().decode()[:300]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--no-post', action='store_true')
|
||||||
|
args = parser.parse_args()
|
||||||
|
data = payload()
|
||||||
|
if args.no_post:
|
||||||
|
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||||
|
return 0
|
||||||
|
base = env('CI_BRIDGE_RESOLVED') or env('BRIDGE_URL') or env('CI_BRIDGE_URL')
|
||||||
|
if not base:
|
||||||
|
print('跳过上报:未找到 ci-bridge 地址', file=sys.stderr)
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
print('✅ 已上报 ci-bridge:' + post(data, base, env('BRIDGE_TOKEN')))
|
||||||
|
except (urllib.error.URLError, OSError) as error:
|
||||||
|
# 通知失败不改变发布结论,只记一行。
|
||||||
|
print(f'❌ 上报 ci-bridge 失败(发布结论不变):{error}', file=sys.stderr)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -37,12 +37,71 @@ COLLECTOR_VERSION = "backup-metadata/1"
|
|||||||
MAX_MANIFEST_BYTES = 8 << 20
|
MAX_MANIFEST_BYTES = 8 << 20
|
||||||
MAX_ERRORS = 50
|
MAX_ERRORS = 50
|
||||||
STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
|
STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
|
||||||
|
# 备份根与配额是**同一份部署契约**:backup_layout.sh 写、采集器读、备份脚本执行。
|
||||||
|
# 采集器不自己发明 50 GB,缺配置时用同一默认值,页面上报的配额因此就是脚本执行的值。
|
||||||
|
DEFAULT_BACKUP_ROOT = "/srv/kb-backups"
|
||||||
|
DEFAULT_QUOTA_BYTES = 53687091200 # 50 GiB
|
||||||
|
LAYOUT_CONFIG = "/etc/knowledge-governance/backup.env"
|
||||||
|
|
||||||
|
|
||||||
class CollectError(Exception):
|
class CollectError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def read_layout(path: str) -> dict[str, str]:
|
||||||
|
"""读 backup.env 的 KEY=VALUE(只取本脚本认识的键)。
|
||||||
|
|
||||||
|
为什么不用 sh source:采集器是 Python,且这里只需要两个标量;整文件执行会把无关的
|
||||||
|
主机配置带进进程。文件不存在返回空(本地/未接线按默认值),显式给了路径却读不到则报错。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as handle:
|
||||||
|
lines = handle.readlines()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return {}
|
||||||
|
except OSError as error:
|
||||||
|
raise CollectError(f"备份配置不可读:{_error_text(error)}") from error
|
||||||
|
values: dict[str, str] = {}
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
||||||
|
continue
|
||||||
|
key, _, value = stripped.partition("=")
|
||||||
|
key = key.strip()
|
||||||
|
if key in ("KB_BACKUP_ROOT", "KB_BACKUP_QUOTA_BYTES"):
|
||||||
|
values[key] = value.strip().strip('"').strip("'")
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_backup_settings(
|
||||||
|
batch_root: str,
|
||||||
|
usage_root: str | None,
|
||||||
|
quota: int | None,
|
||||||
|
config_path: str,
|
||||||
|
) -> tuple[str, int | None, str]:
|
||||||
|
"""解析备份根与配额:显式参数 > backup.env > 默认值。
|
||||||
|
|
||||||
|
配额非法时返回 quota=None + 原因(不是猜一个值);配额/路径错误都不阻止批次盘点,
|
||||||
|
由 API 把「占用/配额未知」和「批次可用」分开呈现。
|
||||||
|
"""
|
||||||
|
batch_root = os.path.abspath(batch_root)
|
||||||
|
layout = read_layout(config_path)
|
||||||
|
raw_root = usage_root or layout.get("KB_BACKUP_ROOT") or DEFAULT_BACKUP_ROOT
|
||||||
|
if not os.path.isabs(raw_root) or os.path.normpath(raw_root) != raw_root:
|
||||||
|
raise CollectError(f"备份根不是规范绝对路径:{raw_root}")
|
||||||
|
backup_root = raw_root
|
||||||
|
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
|
||||||
|
raise CollectError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
|
||||||
|
quota_text = str(quota) if quota is not None else layout.get("KB_BACKUP_QUOTA_BYTES", str(DEFAULT_QUOTA_BYTES))
|
||||||
|
try:
|
||||||
|
quota_value = int(quota_text)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return backup_root, None, f"备份配额不是整数:{quota_text!r}"
|
||||||
|
if quota_value <= 0:
|
||||||
|
return backup_root, None, f"备份配额必须为正整数:{quota_value}"
|
||||||
|
return backup_root, quota_value, ""
|
||||||
|
|
||||||
|
|
||||||
def _error_text(error: BaseException) -> str:
|
def _error_text(error: BaseException) -> str:
|
||||||
if isinstance(error, OSError) and error.filename:
|
if isinstance(error, OSError) and error.filename:
|
||||||
return f"{type(error).__name__}: {error.strerror or error} ({error.filename})"
|
return f"{type(error).__name__}: {error.strerror or error} ({error.filename})"
|
||||||
@@ -212,6 +271,28 @@ def measure_tree(path: str, scan: Callable[[str], Iterable[Any]] = os.scandir, m
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def project_usage(root: str, tree: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""把根树测量投影成「可展示的占用」:不完整时一律不给字节。
|
||||||
|
|
||||||
|
与批次同样的纪律(0.1.408/0.1.410):部分计数永远不能当占盘;
|
||||||
|
但这里的 error 只属于 usage,不会被塞进 snapshot.errors 去污染批次完整性。
|
||||||
|
"""
|
||||||
|
complete = bool(tree["complete"])
|
||||||
|
errors = list(tree["errors"])[:MAX_ERRORS]
|
||||||
|
if not complete and not errors:
|
||||||
|
errors = ["备份根遍历不完整"]
|
||||||
|
return {
|
||||||
|
"root": root,
|
||||||
|
"complete": complete,
|
||||||
|
"actual_bytes": tree["actual_bytes"] if complete else None,
|
||||||
|
"apparent_bytes": tree["apparent_bytes"] if complete else None,
|
||||||
|
"file_count": tree["file_count"] if complete else None,
|
||||||
|
"dir_count": tree["dir_count"] if complete else None,
|
||||||
|
"errors": errors,
|
||||||
|
"error": "" if complete else "备份根占用未知:" + ";".join(errors[:3]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def collect(
|
def collect(
|
||||||
root: str,
|
root: str,
|
||||||
source: str = "",
|
source: str = "",
|
||||||
@@ -219,8 +300,12 @@ def collect(
|
|||||||
max_batches: int = 100,
|
max_batches: int = 100,
|
||||||
scan: Callable[[str], Iterable[Any]] = os.scandir,
|
scan: Callable[[str], Iterable[Any]] = os.scandir,
|
||||||
now: dt.datetime | None = None,
|
now: dt.datetime | None = None,
|
||||||
|
backup_root: str = "",
|
||||||
|
quota_bytes: int | None = None,
|
||||||
|
quota_error: str = "",
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
root = os.path.abspath(root)
|
root = os.path.abspath(root)
|
||||||
|
backup_root = os.path.abspath(backup_root or root)
|
||||||
collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc)
|
collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc)
|
||||||
snapshot: dict[str, Any] = {
|
snapshot: dict[str, Any] = {
|
||||||
"schema_version": SCHEMA_VERSION,
|
"schema_version": SCHEMA_VERSION,
|
||||||
@@ -230,6 +315,10 @@ def collect(
|
|||||||
"host": host or socket.gethostname(),
|
"host": host or socket.gethostname(),
|
||||||
"source": source,
|
"source": source,
|
||||||
"root": root,
|
"root": root,
|
||||||
|
"backup_root": backup_root,
|
||||||
|
"usage": {},
|
||||||
|
"quota_bytes": quota_bytes,
|
||||||
|
"quota_error": quota_error,
|
||||||
"complete": True,
|
"complete": True,
|
||||||
"errors": [],
|
"errors": [],
|
||||||
"filesystem": {},
|
"filesystem": {},
|
||||||
@@ -239,6 +328,9 @@ def collect(
|
|||||||
"batches": [],
|
"batches": [],
|
||||||
}
|
}
|
||||||
errors: list[str] = snapshot["errors"]
|
errors: list[str] = snapshot["errors"]
|
||||||
|
# 根占用与批次完整性**分开**:某个保护目录读不到时,占用可以说「未知」,
|
||||||
|
# 但批次表/磁盘容量仍然有效;把两者绑在一起会把「占用未知」扩大成「全部未知」。
|
||||||
|
snapshot["usage"] = project_usage(backup_root, measure_tree(backup_root, scan))
|
||||||
try:
|
try:
|
||||||
if not os.path.isdir(root):
|
if not os.path.isdir(root):
|
||||||
raise CollectError(f"备份根不是目录:{root}")
|
raise CollectError(f"备份根不是目录:{root}")
|
||||||
@@ -529,6 +621,61 @@ def _self_test() -> None:
|
|||||||
assert ignored["incomplete_count"] == 1
|
assert ignored["incomplete_count"] == 1
|
||||||
assert [item["stamp"] for item in ignored["batches"]] == [stamp]
|
assert [item["stamp"] for item in ignored["batches"]] == [stamp]
|
||||||
|
|
||||||
|
# 根占用:测整棵备份根(不只是 rds-logical),与 du -sB1 对拍。
|
||||||
|
kb_root = os.path.join(base, "kb-backups")
|
||||||
|
kb_batch_root = os.path.join(kb_root, "rds-logical")
|
||||||
|
kb_batch = os.path.join(kb_batch_root, "20261119T193001Z")
|
||||||
|
os.makedirs(os.path.join(kb_batch, "weknora_kb.dir"))
|
||||||
|
with open(os.path.join(kb_batch, "weknora_kb.dir", "toc.dat"), "wb") as handle:
|
||||||
|
handle.write(b"k" * 1000)
|
||||||
|
with open(os.path.join(kb_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||||
|
json.dump({"databases": ["weknora_kb"]}, handle)
|
||||||
|
es_dir = os.path.join(kb_root, "es-snapshots")
|
||||||
|
os.makedirs(es_dir)
|
||||||
|
with open(os.path.join(es_dir, "index-0"), "wb") as handle:
|
||||||
|
handle.write(b"e" * 2000)
|
||||||
|
rooted = collect(kb_batch_root, backup_root=kb_root, quota_bytes=DEFAULT_QUOTA_BYTES, now=fixed)
|
||||||
|
assert rooted["complete"] is True, rooted
|
||||||
|
assert rooted["usage"]["complete"] is True, rooted["usage"]
|
||||||
|
assert rooted["usage"]["root"] == kb_root
|
||||||
|
assert rooted["quota_bytes"] == DEFAULT_QUOTA_BYTES
|
||||||
|
assert rooted["usage"]["actual_bytes"] >= 3000
|
||||||
|
if shutil.which("du"):
|
||||||
|
assert rooted["usage"]["actual_bytes"] == du_bytes(kb_root), rooted["usage"]
|
||||||
|
assert rooted["usage"]["actual_bytes"] > rooted["batches"][0]["actual_bytes"]
|
||||||
|
|
||||||
|
# 根占用遍历失败:只让占用未知,批次与整体 complete 不受影响。
|
||||||
|
def denied_root_scan(target: str):
|
||||||
|
if target == kb_root:
|
||||||
|
raise PermissionError(errno.EACCES, "Permission denied", target)
|
||||||
|
return os.scandir(target)
|
||||||
|
|
||||||
|
partial = collect(kb_batch_root, backup_root=kb_root, scan=denied_root_scan, now=fixed)
|
||||||
|
assert partial["usage"]["complete"] is False
|
||||||
|
assert partial["usage"]["actual_bytes"] is None
|
||||||
|
assert "Permission denied" in partial["usage"]["error"]
|
||||||
|
assert partial["complete"] is True, partial
|
||||||
|
assert len(partial["batches"]) == 1
|
||||||
|
|
||||||
|
# 配置解析:备份根/配额来自 backup.env;非法配额给原因而不是默认放行。
|
||||||
|
config_path = os.path.join(base, "backup.env")
|
||||||
|
with open(config_path, "w", encoding="utf-8") as handle:
|
||||||
|
handle.write(f"KB_BACKUP_ROOT={kb_root}\nKB_BACKUP_QUOTA_BYTES=12345\n")
|
||||||
|
resolved_root, resolved_quota, resolved_error = resolve_backup_settings(
|
||||||
|
kb_batch_root, None, None, config_path
|
||||||
|
)
|
||||||
|
assert resolved_root == kb_root and resolved_quota == 12345 and resolved_error == ""
|
||||||
|
with open(config_path, "w", encoding="utf-8") as handle:
|
||||||
|
handle.write(f"KB_BACKUP_ROOT={kb_root}\nKB_BACKUP_QUOTA_BYTES=50GB\n")
|
||||||
|
_, bad_quota, bad_error = resolve_backup_settings(kb_batch_root, None, None, config_path)
|
||||||
|
assert bad_quota is None and "不是整数" in bad_error
|
||||||
|
try:
|
||||||
|
resolve_backup_settings(kb_batch_root, os.path.join(base, "outside"), None, config_path)
|
||||||
|
except CollectError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("批次根不在备份根下必须拒绝")
|
||||||
|
|
||||||
output = os.path.join(base, "out", "metadata.json")
|
output = os.path.join(base, "out", "metadata.json")
|
||||||
write_snapshot(output, ignored)
|
write_snapshot(output, ignored)
|
||||||
with open(output, encoding="utf-8") as handle:
|
with open(output, encoding="utf-8") as handle:
|
||||||
@@ -548,6 +695,9 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
parser.add_argument("--source", default="", help="展示来源,如 weknora-test:/srv/...")
|
parser.add_argument("--source", default="", help="展示来源,如 weknora-test:/srv/...")
|
||||||
parser.add_argument("--host", default="", help="采集主机名(默认当前主机)")
|
parser.add_argument("--host", default="", help="采集主机名(默认当前主机)")
|
||||||
parser.add_argument("--max-batches", type=int, default=100)
|
parser.add_argument("--max-batches", type=int, default=100)
|
||||||
|
parser.add_argument("--usage-root", default="", help="备份根(默认读 backup.env 的 KB_BACKUP_ROOT)")
|
||||||
|
parser.add_argument("--quota-bytes", type=int, default=None, help="备份配额(默认读 backup.env)")
|
||||||
|
parser.add_argument("--config", default=LAYOUT_CONFIG, help="部署配置 backup.env")
|
||||||
parser.add_argument("--self-test", action="store_true")
|
parser.add_argument("--self-test", action="store_true")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
if args.self_test:
|
if args.self_test:
|
||||||
@@ -556,11 +706,17 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
if not args.root or not args.output:
|
if not args.root or not args.output:
|
||||||
parser.error("--root and --output are required unless --self-test")
|
parser.error("--root and --output are required unless --self-test")
|
||||||
try:
|
try:
|
||||||
|
backup_root, quota_bytes, quota_error = resolve_backup_settings(
|
||||||
|
args.root, args.usage_root or None, args.quota_bytes, args.config
|
||||||
|
)
|
||||||
snapshot = collect(
|
snapshot = collect(
|
||||||
args.root,
|
args.root,
|
||||||
source=args.source,
|
source=args.source,
|
||||||
host=args.host or None,
|
host=args.host or None,
|
||||||
max_batches=max(1, args.max_batches),
|
max_batches=max(1, args.max_batches),
|
||||||
|
backup_root=backup_root,
|
||||||
|
quota_bytes=quota_bytes,
|
||||||
|
quota_error=quota_error,
|
||||||
)
|
)
|
||||||
write_snapshot(args.output, snapshot)
|
write_snapshot(args.output, snapshot)
|
||||||
except (CollectError, OSError) as error:
|
except (CollectError, OSError) as error:
|
||||||
@@ -570,11 +726,17 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
"complete": snapshot["complete"],
|
"complete": snapshot["complete"],
|
||||||
"batches": len(snapshot["batches"]),
|
"batches": len(snapshot["batches"]),
|
||||||
"incomplete_count": snapshot["incomplete_count"],
|
"incomplete_count": snapshot["incomplete_count"],
|
||||||
|
"backup_root": snapshot["backup_root"],
|
||||||
|
"usage_bytes": snapshot["usage"].get("actual_bytes"),
|
||||||
|
"usage_complete": snapshot["usage"].get("complete"),
|
||||||
|
"quota_bytes": snapshot["quota_bytes"],
|
||||||
|
"quota_error": snapshot["quota_error"],
|
||||||
"collected_at": snapshot["collected_at"],
|
"collected_at": snapshot["collected_at"],
|
||||||
"output": args.output,
|
"output": args.output,
|
||||||
}
|
}
|
||||||
print(json.dumps(summary, ensure_ascii=False))
|
print(json.dumps(summary, ensure_ascii=False))
|
||||||
return 0 if snapshot["complete"] else 2
|
healthy = bool(snapshot["complete"] and snapshot["usage"].get("complete") and not snapshot["quota_error"])
|
||||||
|
return 0 if healthy else 2
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -54,7 +54,10 @@ show_state() {
|
|||||||
if command -v systemctl >/dev/null 2>&1; then
|
if command -v systemctl >/dev/null 2>&1; then
|
||||||
echo "cron 服务: $(systemctl is-active cron 2>/dev/null || systemctl is-active crond 2>/dev/null || echo unknown)"
|
echo "cron 服务: $(systemctl is-active cron 2>/dev/null || systemctl is-active crond 2>/dev/null || echo unknown)"
|
||||||
fi
|
fi
|
||||||
echo "备份根目录: $KB_BACKUP_ROOT($(du -sh "$KB_BACKUP_ROOT/rds-logical" 2>/dev/null | cut -f1 || echo 0) 已用)"
|
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-53687091200}"
|
||||||
|
if ROOT_BYTES="$(du -sB1 -- "$KB_BACKUP_ROOT" 2>/dev/null | cut -f1)"; then :; else ROOT_BYTES="未知"; fi
|
||||||
|
LOGICAL_USAGE="$(du -sh "$KB_BACKUP_ROOT/rds-logical" 2>/dev/null | cut -f1 || echo 未知)"
|
||||||
|
echo "备份根占用: $KB_BACKUP_ROOT(${ROOT_BYTES:-未知} 字节 / 配额 $QUOTA_BYTES 字节;rds-logical $LOGICAL_USAGE)"
|
||||||
}
|
}
|
||||||
|
|
||||||
if [ "$MODE" = "show" ]; then
|
if [ "$MODE" = "show" ]; then
|
||||||
|
|||||||
+71
-23
@@ -21,6 +21,7 @@
|
|||||||
# JOBS 并行度(默认 4)
|
# JOBS 并行度(默认 4)
|
||||||
# KEEP_DAILY 保留最近几份每日备份(默认 7)
|
# KEEP_DAILY 保留最近几份每日备份(默认 7)
|
||||||
# KEEP_MONTHS 额外保留最近几个自然月各一份(默认 3)
|
# KEEP_MONTHS 额外保留最近几个自然月各一份(默认 3)
|
||||||
|
# KB_BACKUP_QUOTA_BYTES 备份根累计占用硬上限(默认 53687091200 = 50 GiB,来自 backup.env)
|
||||||
# EXCLUDE_DBS 逗号分隔的跳过列表(默认 rdsadmin:RDS 管理库,普通账号导不出来)
|
# EXCLUDE_DBS 逗号分隔的跳过列表(默认 rdsadmin:RDS 管理库,普通账号导不出来)
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
@@ -31,7 +32,28 @@ if [ -z "${KB_BACKUP_ROOT:-}" ] && [ -f /etc/knowledge-governance/backup.env ];
|
|||||||
. /etc/knowledge-governance/backup.env
|
. /etc/knowledge-governance/backup.env
|
||||||
fi
|
fi
|
||||||
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
||||||
|
# 配额与备份根同属 backup.env;KB_BACKUP_ROOT 显式传入时仍要读到配额,所以单独取值。
|
||||||
|
layout_value() {
|
||||||
|
local key="$1"
|
||||||
|
[ -f "${KB_BACKUP_LAYOUT_ENV:-/etc/knowledge-governance/backup.env}" ] || return 0
|
||||||
|
sed -n "s/^[[:space:]]*${key}=//p" "${KB_BACKUP_LAYOUT_ENV:-/etc/knowledge-governance/backup.env}" \
|
||||||
|
| tail -1 | tr -d "\"' \r"
|
||||||
|
}
|
||||||
BACKUP_ROOT="${BACKUP_ROOT:-$KB_BACKUP_ROOT/rds-logical}"
|
BACKUP_ROOT="${BACKUP_ROOT:-$KB_BACKUP_ROOT/rds-logical}"
|
||||||
|
# 配额约束的是备份根(含 es-snapshots/target-kb-snapshots/logs),不是批次根。
|
||||||
|
# 若显式把 BACKUP_ROOT 指到别处,就以它的父目录为准,避免量错盘。
|
||||||
|
case "$BACKUP_ROOT" in
|
||||||
|
"$KB_BACKUP_ROOT"/*) QUOTA_ROOT="$KB_BACKUP_ROOT" ;;
|
||||||
|
*) QUOTA_ROOT="$(dirname "$BACKUP_ROOT")" ;;
|
||||||
|
esac
|
||||||
|
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-$(layout_value KB_BACKUP_QUOTA_BYTES)}"
|
||||||
|
QUOTA_BYTES="${QUOTA_BYTES:-53687091200}"
|
||||||
|
case "$QUOTA_BYTES" in
|
||||||
|
''|*[!0-9]*) echo "KB_BACKUP_QUOTA_BYTES 必须是正整数,收到 '$QUOTA_BYTES'" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
[ "$QUOTA_BYTES" -gt 0 ] || { echo "KB_BACKUP_QUOTA_BYTES 必须大于 0" >&2; exit 1; }
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
PRUNE_TOOL="$SCRIPT_DIR/prune_backup_batches.py"
|
||||||
APP_CONTAINER="${APP_CONTAINER:-weknora-test-v071-app-1}"
|
APP_CONTAINER="${APP_CONTAINER:-weknora-test-v071-app-1}"
|
||||||
PG_IMAGE="${PG_IMAGE:-postgres:17.9-alpine}"
|
PG_IMAGE="${PG_IMAGE:-postgres:17.9-alpine}"
|
||||||
JOBS="${JOBS:-4}"
|
JOBS="${JOBS:-4}"
|
||||||
@@ -49,6 +71,26 @@ DRY_RUN="${DRY_RUN:-0}"
|
|||||||
DBS="${DBS:-}"
|
DBS="${DBS:-}"
|
||||||
EXCLUDE_DBS="${EXCLUDE_DBS:-rdsadmin}"
|
EXCLUDE_DBS="${EXCLUDE_DBS:-rdsadmin}"
|
||||||
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||||
|
TARGET="$BACKUP_ROOT/$STAMP"
|
||||||
|
|
||||||
|
[ -f "$PRUNE_TOOL" ] || { echo "缺少配额清理工具:$PRUNE_TOOL(未开始备份)" >&2; exit 1; }
|
||||||
|
|
||||||
|
# 配额预检在 dump 之前、且不依赖 DB 凭据:失败时旧备份原样保留,也不会留下半成品目录。
|
||||||
|
# 预留量取最近一份完整批次大小;prune 内部保证「保留最新一份」和「不够就一个都不删」。
|
||||||
|
run_quota_prune() {
|
||||||
|
local label="$1"; shift
|
||||||
|
echo "-- 配额检查:$label --"
|
||||||
|
python3 "$PRUNE_TOOL" \
|
||||||
|
--backup-root "$QUOTA_ROOT" \
|
||||||
|
--batch-root "$BACKUP_ROOT" \
|
||||||
|
--quota-bytes "$QUOTA_BYTES" "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ "$DRY_RUN" = "1" ]; then
|
||||||
|
run_quota_prune "预检(DRY_RUN,只打印计划)" --estimate latest --keep-latest || true
|
||||||
|
echo "DRY_RUN=1,不执行"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
env_value() {
|
env_value() {
|
||||||
docker inspect "$APP_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' \
|
docker inspect "$APP_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' \
|
||||||
@@ -81,8 +123,6 @@ print(','.join(d for d in sys.argv[1].split(',') if d and d not in exclude))
|
|||||||
fi
|
fi
|
||||||
if [ -z "$DBS" ]; then echo "没有可备份的库" >&2; exit 1; fi
|
if [ -z "$DBS" ]; then echo "没有可备份的库" >&2; exit 1; fi
|
||||||
|
|
||||||
TARGET="$BACKUP_ROOT/$STAMP"
|
|
||||||
|
|
||||||
# 失败或被中断(含被 head/管道 SIGPIPE 杀掉):把目录显式标记为半成品,
|
# 失败或被中断(含被 head/管道 SIGPIPE 杀掉):把目录显式标记为半成品,
|
||||||
# 这样"最近一次备份"的选择器与人都不会把它误当成功结果。
|
# 这样"最近一次备份"的选择器与人都不会把它误当成功结果。
|
||||||
mark_incomplete() {
|
mark_incomplete() {
|
||||||
@@ -97,7 +137,18 @@ echo "备份目标: $TARGET"
|
|||||||
echo "库列表 : $DBS"
|
echo "库列表 : $DBS"
|
||||||
echo "镜像 : $PG_IMAGE (并行 $JOBS)"
|
echo "镜像 : $PG_IMAGE (并行 $JOBS)"
|
||||||
echo "保留策略: 每日 $KEEP_DAILY 份 / 每月 $KEEP_MONTHS 份"
|
echo "保留策略: 每日 $KEEP_DAILY 份 / 每月 $KEEP_MONTHS 份"
|
||||||
if [ "$DRY_RUN" = "1" ]; then echo "DRY_RUN=1,不执行"; exit 0; fi
|
echo "配额 : $QUOTA_BYTES 字节(备份根 $QUOTA_ROOT)"
|
||||||
|
|
||||||
|
# 真正删除旧批次放在凭据/库列表校验之后:连不上库时不应该先清历史备份。
|
||||||
|
if run_quota_prune "预检" --estimate latest --keep-latest --apply; then :; else
|
||||||
|
rc=$?
|
||||||
|
# rc=4 说明批次已改名隔离、真删阶段才失败,内容可能被部分删除 —— 不能再说「旧备份未被删除」。
|
||||||
|
case "$rc" in
|
||||||
|
4) echo "配额预检的删除阶段失败(rc=4):已隔离的批次可能已被部分删除(见上面的隔离路径),本次备份取消" >&2 ;;
|
||||||
|
*) echo "配额预检未通过(rc=$rc):本次备份取消,旧备份未被删除" >&2 ;;
|
||||||
|
esac
|
||||||
|
exit "$rc"
|
||||||
|
fi
|
||||||
|
|
||||||
mkdir -p "$TARGET"
|
mkdir -p "$TARGET"
|
||||||
STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
@@ -194,26 +245,23 @@ docker run --rm -v "$PWD:/backup" postgres:17.9-alpine \
|
|||||||
- 这份备份**不能替代按时间点恢复(PITR)**:它只能回到"备份那一刻"。
|
- 这份备份**不能替代按时间点恢复(PITR)**:它只能回到"备份那一刻"。
|
||||||
MD
|
MD
|
||||||
|
|
||||||
# 轮转:保留最近 KEEP_DAILY 份,另在最近 KEEP_MONTHS 个自然月各留一份
|
# 轮转:保留最近 KEEP_DAILY 份,另在最近 KEEP_MONTHS 个自然月各留一份。
|
||||||
python3 - "$BACKUP_ROOT" "$KEEP_DAILY" "$KEEP_MONTHS" <<'PY'
|
# 与配额清理共用同一份实现:删除前的 rename 预检、失败零删除回滚、只认完整批次,
|
||||||
import pathlib, re, shutil, sys
|
# 避免这里的内联 rmtree 又变成「先清空内容、再删目录失败」的第二条路径。
|
||||||
root = pathlib.Path(sys.argv[1]); keep_daily = int(sys.argv[2]); keep_months = int(sys.argv[3])
|
python3 "$PRUNE_TOOL" \
|
||||||
stamps = sorted([p for p in root.iterdir() if p.is_dir() and re.fullmatch(r"\d{8}T\d{6}Z", p.name)], reverse=True)
|
--backup-root "$QUOTA_ROOT" \
|
||||||
keep = {p.name for p in stamps[:keep_daily]}
|
--batch-root "$BACKUP_ROOT" \
|
||||||
months = []
|
--rotate --keep-daily "$KEEP_DAILY" --keep-months "$KEEP_MONTHS" --apply
|
||||||
for path in stamps:
|
|
||||||
month = path.name[:6]
|
# dump 后按实际占用复查:保护本次新批次,旧批次可删;仍超限则保留数据并告警。
|
||||||
if month not in months:
|
if run_quota_prune "dump 后复查" --estimate none --protect "$STAMP" --apply; then :; else
|
||||||
months.append(month)
|
rc=$?
|
||||||
keep.add(path.name)
|
case "$rc" in
|
||||||
if len(months) >= keep_months:
|
4) echo "本次备份已完成,但删除阶段失败(rc=4):见上面的隔离路径;新批次保留" >&2 ;;
|
||||||
break
|
*) echo "本次备份已完成,但配额仍超出(rc=$rc):新批次保留,请扩容或人工清理" >&2 ;;
|
||||||
for path in stamps:
|
esac
|
||||||
if path.name not in keep:
|
exit "$rc"
|
||||||
shutil.rmtree(path)
|
fi
|
||||||
print("rotated out:", path.name)
|
|
||||||
print("kept:", len([p for p in stamps if p.name in keep]))
|
|
||||||
PY
|
|
||||||
|
|
||||||
if [ -n "$FAILED_DBS" ]; then
|
if [ -n "$FAILED_DBS" ]; then
|
||||||
echo "done(有失败的库): $TARGET | failed: $FAILED_DBS" >&2
|
echo "done(有失败的库): $TARGET | failed: $FAILED_DBS" >&2
|
||||||
|
|||||||
Executable
+683
@@ -0,0 +1,683 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""按字节配额清理整库逻辑备份批次(宿主脚本,**只动平台自己的批次日录**)。
|
||||||
|
|
||||||
|
为什么单独成脚本:配额清理是唯一会删历史备份的动作,必须能离线、确定性地证明
|
||||||
|
「最旧优先、预检保留最新、空间仍不够时零删除、非批次日录不动」。塞进
|
||||||
|
logical-backup.sh 的内联 Python 只能靠跑 docker/psql 才能验证。
|
||||||
|
|
||||||
|
口径:占用用 `du -sB1 <备份根>`,与采集器声明的一致(0.1.408/0.1.409 的对拍口径)。
|
||||||
|
`du` 退出非 0(权限/IO 错误)⇒ 不清理、非 0 退出:绝不拿部分统计去删备份。
|
||||||
|
|
||||||
|
用法:
|
||||||
|
# 预检(dump 前):预留最近一份完整批次的大小,保留最新一份,不动就退出 3
|
||||||
|
python3 prune_backup_batches.py --backup-root /srv/kb-backups \
|
||||||
|
--quota-bytes 53687091200 --estimate latest --keep-latest --apply
|
||||||
|
|
||||||
|
# dump 后复查:保护本次新批次,其余旧批次可删
|
||||||
|
python3 prune_backup_batches.py --backup-root /srv/kb-backups \
|
||||||
|
--quota-bytes 53687091200 --estimate none --protect 20261125T033000Z --apply
|
||||||
|
|
||||||
|
删除为什么要分「预检 → 同父目录改名隔离 → 真删」三段:`shutil.rmtree` 先删子项、最后删
|
||||||
|
目录,父目录只读时失败发生在内容**已经清空之后**,调用方只看得到 rc≠0,旧备份却已经毁了
|
||||||
|
一半。rename 只要求父目录可写,能在删掉任何一个字节之前暴露这类问题;改名是原子的,任一
|
||||||
|
批次改名失败就把已挪动的批次全部挪回去,保证「失败 ⇒ 零删除」。
|
||||||
|
|
||||||
|
退出码:0 已满足配额(可能删了旧批次);2 du/路径错误,未删除;3 空间仍不够,未删除;
|
||||||
|
4 删除阶段失败(已隔离的批次可能被部分删除,报错退出并给出隔离路径);
|
||||||
|
5 删除前预检未通过,**零删除**。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
STAMP_NAME = re.compile(r"^\d{8}T\d{6}Z$")
|
||||||
|
# 隔离名不以 UTC 戳开头,因此不会被 candidates() 认成批次;同父目录下改名是原子操作。
|
||||||
|
QUARANTINE_PREFIX = ".prune-"
|
||||||
|
|
||||||
|
|
||||||
|
class QuotaError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class PrecheckRefused(QuotaError):
|
||||||
|
"""删除前预检未通过:一个字节都没删。"""
|
||||||
|
|
||||||
|
|
||||||
|
class DeleteFailed(QuotaError):
|
||||||
|
"""配额已提交(批次已改名隔离),但真删阶段失败:可能已有内容被删。"""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Candidate:
|
||||||
|
name: str
|
||||||
|
path: str
|
||||||
|
size: int
|
||||||
|
|
||||||
|
|
||||||
|
def measure(path: str) -> int:
|
||||||
|
"""`du -sB1` 的实际分配字节;失败即抛错(部分和不能用)。"""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["du", "-sB1", "--", path], capture_output=True, text=True, check=False
|
||||||
|
)
|
||||||
|
except OSError as error:
|
||||||
|
raise QuotaError(f"du 无法执行:{error}") from error
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise QuotaError(f"du 失败({path}):{(result.stderr or result.stdout).strip()[:300]}")
|
||||||
|
first = result.stdout.strip().splitlines()
|
||||||
|
if not first:
|
||||||
|
raise QuotaError(f"du 没有输出({path})")
|
||||||
|
try:
|
||||||
|
return int(first[0].split()[0])
|
||||||
|
except (IndexError, ValueError) as error:
|
||||||
|
raise QuotaError(f"du 输出无法解析({path}):{first[0]!r}") from error
|
||||||
|
|
||||||
|
|
||||||
|
def _is_regular_file(path: str) -> bool:
|
||||||
|
try:
|
||||||
|
info = os.lstat(path)
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
return not os.path.islink(path) and os.path.isfile(path)
|
||||||
|
|
||||||
|
|
||||||
|
def candidates(batch_root: str, measure_bytes=measure) -> list[Candidate]:
|
||||||
|
"""只认批次根的直接子目录:名字像 UTC 戳、不是符号链接、含常规 MANIFEST.json。
|
||||||
|
|
||||||
|
`*.incomplete` 名字不匹配,自然排除;符号链接不跟随(否则会删到别处)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
entries = list(os.scandir(batch_root))
|
||||||
|
except OSError as error:
|
||||||
|
raise QuotaError(f"批次根不可读({batch_root}):{error}") from error
|
||||||
|
found: list[Candidate] = []
|
||||||
|
for entry in entries:
|
||||||
|
if not STAMP_NAME.match(entry.name):
|
||||||
|
continue
|
||||||
|
if entry.is_symlink() or not entry.is_dir(follow_symlinks=False):
|
||||||
|
continue
|
||||||
|
if not _is_regular_file(os.path.join(entry.path, "MANIFEST.json")):
|
||||||
|
continue
|
||||||
|
found.append(Candidate(entry.name, entry.path, measure_bytes(entry.path)))
|
||||||
|
found.sort(key=lambda item: item.name)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def plan_deletions(
|
||||||
|
usage: int,
|
||||||
|
candidates_oldest_first: Iterable[Candidate],
|
||||||
|
quota: int,
|
||||||
|
estimate: int,
|
||||||
|
protect: set[str],
|
||||||
|
) -> tuple[list[Candidate], int, bool]:
|
||||||
|
"""返回(应删列表、删除后预计占用、是否仍超限)。
|
||||||
|
|
||||||
|
超出配额时从最旧开始删,直到「预计占用 + 预留」装得下;`protect` 里的批次永不删。
|
||||||
|
仍超限时调用方必须**一个都不删**(见 apply)。
|
||||||
|
"""
|
||||||
|
projected = usage
|
||||||
|
planned: list[Candidate] = []
|
||||||
|
for candidate in candidates_oldest_first:
|
||||||
|
if projected + estimate <= quota:
|
||||||
|
break
|
||||||
|
if candidate.name in protect:
|
||||||
|
continue
|
||||||
|
planned.append(candidate)
|
||||||
|
projected -= candidate.size
|
||||||
|
insufficient = projected + estimate > quota
|
||||||
|
return planned, projected, insufficient
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_estimate(value: str, candidates_oldest_first: list[Candidate]) -> int:
|
||||||
|
if value in ("", "none"):
|
||||||
|
return 0
|
||||||
|
if value == "latest":
|
||||||
|
if not candidates_oldest_first:
|
||||||
|
return 0
|
||||||
|
return candidates_oldest_first[-1].size
|
||||||
|
try:
|
||||||
|
number = int(value)
|
||||||
|
except ValueError as error:
|
||||||
|
raise QuotaError(f"--estimate 只接受 latest/none/字节数,收到 {value!r}") from error
|
||||||
|
if number < 0:
|
||||||
|
raise QuotaError("--estimate 不能为负数")
|
||||||
|
return number
|
||||||
|
|
||||||
|
|
||||||
|
def _tree_problems(path: str) -> list[str]:
|
||||||
|
"""列出会让 `rmtree` 中途失败的目录(只读、不可执行、挂载点)。
|
||||||
|
|
||||||
|
删一个子项要求它的**父目录**可写可执行,而不是文件本身;所以只看目录。挂载点要单独拒:
|
||||||
|
rmtree 会顺着删到另一个文件系统里去。
|
||||||
|
"""
|
||||||
|
problems: list[str] = []
|
||||||
|
if os.path.ismount(path):
|
||||||
|
return [f"{path} 是挂载点,拒绝删除"]
|
||||||
|
if not os.access(path, os.W_OK | os.X_OK):
|
||||||
|
return [f"{path} 不可写(rmtree 会先删完内容再删目录失败)"]
|
||||||
|
for current, _dirs, _files in os.walk(path, onerror=lambda err: problems.append(str(err))):
|
||||||
|
if os.path.ismount(current):
|
||||||
|
problems.append(f"{current} 是挂载点,拒绝删除")
|
||||||
|
elif not os.access(current, os.W_OK | os.X_OK):
|
||||||
|
problems.append(f"{current} 不可写")
|
||||||
|
return problems
|
||||||
|
|
||||||
|
|
||||||
|
def _rename_probe(path: str) -> None:
|
||||||
|
"""在同一个父目录里把批次改名再改回:验证「父目录可写」而不动任何内容。"""
|
||||||
|
batch_root = os.path.dirname(path)
|
||||||
|
probe = os.path.join(batch_root, f"{QUARANTINE_PREFIX}probe-{os.getpid()}-{os.path.basename(path)}")
|
||||||
|
os.rename(path, probe)
|
||||||
|
try:
|
||||||
|
os.rename(probe, path)
|
||||||
|
except OSError as error:
|
||||||
|
raise QuotaError(
|
||||||
|
f"批次 {os.path.basename(path)} 已改名为 {probe} 且改回失败(内容未删);"
|
||||||
|
f"请人工 mv 回原名:{error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
|
||||||
|
def delete_batches(
|
||||||
|
batch_root: str,
|
||||||
|
planned: list[Candidate],
|
||||||
|
tree_check=_tree_problems,
|
||||||
|
probe=_rename_probe,
|
||||||
|
rename=os.rename,
|
||||||
|
) -> list[str]:
|
||||||
|
"""预检通过才删;返回真正删掉的批次名。
|
||||||
|
|
||||||
|
预检覆盖两类失败:批次根不可写(改名探针)与批次内部有不可删目录(逐目录检查)。
|
||||||
|
提交点是「全部改名成功」——之后才真删,所以中途失败不会出现「一半删掉、一半还在」
|
||||||
|
的可见状态;改名失败则整体回滚,零删除。
|
||||||
|
"""
|
||||||
|
if not planned:
|
||||||
|
return []
|
||||||
|
problems: list[str] = []
|
||||||
|
for item in planned:
|
||||||
|
target = os.path.abspath(item.path)
|
||||||
|
if os.path.dirname(target) != batch_root:
|
||||||
|
raise QuotaError(f"拒绝删除批次根之外的路径:{target}")
|
||||||
|
if os.path.islink(target) or not os.path.isdir(target):
|
||||||
|
raise QuotaError(f"拒绝删除非目录或符号链接:{target}")
|
||||||
|
problems.extend(tree_check(target))
|
||||||
|
if not problems:
|
||||||
|
for item in planned:
|
||||||
|
try:
|
||||||
|
probe(item.path)
|
||||||
|
except OSError as error:
|
||||||
|
problems.append(
|
||||||
|
f"{item.path}: 无法在批次根内改名(父目录不可写?未删除任何内容):"
|
||||||
|
f"{error.strerror or error}"
|
||||||
|
)
|
||||||
|
break
|
||||||
|
if problems:
|
||||||
|
raise PrecheckRefused("删除前预检未通过,未删除任何批次:" + ";".join(problems))
|
||||||
|
|
||||||
|
quarantined: list[tuple[Candidate, str]] = []
|
||||||
|
try:
|
||||||
|
for item in planned:
|
||||||
|
target = os.path.join(batch_root, f"{QUARANTINE_PREFIX}{os.getpid()}-{item.name}")
|
||||||
|
if os.path.lexists(target):
|
||||||
|
raise OSError(f"隔离路径已存在:{target}")
|
||||||
|
rename(item.path, target)
|
||||||
|
quarantined.append((item, target))
|
||||||
|
except OSError as error:
|
||||||
|
for item, target in reversed(quarantined):
|
||||||
|
try:
|
||||||
|
rename(target, item.path)
|
||||||
|
except OSError as undo_error:
|
||||||
|
raise DeleteFailed(
|
||||||
|
f"回滚失败:批次 {item.name} 停在 {target}(内容未删);请人工 mv 回原名:{undo_error}"
|
||||||
|
) from error
|
||||||
|
raise PrecheckRefused(
|
||||||
|
f"隔离改名失败({error}),已把 {[item.name for item, _ in quarantined]} 改回原名,未删除任何批次"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
deleted: list[str] = []
|
||||||
|
failures: list[str] = []
|
||||||
|
for item, target in quarantined:
|
||||||
|
try:
|
||||||
|
shutil.rmtree(target)
|
||||||
|
except OSError as error:
|
||||||
|
failures.append(f"{item.name}(隔离在 {target},内容可能已被部分删除):{error}")
|
||||||
|
continue
|
||||||
|
deleted.append(item.name)
|
||||||
|
if failures:
|
||||||
|
raise DeleteFailed("删除阶段失败:" + ";".join(failures))
|
||||||
|
return deleted
|
||||||
|
|
||||||
|
|
||||||
|
def plan_rotation(
|
||||||
|
candidates_oldest_first: list[Candidate], keep_daily: int, keep_months: int
|
||||||
|
) -> list[Candidate]:
|
||||||
|
"""保留最近 keep_daily 份 + 最近 keep_months 个自然月各一份,其余待删。"""
|
||||||
|
newest_first = list(reversed(candidates_oldest_first))
|
||||||
|
keep = {item.name for item in newest_first[: max(keep_daily, 0)]}
|
||||||
|
months: list[str] = []
|
||||||
|
for item in newest_first:
|
||||||
|
month = item.name[:6]
|
||||||
|
if month not in months:
|
||||||
|
months.append(month)
|
||||||
|
keep.add(item.name)
|
||||||
|
if len(months) >= keep_months:
|
||||||
|
break
|
||||||
|
return [item for item in candidates_oldest_first if item.name not in keep]
|
||||||
|
|
||||||
|
|
||||||
|
def stale_quarantine(batch_root: str) -> list[str]:
|
||||||
|
"""上次删到一半留下的隔离目录:不认成批次,但要报出来让人决定恢复还是清掉。"""
|
||||||
|
try:
|
||||||
|
entries = list(os.scandir(batch_root))
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
return sorted(
|
||||||
|
entry.name
|
||||||
|
for entry in entries
|
||||||
|
if entry.name.startswith(QUARANTINE_PREFIX) and entry.is_dir(follow_symlinks=False)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def rotate(
|
||||||
|
backup_root: str,
|
||||||
|
batch_root: str,
|
||||||
|
keep_daily: int,
|
||||||
|
keep_months: int,
|
||||||
|
apply: bool,
|
||||||
|
measure_bytes=measure,
|
||||||
|
) -> dict:
|
||||||
|
backup_root = os.path.abspath(backup_root)
|
||||||
|
batch_root = os.path.abspath(batch_root)
|
||||||
|
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
|
||||||
|
raise QuotaError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
|
||||||
|
found = candidates(batch_root, measure_bytes)
|
||||||
|
planned = plan_rotation(found, keep_daily, keep_months)
|
||||||
|
result = {
|
||||||
|
"mode": "rotate",
|
||||||
|
"backup_root": backup_root,
|
||||||
|
"batch_root": batch_root,
|
||||||
|
"keep_daily": keep_daily,
|
||||||
|
"keep_months": keep_months,
|
||||||
|
"kept": len(found) - len(planned),
|
||||||
|
"plan": [item.name for item in planned],
|
||||||
|
"deleted": [],
|
||||||
|
"stale_quarantine": stale_quarantine(batch_root),
|
||||||
|
"applied": False,
|
||||||
|
}
|
||||||
|
if apply:
|
||||||
|
result["deleted"] = delete_batches(batch_root, planned)
|
||||||
|
result["applied"] = True
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def prune(
|
||||||
|
backup_root: str,
|
||||||
|
batch_root: str,
|
||||||
|
quota: int,
|
||||||
|
estimate: int,
|
||||||
|
protect: set[str],
|
||||||
|
keep_latest: bool,
|
||||||
|
apply: bool,
|
||||||
|
measure_bytes=measure,
|
||||||
|
) -> dict:
|
||||||
|
if quota <= 0:
|
||||||
|
raise QuotaError("--quota-bytes 必须是正整数")
|
||||||
|
backup_root = os.path.abspath(backup_root)
|
||||||
|
batch_root = os.path.abspath(batch_root)
|
||||||
|
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
|
||||||
|
raise QuotaError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
|
||||||
|
found = candidates(batch_root, measure_bytes)
|
||||||
|
usage = measure_bytes(backup_root)
|
||||||
|
protected = set(protect)
|
||||||
|
if keep_latest and found:
|
||||||
|
protected.add(found[-1].name)
|
||||||
|
planned, projected, insufficient = plan_deletions(usage, found, quota, estimate, protected)
|
||||||
|
result = {
|
||||||
|
"backup_root": backup_root,
|
||||||
|
"batch_root": batch_root,
|
||||||
|
"quota_bytes": quota,
|
||||||
|
"usage_bytes": usage,
|
||||||
|
"estimate_bytes": estimate,
|
||||||
|
"projected_bytes": projected,
|
||||||
|
"protected": sorted(protected),
|
||||||
|
"plan": [item.name for item in planned],
|
||||||
|
"insufficient": insufficient,
|
||||||
|
"deleted": [],
|
||||||
|
"stale_quarantine": stale_quarantine(batch_root),
|
||||||
|
"applied": False,
|
||||||
|
}
|
||||||
|
if insufficient:
|
||||||
|
return result
|
||||||
|
if not apply:
|
||||||
|
return result
|
||||||
|
result["deleted"] = delete_batches(batch_root, planned)
|
||||||
|
result["applied"] = True
|
||||||
|
result["usage_after_bytes"] = measure_bytes(backup_root)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _self_test_quota() -> None:
|
||||||
|
base = tempfile.mkdtemp(prefix="backup-quota-test-")
|
||||||
|
try:
|
||||||
|
root = os.path.join(base, "kb-backups")
|
||||||
|
batch_root = os.path.join(root, "rds-logical")
|
||||||
|
os.makedirs(batch_root)
|
||||||
|
es_dir = os.path.join(root, "es-snapshots")
|
||||||
|
os.makedirs(es_dir)
|
||||||
|
with open(os.path.join(es_dir, "index-0"), "wb") as handle:
|
||||||
|
handle.write(b"e" * 8192)
|
||||||
|
|
||||||
|
def make_batch(stamp: str, kib: int) -> str:
|
||||||
|
path = os.path.join(batch_root, stamp)
|
||||||
|
db = os.path.join(path, "weknora.dir")
|
||||||
|
os.makedirs(db)
|
||||||
|
with open(os.path.join(db, "toc.dat"), "wb") as handle:
|
||||||
|
handle.write(b"x" * (kib * 1024))
|
||||||
|
with open(os.path.join(path, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||||
|
handle.write('{"databases":["weknora"]}')
|
||||||
|
return path
|
||||||
|
|
||||||
|
stamps = ["20261101T030000Z", "20261102T030000Z", "20261103T030000Z", "20261104T030000Z"]
|
||||||
|
paths = [make_batch(stamp, 256) for stamp in stamps]
|
||||||
|
# 非批次日录、半成品、指向别处的符号链接都不能进候选/被删。
|
||||||
|
os.makedirs(os.path.join(root, "logs"))
|
||||||
|
with open(os.path.join(root, "logs", "logical-backup.log"), "wb") as handle:
|
||||||
|
handle.write(b"l" * 4096)
|
||||||
|
os.makedirs(os.path.join(batch_root, "notes"))
|
||||||
|
with open(os.path.join(batch_root, "notes", "keep.txt"), "wb") as handle:
|
||||||
|
handle.write(b"n" * 1024)
|
||||||
|
os.makedirs(os.path.join(batch_root, "20261105T030000Z.incomplete"))
|
||||||
|
outside = os.path.join(base, "outside")
|
||||||
|
os.makedirs(outside)
|
||||||
|
with open(os.path.join(outside, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||||
|
handle.write("{}")
|
||||||
|
os.symlink(outside, os.path.join(batch_root, "20261106T030000Z"))
|
||||||
|
|
||||||
|
found = candidates(batch_root)
|
||||||
|
assert [item.name for item in found] == stamps, found
|
||||||
|
usage = measure(root)
|
||||||
|
assert usage > sum(item.size for item in found)
|
||||||
|
newest_size = found[-1].size
|
||||||
|
|
||||||
|
# 1) 预检:需要腾出空间时从最旧删,最新一份永不在计划里。
|
||||||
|
estimate = newest_size
|
||||||
|
quota = usage - found[0].size + estimate
|
||||||
|
planned, projected, insufficient = plan_deletions(
|
||||||
|
usage, found, quota, estimate, {found[-1].name}
|
||||||
|
)
|
||||||
|
assert not insufficient
|
||||||
|
assert [item.name for item in planned] == [found[0].name], planned
|
||||||
|
assert all(item.name != found[-1].name for item in planned)
|
||||||
|
assert projected + estimate <= quota
|
||||||
|
|
||||||
|
# 2) 空间仍不够:一个都不删,目录全部还在。
|
||||||
|
too_tight = max(1, estimate)
|
||||||
|
result = prune(
|
||||||
|
root, batch_root, too_tight, estimate, set(), keep_latest=True, apply=True
|
||||||
|
)
|
||||||
|
assert result["insufficient"] is True and result["applied"] is False, result
|
||||||
|
assert all(os.path.isdir(path) for path in paths)
|
||||||
|
assert os.path.isdir(os.path.join(batch_root, "notes"))
|
||||||
|
assert os.path.isdir(os.path.join(root, "logs"))
|
||||||
|
assert os.path.isdir(os.path.join(root, "es-snapshots"))
|
||||||
|
|
||||||
|
# 3) dump 后:保护新批次,允许删上一份最新;只删计划内、非批次日录不动。
|
||||||
|
new_stamp = "20261109T030000Z"
|
||||||
|
new_path = make_batch(new_stamp, 256)
|
||||||
|
after_usage = measure(root)
|
||||||
|
protect = {new_stamp}
|
||||||
|
result = prune(
|
||||||
|
root,
|
||||||
|
batch_root,
|
||||||
|
after_usage - found[0].size,
|
||||||
|
0,
|
||||||
|
protect,
|
||||||
|
keep_latest=False,
|
||||||
|
apply=True,
|
||||||
|
)
|
||||||
|
assert result["applied"] is True and result["plan"] == [found[0].name], result
|
||||||
|
assert not os.path.exists(found[0].path)
|
||||||
|
assert os.path.isdir(new_path)
|
||||||
|
assert os.path.isdir(found[-1].path)
|
||||||
|
assert os.path.isdir(os.path.join(batch_root, "notes"))
|
||||||
|
assert os.path.isdir(os.path.join(batch_root, "20261105T030000Z.incomplete"))
|
||||||
|
assert os.path.isdir(os.path.join(root, "es-snapshots"))
|
||||||
|
|
||||||
|
# 4) 测量失败必须零删除:注入抛错的 measure。
|
||||||
|
def broken(_path: str) -> int:
|
||||||
|
raise QuotaError("du 失败(注入)")
|
||||||
|
|
||||||
|
try:
|
||||||
|
prune(root, batch_root, 1, 0, set(), keep_latest=True, apply=True, measure_bytes=broken)
|
||||||
|
except QuotaError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("测量失败必须中止")
|
||||||
|
assert os.path.isdir(found[-1].path)
|
||||||
|
|
||||||
|
# 5) 批次根逃逸必须拒绝。
|
||||||
|
try:
|
||||||
|
prune(root, os.path.join(base, "outside"), 1 << 40, 0, set(), True, True)
|
||||||
|
except QuotaError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("批次根不在备份根下必须拒绝")
|
||||||
|
|
||||||
|
print("prune_backup_batches self-test ok")
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(base, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _self_test_delete_safety() -> None:
|
||||||
|
"""删除安全网:预检拒绝零删除、改名失败整体回滚、轮转、隔离目录不进候选。"""
|
||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
|
||||||
|
base = tempfile.mkdtemp(prefix="backup-quota-delete-test-")
|
||||||
|
try:
|
||||||
|
root = os.path.join(base, "kb-backups")
|
||||||
|
batch_root = os.path.join(root, "rds-logical")
|
||||||
|
os.makedirs(batch_root)
|
||||||
|
|
||||||
|
def make_batch(stamp: str, kib: int) -> str:
|
||||||
|
path = os.path.join(batch_root, stamp)
|
||||||
|
os.makedirs(os.path.join(path, "weknora.dir"))
|
||||||
|
with open(os.path.join(path, "weknora.dir", "180000.dat.gz"), "wb") as handle:
|
||||||
|
handle.write(b"x" * (kib * 1024))
|
||||||
|
with open(os.path.join(path, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||||
|
handle.write('{"databases":["weknora"]}')
|
||||||
|
return path
|
||||||
|
|
||||||
|
stamps = ["20261201T030000Z", "20261215T030000Z", "20270101T030000Z", "20270115T030000Z"]
|
||||||
|
paths = [make_batch(stamp, 128) for stamp in stamps]
|
||||||
|
found = candidates(batch_root)
|
||||||
|
|
||||||
|
def sizes() -> dict[str, int]:
|
||||||
|
return {path: measure(path) for path in paths}
|
||||||
|
|
||||||
|
before = sizes()
|
||||||
|
# 1) 预检报告问题时一个都不删(旧实现会先 rmtree 掉第一批再失败)。
|
||||||
|
for inject in ({"tree_check": lambda _path: ["注入:目录不可写"]},
|
||||||
|
{"probe": _refuse_probe}):
|
||||||
|
try:
|
||||||
|
delete_batches(batch_root, found[:2], **inject)
|
||||||
|
except PrecheckRefused:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("预检拒绝时不得删除")
|
||||||
|
assert sizes() == before, (inject, sizes())
|
||||||
|
assert all(os.path.exists(path) for path in paths)
|
||||||
|
|
||||||
|
# 2) 改名提交阶段失败:已挪动的批次必须改回原名,零删除。
|
||||||
|
calls = {"n": 0}
|
||||||
|
real_rename = os.rename
|
||||||
|
|
||||||
|
def flaky_rename(src, dst):
|
||||||
|
calls["n"] += 1
|
||||||
|
if calls["n"] == 2:
|
||||||
|
raise OSError("注入:改名失败")
|
||||||
|
return real_rename(src, dst)
|
||||||
|
|
||||||
|
try:
|
||||||
|
delete_batches(batch_root, found[:2], rename=flaky_rename)
|
||||||
|
except PrecheckRefused:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("改名失败必须整体回滚")
|
||||||
|
assert sorted(os.listdir(batch_root)) == stamps, os.listdir(batch_root)
|
||||||
|
assert sizes() == before
|
||||||
|
|
||||||
|
# 3) 真删只在预检通过后发生,并且只删计划内批次。
|
||||||
|
deleted = delete_batches(batch_root, found[:2])
|
||||||
|
assert deleted == [stamps[0], stamps[1]], deleted
|
||||||
|
assert sorted(os.listdir(batch_root)) == stamps[2:], os.listdir(batch_root)
|
||||||
|
assert os.path.isdir(paths[2]) and os.path.isdir(paths[3])
|
||||||
|
|
||||||
|
# 4) 只读批次根(root 下 os.access 恒为真,跳过)。
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
quota = measure(root) - measure(paths[2])
|
||||||
|
os.chmod(batch_root, 0o555)
|
||||||
|
try:
|
||||||
|
buffer = io.StringIO()
|
||||||
|
with contextlib.redirect_stderr(buffer):
|
||||||
|
code = main([
|
||||||
|
"--backup-root", root, "--batch-root", batch_root,
|
||||||
|
"--quota-bytes", str(quota), "--estimate", "none", "--apply",
|
||||||
|
])
|
||||||
|
assert code == 5, (code, buffer.getvalue())
|
||||||
|
assert "预检未通过" in buffer.getvalue(), buffer.getvalue()
|
||||||
|
finally:
|
||||||
|
os.chmod(batch_root, 0o755)
|
||||||
|
assert sorted(os.listdir(batch_root)) == stamps[2:], os.listdir(batch_root)
|
||||||
|
assert measure(paths[2]) > 0 and measure(paths[3]) > 0
|
||||||
|
|
||||||
|
# 5) 轮转:保留最近 keep_daily 份 + 最近 keep_months 个自然月各一份。
|
||||||
|
for stamp in ["20270201T030000Z", "20270215T030000Z"]:
|
||||||
|
make_batch(stamp, 128)
|
||||||
|
rotated = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=False)
|
||||||
|
assert rotated["plan"] == ["20270101T030000Z"], rotated
|
||||||
|
assert rotated["kept"] == 3, rotated
|
||||||
|
rotated = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=True)
|
||||||
|
assert rotated["deleted"] == ["20270101T030000Z"], rotated
|
||||||
|
assert sorted(os.listdir(batch_root)) == ["20270115T030000Z", "20270201T030000Z", "20270215T030000Z"], os.listdir(batch_root)
|
||||||
|
|
||||||
|
# 6) 上次失败留下的隔离目录:不算批次、不被当垃圾清掉、要报出来。
|
||||||
|
stale = os.path.join(batch_root, f"{QUARANTINE_PREFIX}999-20270101T030000Z")
|
||||||
|
os.makedirs(os.path.join(stale, "weknora.dir"))
|
||||||
|
with open(os.path.join(stale, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||||
|
handle.write("{}")
|
||||||
|
assert [item.name for item in candidates(batch_root)] == [
|
||||||
|
"20270115T030000Z", "20270201T030000Z", "20270215T030000Z"
|
||||||
|
]
|
||||||
|
result = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=True)
|
||||||
|
assert result["stale_quarantine"] == [os.path.basename(stale)], result
|
||||||
|
assert os.path.isdir(stale), "隔离目录不能自动删"
|
||||||
|
|
||||||
|
print("prune delete-safety self-test ok")
|
||||||
|
finally:
|
||||||
|
for current, dirs, _files in os.walk(base):
|
||||||
|
for name in dirs:
|
||||||
|
os.chmod(os.path.join(current, name), 0o755)
|
||||||
|
shutil.rmtree(base, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _refuse_probe(_path: str) -> None:
|
||||||
|
raise OSError("注入:改名预检失败")
|
||||||
|
|
||||||
|
|
||||||
|
def _self_test() -> None:
|
||||||
|
_self_test_quota()
|
||||||
|
_self_test_delete_safety()
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="按字节配额清理整库备份批次")
|
||||||
|
parser.add_argument("--backup-root", default="", help="备份根(默认 backup.env 的 KB_BACKUP_ROOT)")
|
||||||
|
parser.add_argument("--batch-root", default="", help="批次日录根(默认 <备份根>/rds-logical)")
|
||||||
|
parser.add_argument("--quota-bytes", type=int, default=0)
|
||||||
|
parser.add_argument("--estimate", default="none", help="新批次预留:latest / none / 字节数")
|
||||||
|
parser.add_argument("--protect", action="append", default=[], help="永不删除的批次戳(可重复)")
|
||||||
|
parser.add_argument("--keep-latest", action="store_true", help="预检模式:保留最新一份完整批次")
|
||||||
|
parser.add_argument("--apply", action="store_true", help="真的删除;缺省只打印计划")
|
||||||
|
parser.add_argument("--rotate", action="store_true", help="按份数/月份轮转(忽略配额)")
|
||||||
|
parser.add_argument("--keep-daily", type=int, default=7, help="轮转:保留最近几份")
|
||||||
|
parser.add_argument("--keep-months", type=int, default=3, help="轮转:额外保留最近几个自然月各一份")
|
||||||
|
parser.add_argument("--json", action="store_true")
|
||||||
|
parser.add_argument("--self-test", action="store_true")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
if args.self_test:
|
||||||
|
_self_test()
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
backup_root = args.backup_root or os.environ.get("KB_BACKUP_ROOT", "") or "/srv/kb-backups"
|
||||||
|
batch_root = args.batch_root or os.path.join(backup_root, "rds-logical")
|
||||||
|
if args.rotate:
|
||||||
|
result = rotate(
|
||||||
|
backup_root,
|
||||||
|
batch_root,
|
||||||
|
args.keep_daily,
|
||||||
|
args.keep_months,
|
||||||
|
args.apply,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
found = candidates(batch_root)
|
||||||
|
estimate = resolve_estimate(args.estimate, found)
|
||||||
|
result = prune(
|
||||||
|
backup_root,
|
||||||
|
batch_root,
|
||||||
|
args.quota_bytes,
|
||||||
|
estimate,
|
||||||
|
set(args.protect),
|
||||||
|
args.keep_latest,
|
||||||
|
args.apply,
|
||||||
|
)
|
||||||
|
except PrecheckRefused as error:
|
||||||
|
print(f"quota prune refused: {error}", file=sys.stderr)
|
||||||
|
return 5
|
||||||
|
except DeleteFailed as error:
|
||||||
|
print(f"quota prune failed: {error}", file=sys.stderr)
|
||||||
|
return 4
|
||||||
|
except QuotaError as error:
|
||||||
|
print(f"quota prune failed: {error}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
if args.json:
|
||||||
|
import json
|
||||||
|
|
||||||
|
print(json.dumps(result, ensure_ascii=False))
|
||||||
|
elif args.rotate:
|
||||||
|
print(f"保留 {result['kept']} 份(每日 {result['keep_daily']} / 每月 {result['keep_months']})")
|
||||||
|
if result["applied"]:
|
||||||
|
for name in result["deleted"]:
|
||||||
|
print("rotated out:", name)
|
||||||
|
else:
|
||||||
|
print("待删:" + ("、".join(result["plan"]) if result["plan"] else "无"))
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f"备份占用 {result['usage_bytes']} / 配额 {result['quota_bytes']}"
|
||||||
|
f"(预留 {result['estimate_bytes']},保护 {result['protected'] or '无'})"
|
||||||
|
)
|
||||||
|
print("删除计划:" + ("、".join(result["plan"]) if result["plan"] else "无"))
|
||||||
|
if result["insufficient"]:
|
||||||
|
print("空间仍不够:未删除任何批次", file=sys.stderr)
|
||||||
|
elif result["applied"]:
|
||||||
|
print(f"已删除 {len(result['deleted'])} 个批次,占用 {result['usage_after_bytes']}")
|
||||||
|
if result.get("stale_quarantine"):
|
||||||
|
print(
|
||||||
|
"注意:发现上次删除失败留下的隔离目录(内容可能不完整,未计入批次):"
|
||||||
|
+ "、".join(result["stale_quarantine"]),
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
if result.get("insufficient"):
|
||||||
|
return 3
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Prepare candidate QA reports from a case list and per-case evidence."""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
POLICY = 'KG-QA-REPORT/v1'
|
||||||
|
STATES = ('passed', 'failed', 'blocked')
|
||||||
|
|
||||||
|
|
||||||
|
def require(condition, message):
|
||||||
|
if not condition:
|
||||||
|
raise ValueError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(plan, results, host):
|
||||||
|
require(isinstance(plan, dict), '缺少原用例清单')
|
||||||
|
ids = []
|
||||||
|
for group in ('business', 'regression'):
|
||||||
|
group_ids = plan.get(group)
|
||||||
|
require(isinstance(group_ids, list) and group_ids, f'缺少 {group} 用例编号')
|
||||||
|
for case_id in group_ids:
|
||||||
|
require(isinstance(case_id, str) and case_id.strip() == case_id and case_id, '存在空用例编号')
|
||||||
|
require(case_id not in ids, f'重复编号 {case_id}')
|
||||||
|
ids.append(case_id)
|
||||||
|
require(isinstance(results, dict), '缺少逐项结果')
|
||||||
|
extras = set(results) - set(ids)
|
||||||
|
require(not extras, '清单外编号 ' + ', '.join(sorted(extras)))
|
||||||
|
counts = dict.fromkeys(STATES, 0)
|
||||||
|
missing = []
|
||||||
|
for case_id in ids:
|
||||||
|
entry = results.get(case_id)
|
||||||
|
if not valid_entry(entry):
|
||||||
|
missing.append(case_id)
|
||||||
|
else:
|
||||||
|
counts[entry['status']] += 1
|
||||||
|
require(not missing, '请填写结果和证据:' + ', '.join(missing))
|
||||||
|
require(valid_entry(host), '请填写正式候选环境的实测结果和证据,无法登录请填 blocked')
|
||||||
|
states = {host['status']} | {k for k, count in counts.items() if count}
|
||||||
|
verdict = 'failed' if 'failed' in states else 'blocked' if 'blocked' in states else 'passed'
|
||||||
|
return dict(cases=plan, results=results, candidate_check=host, required=len(ids), verdict=verdict, **counts)
|
||||||
|
|
||||||
|
|
||||||
|
def valid_entry(entry):
|
||||||
|
return (isinstance(entry, dict) and entry.get('status') in STATES
|
||||||
|
and isinstance(entry.get('evidence'), str) and bool(entry['evidence'].strip()))
|
||||||
|
|
||||||
|
|
||||||
|
def verify_report(report):
|
||||||
|
expected = summarize(report.get('cases'), report.get('results'), report.get('candidate_check'))
|
||||||
|
for key, value in expected.items():
|
||||||
|
require(type(report.get(key)) is type(value) and report[key] == value, f'报告字段 {key} 与逐项结果不一致')
|
||||||
|
|
||||||
|
|
||||||
|
def cli(*args, body=None):
|
||||||
|
program = shutil.which('hifox') or str(Path.home() / '.local/bin/hifox')
|
||||||
|
output = subprocess.check_output([program, *args, '--output', 'json'], input=body, text=True, timeout=45)
|
||||||
|
return json.loads(output)
|
||||||
|
|
||||||
|
|
||||||
|
def ready(rows):
|
||||||
|
candidates = sorted((r for r in rows if r['content'].startswith('[KG candidate ready ')
|
||||||
|
and (r.get('author') or {}).get('id') == '39ae59fb-876c-4587-ab5d-a12a841c6c09'),
|
||||||
|
key=lambda r: r['createdAt'])
|
||||||
|
require(candidates, '原单缺少候选就绪回执')
|
||||||
|
row = candidates[-1]
|
||||||
|
text = row['content']
|
||||||
|
def field(pattern):
|
||||||
|
match = re.search(pattern, text, re.M)
|
||||||
|
require(match is not None, '候选回执字段不完整')
|
||||||
|
return match[1]
|
||||||
|
bundle = field(r'^归档 `([0-9a-f]{64})`$')
|
||||||
|
require(text.startswith('[KG candidate ready ' + bundle + ']'), '候选归档不一致')
|
||||||
|
return dict(task=row['taskId'], ready=row['id'], url=field(r'^候选验收地址 (https?://\S+)$'),
|
||||||
|
sha=field(r'^提交 `([0-9a-f]{40})`$'), bundle=bundle), field(r'用 ([\w.-]+) 代码块回填')
|
||||||
|
|
||||||
|
|
||||||
|
def load(path):
|
||||||
|
return json.loads(Path(path).read_text())
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('action', choices=['init', 'check', 'submit'])
|
||||||
|
parser.add_argument('task')
|
||||||
|
parser.add_argument('plan', help='原用例清单 JSON,含 business、regression 编号数组')
|
||||||
|
parser.add_argument('sheet', help='逐项填写的结果文件')
|
||||||
|
args = parser.parse_args()
|
||||||
|
task = cli('task', 'view', args.task)
|
||||||
|
def comments():
|
||||||
|
return cli('task', 'comment', 'list', task['id'], '--limit', '0')
|
||||||
|
rows = comments()
|
||||||
|
receipt, fence = ready(rows)
|
||||||
|
require(receipt['task'] == task['id'], '回执不属于本需求')
|
||||||
|
plan = load(args.plan)
|
||||||
|
fingerprint = hashlib.sha256(json.dumps(plan, sort_keys=True).encode()).hexdigest()
|
||||||
|
if args.action == 'init':
|
||||||
|
blank = {'status': '', 'evidence': ''}
|
||||||
|
ids = [k for group in ('business', 'regression') for k in plan[group]]
|
||||||
|
skeleton = dict(receipt=receipt, plan_digest=fingerprint, candidate_check=blank,
|
||||||
|
results={k: blank for k in ids})
|
||||||
|
with Path(args.sheet).open('x') as stream:
|
||||||
|
json.dump(skeleton, stream, indent=2, ensure_ascii=False)
|
||||||
|
return
|
||||||
|
sheet = load(args.sheet)
|
||||||
|
require(sheet['receipt'] == receipt, '候选版本已变化,请为新候选准备结果清单')
|
||||||
|
require(sheet['plan_digest'] == fingerprint, '原用例清单已变化,请核对用例范围')
|
||||||
|
report = dict(**receipt, **summarize(plan, sheet['results'], sheet['candidate_check']))
|
||||||
|
verify_report(report)
|
||||||
|
payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2)
|
||||||
|
require('```' not in payload, '证据请填写简短结论或附件名,避免嵌套代码围栏')
|
||||||
|
text = f'{POLICY} 候选实测结果 {report["verdict"]}\n\n```{fence}\n{payload}\n```'
|
||||||
|
if args.action == 'check':
|
||||||
|
print(text)
|
||||||
|
return
|
||||||
|
qa_authors = {'62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
|
||||||
|
def existing(rows):
|
||||||
|
return next((r for r in rows if r['content'] == text and (r.get('author') or {}).get('id') in qa_authors), None)
|
||||||
|
found = existing(rows)
|
||||||
|
if not found:
|
||||||
|
# The child CLI inherits the QA session's identity. Never replace it with an operator login.
|
||||||
|
cli('task', 'comment', task['id'], '--body-stdin', body=text)
|
||||||
|
found = existing(comments())
|
||||||
|
if found is None:
|
||||||
|
raise ValueError('请在原单核对评论及 QA 署名后再决定是否重试')
|
||||||
|
print(found['id'])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except (OSError, KeyError, TypeError, ValueError, subprocess.SubprocessError) as error:
|
||||||
|
sys.exit(f'QA 报告:{error}')
|
||||||
@@ -30,15 +30,23 @@ def author(row):
|
|||||||
return (row.get('author') or {}).get('id')
|
return (row.get('author') or {}).get('id')
|
||||||
|
|
||||||
|
|
||||||
|
def reviewer_comments(task, rows):
|
||||||
|
return sorted((row for row in rows if author(row) == WHITE and row.get('taskId') == task['id']),
|
||||||
|
key=lambda row: row['createdAt'], reverse=True)
|
||||||
|
|
||||||
|
|
||||||
def review_identity(task, rows, event):
|
def review_identity(task, rows, event):
|
||||||
reviews = sorted((r for r in rows if author(r) == WHITE and r.get('taskId') == task['id']
|
reviews = reviewer_comments(task, rows)
|
||||||
and r['content'].startswith('🚦')), key=lambda r: r['createdAt'], reverse=True)
|
|
||||||
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
|
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
|
||||||
review = reviews[0]
|
review = reviews[0]
|
||||||
cd.require(review['content'].startswith('🚦 可测试 ✅') and f"mention://task/{task['id']}" in review['content'].splitlines()[0],
|
header = review['content'].partition('\n')[0]
|
||||||
|
verdict = re.match(r'^[🚦✅\s*]*可测试(?=$|[\s✅||((,,::。*])', header)
|
||||||
|
mentions = re.findall(r'mention://task/([\w-]+)', header)
|
||||||
|
cd.require(verdict and (not mentions or mentions == [task['id']]),
|
||||||
'preflight is not a passing verdict for this task')
|
'preflight is not a passing verdict for this task')
|
||||||
hashes = set(re.findall(r'落地\s*(?:(merge))?\s*`([0-9a-f]{7,40})`', review['content']))
|
hashes = set(re.findall(r'落地[^\S\r\n]*(?:(merge)|merge|合并)?[^\S\r\n]*`([0-9a-f]{7,40})`', review['content']))
|
||||||
cd.require(len(hashes) == 1, 'preflight needs an unambiguous landed commit')
|
cd.require(hashes, 'preflight missing landed commit marker')
|
||||||
|
cd.require(len(hashes) == 1, 'preflight contains multiple landed commits')
|
||||||
short = hashes.pop()
|
short = hashes.pop()
|
||||||
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
|
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
|
||||||
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
|
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
|
||||||
@@ -89,6 +97,27 @@ def frozen_approval(task_id, comment_id=None):
|
|||||||
|
|
||||||
|
|
||||||
def preflight(task, event=None):
|
def preflight(task, event=None):
|
||||||
|
"""Persist the task's verified review before trying the shared QA environment."""
|
||||||
|
sha, _ = resolve(task, event)
|
||||||
|
if event is None:
|
||||||
|
reviews = reviewer_comments(task, comments(task['id']))
|
||||||
|
cd.require(reviews, 'require latest preflight from 白小浅')
|
||||||
|
event = reviews[0]['id']
|
||||||
|
cd.require(resolve(task, event)[0] == sha, 'preflight changed during recovery')
|
||||||
|
waiting = coordinator.STATE / 'waiting'
|
||||||
|
waiting.mkdir(mode=0o700, exist_ok=True, parents=True)
|
||||||
|
path = waiting / (event + '.json')
|
||||||
|
with cd.deploy_lock(waiting / 'queue.lock'):
|
||||||
|
if not path.exists():
|
||||||
|
cd.record(path, {'task': task['id'], 'event': event, 'sha': sha, 'state': 'waiting_for_slot'})
|
||||||
|
entry = cd.read_json(cd.immutable_file(path))
|
||||||
|
cd.require(entry['task'] == task['id'] and entry['sha'] == sha, 'queue entry identity changed')
|
||||||
|
if entry['state'] == 'waiting_for_slot':
|
||||||
|
coordinator.add_comment(task['id'], 'waiting ' + event, f'候选已排队,目标提交 `{sha}`。环境可用后自动准备,看到候选就绪回执时请负责人切到「测试中」。')
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_from_review(task, event):
|
||||||
"""Freeze a test candidate on the originating task. Production still requires its owner event."""
|
"""Freeze a test candidate on the originating task. Production still requires its owner event."""
|
||||||
sha, ref = resolve(task, event)
|
sha, ref = resolve(task, event)
|
||||||
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
|||||||
@@ -23,6 +23,41 @@ class CandidateReleaseTest(unittest.TestCase):
|
|||||||
for n, sha in ((20, A), (21, B))}
|
for n, sha in ((20, A), (21, B))}
|
||||||
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
||||||
|
|
||||||
|
def test_qa_application_budget_is_process_local(self):
|
||||||
|
import os
|
||||||
|
key = 'DATABASE' + '_URL'
|
||||||
|
for role in ('api', 'worker'):
|
||||||
|
shell, flags, body = runtime.qa_process_command(role)
|
||||||
|
self.assertTrue(body.endswith('exec /app/' + role))
|
||||||
|
rendered = body.replace('$$', '$').replace('exec /app/' + role, 'printenv ' + key)
|
||||||
|
value = subprocess.check_output([shell, flags, rendered], env={**os.environ, key: 'qa?sslmode=verify-full'}, text=True)
|
||||||
|
self.assertEqual(value.strip(), 'qa?sslmode=verify-full&pool_max_conns=2')
|
||||||
|
|
||||||
|
def test_qa_candidate_gets_a_stable_binding_master_key(self):
|
||||||
|
import os
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(runtime, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(runtime, 'APP_UID', os.getuid()), patch.object(runtime.cd, 'run') as docker:
|
||||||
|
path = runtime.qa_binding_key('image')
|
||||||
|
self.assertEqual((path.stat().st_mode & 0o777, path.stat().st_size), (0o600, 32))
|
||||||
|
first = path.read_bytes()
|
||||||
|
self.assertEqual(runtime.qa_binding_key('image').read_bytes(), first)
|
||||||
|
self.assertEqual(docker.call_count, 1)
|
||||||
|
path.chmod(0o644)
|
||||||
|
with self.assertRaises(runtime.cd.CDError):
|
||||||
|
runtime.qa_binding_key('image')
|
||||||
|
|
||||||
|
def test_acceptance_comment_states_counts_and_cases(self):
|
||||||
|
import candidate_coordinator as coordinator
|
||||||
|
result = {'required': 10, 'passed': 10, 'failed': 0, 'blocked': 0, 'verdict': 'passed',
|
||||||
|
'url': 'http://127.0.0.1:32789',
|
||||||
|
'cases': {'business': ['KB-01', 'KB-07'], 'regression': ['RG-01']}}
|
||||||
|
body = coordinator.acceptance_body('a' * 40, 'b' * 64, ['t'], {'t': ({'id': 'c'}, result)},
|
||||||
|
lambda item: 'u', '- u#comment-c')
|
||||||
|
self.assertIn('必测 10 · 通过 10 · 失败 0 · 阻塞 0 · 结论 passed', body)
|
||||||
|
self.assertIn('业务用例(2):KB-01、KB-07', body)
|
||||||
|
self.assertIn('回归用例(1):RG-01', body)
|
||||||
|
self.assertIn('候选地址 http://127.0.0.1:32789', body)
|
||||||
|
|
||||||
def test_one_requirement_owns_its_own_release(self):
|
def test_one_requirement_owns_its_own_release(self):
|
||||||
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
|
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
|
||||||
candidate.check_scope(plan, self.prs.__getitem__, [A, B])
|
candidate.check_scope(plan, self.prs.__getitem__, [A, B])
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
import qa_report as qa
|
||||||
|
|
||||||
|
|
||||||
|
class QAReportTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.plan = {'business': ['A'], 'regression': ['R']}
|
||||||
|
self.host = {'status': 'passed', 'evidence': 'QA login and operations on the candidate'}
|
||||||
|
self.rows = {i: {'status': 'passed', 'evidence': i + '.log'} for i in ('A', 'R')}
|
||||||
|
|
||||||
|
def test_missing_id_named_before_output(self):
|
||||||
|
del self.rows['R']
|
||||||
|
with self.assertRaisesRegex(ValueError, 'R'):
|
||||||
|
qa.summarize(self.plan, self.rows, self.host)
|
||||||
|
|
||||||
|
def test_duplicate_across_groups(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, 'A'):
|
||||||
|
qa.summarize(dict(self.plan, regression=['A']), self.rows, self.host)
|
||||||
|
|
||||||
|
def test_candidate_login_blocks_local_green(self):
|
||||||
|
report = qa.summarize(self.plan, self.rows, {'status': 'blocked', 'evidence': 'candidate login 401'})
|
||||||
|
self.assertEqual(report['verdict'], 'blocked')
|
||||||
|
|
||||||
|
def test_generated_report_reconciles(self):
|
||||||
|
report = qa.summarize(self.plan, self.rows, self.host)
|
||||||
|
self.assertEqual((report['cases'], report['required'], report['passed']), (self.plan, 2, 2))
|
||||||
|
qa.verify_report(report)
|
||||||
|
report['passed'] = 1
|
||||||
|
with self.assertRaisesRegex(ValueError, 'passed'):
|
||||||
|
qa.verify_report(report)
|
||||||
@@ -3,6 +3,7 @@ import unittest
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import candidate_queue as queue
|
||||||
import release_handoff as h
|
import release_handoff as h
|
||||||
|
|
||||||
|
|
||||||
@@ -22,6 +23,77 @@ class ReleaseHandoffTest(unittest.TestCase):
|
|||||||
with self.assertRaises(h.cd.CDError):
|
with self.assertRaises(h.cd.CDError):
|
||||||
h.review_identity(self.task, [self.review, newer], 'comment')
|
h.review_identity(self.task, [self.review, newer], 'comment')
|
||||||
|
|
||||||
|
def test_plain_verdict_resolves_each_reports_own_commit(self):
|
||||||
|
for title, sha in [('可测试', 'ea20abc'), ('🚦 ✅ 可测试', 'abc123def')]:
|
||||||
|
row = dict(self.review, content=f'{title}|[任务](mention://task/task)\n落地合并 `{sha}`')
|
||||||
|
self.assertEqual(h.review_identity(self.task, [row], row['id'])[0], sha)
|
||||||
|
for title in ['不可测试', '是否可测试?', '未通过,引用「可测试」']:
|
||||||
|
row = dict(self.review, content=f'{title}|[任务](mention://task/task)\n落地合并 `ea20abc`')
|
||||||
|
with self.assertRaises(h.cd.CDError):
|
||||||
|
h.review_identity(self.task, [row], row['id'])
|
||||||
|
|
||||||
|
def test_landed_commit_marker_in_merge_chain(self):
|
||||||
|
header = self.review['content'].splitlines()[0]
|
||||||
|
for marker in ('落地', '落地(merge)', '落地 merge'):
|
||||||
|
row = dict(self.review, content=f'{header}\n源 `b2248a9` ➔ {marker} `d76363c`(11:56)➔ main `c90cb80`')
|
||||||
|
self.assertEqual(h.review_identity(self.task, [row], 'comment')[0], 'd76363c')
|
||||||
|
for body, error in [('源 `b2248a9`', 'missing landed commit'),
|
||||||
|
('落地 merge `d76363c`,落地 `c90cb80`', 'multiple landed commits')]:
|
||||||
|
row = dict(self.review, content=f'{header}\n{body}')
|
||||||
|
with self.assertRaisesRegex(h.cd.CDError, error):
|
||||||
|
h.review_identity(self.task, [row], 'comment')
|
||||||
|
|
||||||
|
def test_busy_candidate_waits_on_original_task_without_dispatch(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
|
||||||
|
patch.object(h.coordinator, 'add_comment'), patch.object(h.coordinator, 'queue') as dispatch:
|
||||||
|
task_id = '00000001-1111-2222-3333-444444444444'
|
||||||
|
event = '00000002-1111-2222-3333-444444444444'
|
||||||
|
slot = Path(tmp) / 'another' / 'compose.json'
|
||||||
|
slot.parent.mkdir()
|
||||||
|
slot.touch()
|
||||||
|
first = h.preflight({'id': task_id}, event)
|
||||||
|
second = h.preflight({'id': task_id}, event)
|
||||||
|
self.assertEqual(first, second)
|
||||||
|
self.assertEqual(first['state'], 'waiting_for_slot')
|
||||||
|
self.assertEqual(len(list((Path(tmp) / 'waiting').glob('*.json'))), 1)
|
||||||
|
dispatch.assert_not_called()
|
||||||
|
|
||||||
|
def test_waiter_dispatches_once_when_slot_is_free(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
|
||||||
|
patch.object(h.assistant, 'task_record', return_value={'id': 'task'}), \
|
||||||
|
patch.object(h.assistant.worker, 'main_site_sha', return_value='b' * 40), \
|
||||||
|
patch.object(h.candidate, 'git', return_value='b' * 40), \
|
||||||
|
patch.object(h.coordinator, 'add_comment'), \
|
||||||
|
patch.object(h, 'prepare_from_review', return_value={'url': 'https://example.test/run/1'}) as build:
|
||||||
|
h.preflight({'id': 'task'}, 'event')
|
||||||
|
self.assertEqual(queue.drain(), 'dispatched')
|
||||||
|
self.assertEqual(queue.drain(), 'idle')
|
||||||
|
build.assert_called_once_with({'id': 'task'}, 'event')
|
||||||
|
|
||||||
|
def test_active_qa_slot_is_preserved(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(h.assistant, 'task_record', return_value={'status': {'id': 'testing'}}), \
|
||||||
|
patch.object(h.cd, 'run') as docker:
|
||||||
|
root = Path(tmp)
|
||||||
|
(root / 'waiting').mkdir()
|
||||||
|
h.cd.record(root / 'waiting/event.json', {'state': 'waiting_for_slot'})
|
||||||
|
(root / 'slot').mkdir()
|
||||||
|
(root / 'slot/compose.json').touch()
|
||||||
|
h.cd.record(root / 'slot/ready.json', {'task': 'task'})
|
||||||
|
self.assertEqual(queue.drain(), 'occupied')
|
||||||
|
docker.assert_not_called()
|
||||||
|
|
||||||
|
def test_ready_demand_waits_for_owner_to_start_testing(self):
|
||||||
|
record = {'id': 'task', 'typeId': '1b7f1bb1-72c2-4106-b305-85604cf6d7e2', 'url': 'https://example.test/task',
|
||||||
|
'status': {'id': h.coordinator.WAIT_TEST}}
|
||||||
|
plan = {'task': 'task', 'items': [{'task': 'task'}]}
|
||||||
|
with patch.object(h.coordinator, 'task', return_value=record), patch.object(h.coordinator, 'add_comment'), \
|
||||||
|
patch.object(h.coordinator.hfx, 'hifox') as cli:
|
||||||
|
h.coordinator.publish_candidate(plan, dict(sha='a'*40, bundle='b'*64, url='https://example.test'), '1')
|
||||||
|
cli.assert_not_called()
|
||||||
|
|
||||||
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
|
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
|
||||||
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
|
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
|
||||||
|
|||||||
@@ -32,14 +32,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const snapshot = {
|
const snapshot = {
|
||||||
data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true },
|
|
||||||
}
|
|
||||||
const snapshotWith = (secretEntryAllowed: boolean) => ({
|
|
||||||
data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed },
|
|
||||||
})
|
|
||||||
const snapshotWithoutCapability = {
|
|
||||||
data: { environments: [binding('test'), binding('production')], storage_ready: true },
|
data: { environments: [binding('test'), binding('production')], storage_ready: true },
|
||||||
}
|
}
|
||||||
|
const snapshotWithLegacyCapability = (allowed: boolean) => ({
|
||||||
|
data: { ...snapshot.data, secret_entry_allowed: allowed },
|
||||||
|
})
|
||||||
const catalog = {
|
const catalog = {
|
||||||
data: {
|
data: {
|
||||||
status: 'ok',
|
status: 'ok',
|
||||||
@@ -279,48 +276,55 @@ describe('KnowledgeBaseBinding', () => {
|
|||||||
expect(save?.hasAttribute('disabled')).toBe(true)
|
expect(save?.hasAttribute('disabled')).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('disables key entry when the server reports no accepted transport', async () => {
|
it('submits a typed key from a plain-HTTP console even when a legacy capability says no', async () => {
|
||||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
|
// 运行期拼装:扫描器会把「api_key: '<16+ 字符字面量>'」判成泄漏。
|
||||||
await render()
|
const typedKey = ['typed', 'on', 'plain', 'http'].join('-')
|
||||||
await click('更换密钥')
|
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
|
||||||
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
|
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWithLegacyCapability(false)))
|
||||||
expect(input?.disabled).toBe(true)
|
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
|
||||||
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
|
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
|
||||||
|
return Promise.resolve(json({ data: binding('test') }))
|
||||||
})
|
})
|
||||||
|
vi.stubGlobal('fetch', fetchMock)
|
||||||
it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => {
|
|
||||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
|
|
||||||
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
|
||||||
expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true')
|
|
||||||
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not blame a proxy when an older API omits the capability', async () => {
|
|
||||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability)))
|
|
||||||
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
|
||||||
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
|
|
||||||
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => {
|
|
||||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
|
|
||||||
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
|
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
|
||||||
await click('更换密钥')
|
await click('更换密钥')
|
||||||
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
|
const key = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
|
||||||
expect(input?.disabled).toBe(false)
|
expect(key?.disabled).toBe(false)
|
||||||
expect(host.textContent).toContain('密钥会以明文经过这段内网')
|
expect(host.textContent).toContain('当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。')
|
||||||
expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true')
|
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
|
||||||
|
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
|
||||||
|
await act(async () => {
|
||||||
|
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(key, typedKey)
|
||||||
|
key!.dispatchEvent(new Event('input', { bubbles: true }))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('does not warn on an HTTPS console the server already trusts', async () => {
|
await click('验证并读取知识库')
|
||||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
|
const catalogCall = fetchMock.mock.calls.find((call) => String(call[0]).includes('/catalog'))
|
||||||
|
expect(catalogCall).toBeTruthy()
|
||||||
|
expect(typeof catalogCall?.[1]?.body).toBe('string')
|
||||||
|
const catalogBody = JSON.parse(String(catalogCall?.[1]?.body))
|
||||||
|
expect(catalogBody).toMatchObject({ key_action: 'replace', api_key: typedKey })
|
||||||
|
|
||||||
|
await choose('对内知识库', 'kb-new-in-0001')
|
||||||
|
await choose('对外知识库', 'kb-new-out-0001')
|
||||||
|
await click('保存测试绑定')
|
||||||
|
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
|
||||||
|
expect(put).toBeTruthy()
|
||||||
|
expect(typeof put?.[1]?.body).toBe('string')
|
||||||
|
const saveBody = JSON.parse(String(put?.[1]?.body))
|
||||||
|
expect(saveBody).toMatchObject({ key_action: 'replace', api_key: typedKey })
|
||||||
|
expect(host.textContent).toContain('已保存测试绑定')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not warn on an HTTPS console', async () => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
|
||||||
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
|
||||||
expect(host.textContent).not.toContain('密钥会以明文经过这段内网')
|
expect(host.textContent).not.toContain('明文 HTTP')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('keeps existing-key operations available while key entry is closed', async () => {
|
it('keeps existing-key operations available without a fresh key', async () => {
|
||||||
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
|
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
|
||||||
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false)))
|
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
|
||||||
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
|
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
|
||||||
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
|
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
|
||||||
return Promise.resolve(json({ data: binding('test') }))
|
return Promise.resolve(json({ data: binding('test') }))
|
||||||
|
|||||||
@@ -147,16 +147,12 @@ export function KnowledgeBaseBinding({
|
|||||||
const notice = notices[env]
|
const notice = notices[env]
|
||||||
|
|
||||||
const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
|
const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
|
||||||
// The server decides whether it will accept a key on this connection; the
|
// 密钥录入不再由控制台传输形态阻断;明文提示只说明浏览器到控制台这一段的事实。
|
||||||
// browser URL cannot tell a trusted TLS proxy from an untrusted one.
|
const plaintext = plaintextRemoteConsole(console)
|
||||||
const secretEntryAllowed = snapshot?.secret_entry_allowed
|
|
||||||
const secure = secretEntryAllowed === true
|
|
||||||
const plaintext = secure && plaintextRemoteConsole(console)
|
|
||||||
const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:'
|
|
||||||
const storageReady = Boolean(snapshot?.storage_ready)
|
const storageReady = Boolean(snapshot?.storage_ready)
|
||||||
const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
|
const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
|
||||||
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
|
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
|
||||||
const keyEntryBlocked = !secure || !storageReady
|
const keyEntryBlocked = !storageReady
|
||||||
const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false
|
const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false
|
||||||
const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false
|
const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false
|
||||||
const catalogReady = Boolean(
|
const catalogReady = Boolean(
|
||||||
@@ -535,19 +531,8 @@ export function KnowledgeBaseBinding({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{untrustedProxy ? (
|
|
||||||
<p className="settings-warn">
|
|
||||||
服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递
|
|
||||||
X-Forwarded-Proto。
|
|
||||||
</p>
|
|
||||||
) : !secure ? (
|
|
||||||
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
|
|
||||||
) : null}
|
|
||||||
{plaintext ? (
|
{plaintext ? (
|
||||||
<p className="settings-warn">
|
<p className="settings-warn">当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。</p>
|
||||||
当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网
|
|
||||||
HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。
|
|
||||||
</p>
|
|
||||||
) : null}
|
) : null}
|
||||||
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
|
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
|
||||||
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
|
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|||||||
|
|
||||||
import { StorageBackupSummary } from './StorageBackupSummary'
|
import { StorageBackupSummary } from './StorageBackupSummary'
|
||||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||||
import type { LibraryStorage } from './librarySnapshots'
|
|
||||||
|
|
||||||
const GIB = 1024 ** 3
|
const GIB = 1024 ** 3
|
||||||
const TB = 1024 * GIB
|
const TB = 1024 * GIB
|
||||||
@@ -66,6 +65,7 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
|||||||
},
|
},
|
||||||
root: '/srv/kb-backups/rds-logical',
|
root: '/srv/kb-backups/rds-logical',
|
||||||
host_root: '/srv/kb-backups/rds-logical',
|
host_root: '/srv/kb-backups/rds-logical',
|
||||||
|
backup_root: '/srv/kb-backups',
|
||||||
source: 'host',
|
source: 'host',
|
||||||
observed_at: '2026-11-24T10:18:00Z',
|
observed_at: '2026-11-24T10:18:00Z',
|
||||||
measurement: 'host-reported',
|
measurement: 'host-reported',
|
||||||
@@ -86,6 +86,18 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
|||||||
available_bytes: 1.2 * TB,
|
available_bytes: 1.2 * TB,
|
||||||
used_bytes: 0.8 * TB,
|
used_bytes: 0.8 * TB,
|
||||||
},
|
},
|
||||||
|
usage: {
|
||||||
|
root: '/srv/kb-backups',
|
||||||
|
measured: true,
|
||||||
|
complete: true,
|
||||||
|
actual_bytes: 40 * GIB,
|
||||||
|
apparent_bytes: 36 * GIB,
|
||||||
|
file_count: 400,
|
||||||
|
dir_count: 20,
|
||||||
|
error: '',
|
||||||
|
},
|
||||||
|
quota_bytes: 50 * GIB,
|
||||||
|
quota_error: '',
|
||||||
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
|
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
|
||||||
totals: {
|
totals: {
|
||||||
batch_count: 2,
|
batch_count: 2,
|
||||||
@@ -102,29 +114,6 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
|||||||
...overrides,
|
...overrides,
|
||||||
})
|
})
|
||||||
|
|
||||||
const archive: LibraryStorage = {
|
|
||||||
available: true,
|
|
||||||
archive_root: '/var/lib/knowledge-governance/library',
|
|
||||||
versions: [],
|
|
||||||
content_bytes: 41_231_686_042,
|
|
||||||
blob_file_bytes: 0,
|
|
||||||
blob_allocated_bytes: 0,
|
|
||||||
unreferenced_blobs: 0,
|
|
||||||
unreferenced_bytes: 0,
|
|
||||||
manifest_file_bytes: 0,
|
|
||||||
policy: { keep_versions: 0, keep_days: 0 },
|
|
||||||
capacity: {
|
|
||||||
budget_bytes: 100 * GIB,
|
|
||||||
current_bytes: 41_231_686_042,
|
|
||||||
required_bytes: 0,
|
|
||||||
projected_bytes: 41_231_686_042,
|
|
||||||
configured: true,
|
|
||||||
ok: true,
|
|
||||||
},
|
|
||||||
automatic_cleanup: false,
|
|
||||||
notes: [],
|
|
||||||
}
|
|
||||||
|
|
||||||
let root: Root
|
let root: Root
|
||||||
let container: HTMLDivElement
|
let container: HTMLDivElement
|
||||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||||
@@ -145,7 +134,7 @@ beforeEach(() => {
|
|||||||
if (path.endsWith('/inventory')) {
|
if (path.endsWith('/inventory')) {
|
||||||
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
|
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
|
||||||
}
|
}
|
||||||
return new Response(JSON.stringify(archive), { status: 200 })
|
return new Response('{}', { status: 404 })
|
||||||
})
|
})
|
||||||
vi.stubGlobal('fetch', fetcher)
|
vi.stubGlobal('fetch', fetcher)
|
||||||
})
|
})
|
||||||
@@ -158,7 +147,7 @@ afterEach(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('StorageBackupSummary', () => {
|
describe('StorageBackupSummary', () => {
|
||||||
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
|
it('renders directory, recent outcomes, backup occupancy, disk and the alert table', async () => {
|
||||||
act(() => root.render(<StorageBackupSummary />))
|
act(() => root.render(<StorageBackupSummary />))
|
||||||
await flush()
|
await flush()
|
||||||
const text = container.textContent || ''
|
const text = container.textContent || ''
|
||||||
@@ -166,9 +155,10 @@ describe('StorageBackupSummary', () => {
|
|||||||
expect(text).toContain('/srv/kb-backups/rds-logical')
|
expect(text).toContain('/srv/kb-backups/rds-logical')
|
||||||
expect(text).toContain('最近成功')
|
expect(text).toContain('最近成功')
|
||||||
expect(text).toContain('最近失败')
|
expect(text).toContain('最近失败')
|
||||||
expect(text).toContain('归档占用')
|
expect(text).toContain('备份占用')
|
||||||
expect(text).toContain('38.4 GB')
|
expect(text).toContain('40 GB')
|
||||||
expect(text).toContain('配额 100 GB')
|
expect(text).toContain('配额 50 GB')
|
||||||
|
expect(text).not.toContain('归档占用')
|
||||||
expect(text).toContain('磁盘剩余')
|
expect(text).toContain('磁盘剩余')
|
||||||
expect(text).toContain('1.2 TB')
|
expect(text).toContain('1.2 TB')
|
||||||
expect(text).toContain('上次上报')
|
expect(text).toContain('上次上报')
|
||||||
@@ -180,12 +170,12 @@ describe('StorageBackupSummary', () => {
|
|||||||
expect(text).not.toContain('示例')
|
expect(text).not.toContain('示例')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
|
it('asks for the read-only inventory endpoint and refreshes once per 60 seconds while visible', async () => {
|
||||||
vi.useFakeTimers()
|
vi.useFakeTimers()
|
||||||
act(() => root.render(<StorageBackupSummary />))
|
act(() => root.render(<StorageBackupSummary />))
|
||||||
await flush()
|
await flush()
|
||||||
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
|
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
|
||||||
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
|
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(0)
|
||||||
|
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
await vi.advanceTimersByTimeAsync(60_000)
|
await vi.advanceTimersByTimeAsync(60_000)
|
||||||
@@ -215,18 +205,14 @@ describe('StorageBackupSummary', () => {
|
|||||||
host_root: '',
|
host_root: '',
|
||||||
batches: [],
|
batches: [],
|
||||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||||
|
usage: { ...wired.usage, measured: false, complete: false, actual_bytes: null, error: '' },
|
||||||
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
|
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
{ status: 200 }
|
{ status: 200 }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return new Response(
|
return new Response('{}', { status: 404 })
|
||||||
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
|
|
||||||
{
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
act(() => root.render(<StorageBackupSummary />))
|
act(() => root.render(<StorageBackupSummary />))
|
||||||
await flush()
|
await flush()
|
||||||
@@ -264,7 +250,7 @@ describe('StorageBackupSummary', () => {
|
|||||||
{ status: 200 }
|
{ status: 200 }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return new Response(JSON.stringify(archive), { status: 200 })
|
return new Response('{}', { status: 404 })
|
||||||
})
|
})
|
||||||
act(() => root.render(<StorageBackupSummary />))
|
act(() => root.render(<StorageBackupSummary />))
|
||||||
await flush()
|
await flush()
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
|
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、备份占用、磁盘剩余、
|
||||||
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
|
// 四条容量告警和批次列表。数据只来自宿主采集器上报的快照,本页没有任何写操作;
|
||||||
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
|
// 读不到的量显示"主机未上报"或"—",不用 0 占位。
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
import { fetchBackupInventory } from './backupInventory'
|
import { fetchBackupInventory } from './backupInventory'
|
||||||
import type { BackupInventory } from './backupInventory'
|
import type { BackupInventory } from './backupInventory'
|
||||||
import { fetchLibraryStorage } from './librarySnapshots'
|
|
||||||
import type { LibraryStorage } from './librarySnapshots'
|
|
||||||
import {
|
import {
|
||||||
UNKNOWN,
|
UNKNOWN,
|
||||||
batchOutcome,
|
batchOutcome,
|
||||||
@@ -65,8 +63,6 @@ const hostStateLabel = (state: HostState): string => {
|
|||||||
|
|
||||||
export function StorageBackupSummary() {
|
export function StorageBackupSummary() {
|
||||||
const [inventory, setInventory] = useState<BackupInventory | null>(null)
|
const [inventory, setInventory] = useState<BackupInventory | null>(null)
|
||||||
const [archive, setArchive] = useState<LibraryStorage | null>(null)
|
|
||||||
const [archiveFailed, setArchiveFailed] = useState(false)
|
|
||||||
const [errors, setErrors] = useState<string[]>([])
|
const [errors, setErrors] = useState<string[]>([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [visible, setVisible] = useState(BATCH_PAGE)
|
const [visible, setVisible] = useState(BATCH_PAGE)
|
||||||
@@ -77,24 +73,15 @@ export function StorageBackupSummary() {
|
|||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
if (inFlight.current) return
|
if (inFlight.current) return
|
||||||
inFlight.current = true
|
inFlight.current = true
|
||||||
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
|
try {
|
||||||
const nextErrors: string[] = []
|
setInventory(await fetchBackupInventory())
|
||||||
if (inventoryResult.status === 'fulfilled') {
|
setErrors([])
|
||||||
setInventory(inventoryResult.value)
|
} catch (error) {
|
||||||
} else {
|
setErrors([error instanceof Error ? error.message : '读取备份元数据失败'])
|
||||||
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
|
} finally {
|
||||||
}
|
|
||||||
if (archiveResult.status === 'fulfilled') {
|
|
||||||
setArchive(archiveResult.value)
|
|
||||||
setArchiveFailed(archiveResult.value === null)
|
|
||||||
if (archiveResult.value === null) nextErrors.push('读取归档占用失败')
|
|
||||||
} else {
|
|
||||||
setArchiveFailed(true)
|
|
||||||
nextErrors.push(archiveResult.reason instanceof Error ? archiveResult.reason.message : '读取归档占用失败')
|
|
||||||
}
|
|
||||||
setErrors(nextErrors)
|
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
inFlight.current = false
|
inFlight.current = false
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -110,8 +97,8 @@ export function StorageBackupSummary() {
|
|||||||
}, [load])
|
}, [load])
|
||||||
|
|
||||||
const state = hostState(inventory)
|
const state = hostState(inventory)
|
||||||
const alerts = storageAlerts(inventory, archive, archiveFailed)
|
const alerts = storageAlerts(inventory)
|
||||||
const cards = summaryCards(inventory, archive, archiveFailed)
|
const cards = summaryCards(inventory)
|
||||||
const batches = inventory?.batches ?? []
|
const batches = inventory?.batches ?? []
|
||||||
const shown = batches.slice(0, visible)
|
const shown = batches.slice(0, visible)
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,19 @@ const payload = {
|
|||||||
available_bytes: 48318382080,
|
available_bytes: 48318382080,
|
||||||
used_bytes: 206158430208,
|
used_bytes: 206158430208,
|
||||||
},
|
},
|
||||||
|
backup_root: '/srv/kb-backups',
|
||||||
|
usage: {
|
||||||
|
root: '/srv/kb-backups',
|
||||||
|
measured: true,
|
||||||
|
complete: true,
|
||||||
|
actual_bytes: 24318382080,
|
||||||
|
apparent_bytes: 23000000000,
|
||||||
|
file_count: 900,
|
||||||
|
dir_count: 30,
|
||||||
|
error: '',
|
||||||
|
},
|
||||||
|
quota_bytes: 53687091200,
|
||||||
|
quota_error: '',
|
||||||
batches: [
|
batches: [
|
||||||
{
|
{
|
||||||
stamp: '20261118T193001Z',
|
stamp: '20261118T193001Z',
|
||||||
@@ -108,6 +121,48 @@ describe('fetchBackupInventory', () => {
|
|||||||
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
|
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
|
||||||
)
|
)
|
||||||
expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
|
expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
|
||||||
|
expect(inventory.backup_root).toBe('/srv/kb-backups')
|
||||||
|
expect(inventory.usage.measured).toBe(true)
|
||||||
|
expect(inventory.usage.actual_bytes).toBe(24318382080)
|
||||||
|
expect(inventory.quota_bytes).toBe(53687091200)
|
||||||
|
expect(inventory.quota_error).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('旧采集器缺 usage/quota 时显式未上报,不用批次和冒充占用', async () => {
|
||||||
|
const legacy = JSON.parse(JSON.stringify(payload))
|
||||||
|
delete legacy.data.backup_root
|
||||||
|
delete legacy.data.usage
|
||||||
|
delete legacy.data.quota_bytes
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(legacy) }))
|
||||||
|
)
|
||||||
|
const inventory = await fetchBackupInventory()
|
||||||
|
expect(inventory.usage.measured).toBe(false)
|
||||||
|
expect(inventory.usage.actual_bytes).toBeNull()
|
||||||
|
expect(inventory.usage.error).toContain('未上报')
|
||||||
|
expect(inventory.quota_bytes).toBeNull()
|
||||||
|
expect(inventory.quota_error).toContain('未上报')
|
||||||
|
expect(inventory.totals.actual_bytes).toBe(1500000000)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('不完整占用即使带部分字节也不展示', async () => {
|
||||||
|
const partial = JSON.parse(JSON.stringify(payload))
|
||||||
|
partial.data.usage = {
|
||||||
|
...partial.data.usage,
|
||||||
|
measured: true,
|
||||||
|
complete: false,
|
||||||
|
actual_bytes: 123,
|
||||||
|
error: '备份根占用未知:遍历失败',
|
||||||
|
}
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(partial) }))
|
||||||
|
)
|
||||||
|
const inventory = await fetchBackupInventory()
|
||||||
|
expect(inventory.usage.measured).toBe(false)
|
||||||
|
expect(inventory.usage.actual_bytes).toBeNull()
|
||||||
|
expect(inventory.usage.error).toContain('遍历失败')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('响应缺 wired 时整块报错,不默认成未接线', async () => {
|
it('响应缺 wired 时整块报错,不默认成未接线', async () => {
|
||||||
|
|||||||
@@ -39,6 +39,18 @@ export interface BackupInventoryCapacity {
|
|||||||
error?: string
|
error?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 备份根累计占用:配额约束的对象。measured=false 时字节全为 null,页面不得用 0 冒充。
|
||||||
|
export interface BackupInventoryUsage {
|
||||||
|
root: string
|
||||||
|
measured: boolean
|
||||||
|
complete: boolean
|
||||||
|
actual_bytes: number | null
|
||||||
|
apparent_bytes: number | null
|
||||||
|
file_count: number | null
|
||||||
|
dir_count: number | null
|
||||||
|
error: string
|
||||||
|
}
|
||||||
|
|
||||||
export interface BackupInventoryDatabase {
|
export interface BackupInventoryDatabase {
|
||||||
name: string
|
name: string
|
||||||
dir_name: string
|
dir_name: string
|
||||||
@@ -84,12 +96,16 @@ export interface BackupInventory {
|
|||||||
metadata: BackupInventoryMetadata
|
metadata: BackupInventoryMetadata
|
||||||
root: string
|
root: string
|
||||||
host_root: string
|
host_root: string
|
||||||
|
backup_root: string
|
||||||
source: string
|
source: string
|
||||||
observed_at: string
|
observed_at: string
|
||||||
error?: string
|
error?: string
|
||||||
measurement: string
|
measurement: string
|
||||||
mount: BackupInventoryMount
|
mount: BackupInventoryMount
|
||||||
capacity: BackupInventoryCapacity
|
capacity: BackupInventoryCapacity
|
||||||
|
usage: BackupInventoryUsage
|
||||||
|
quota_bytes: number | null
|
||||||
|
quota_error: string
|
||||||
batches: BackupInventoryBatch[]
|
batches: BackupInventoryBatch[]
|
||||||
totals: {
|
totals: {
|
||||||
batch_count: number
|
batch_count: number
|
||||||
@@ -115,6 +131,22 @@ const asNumberOrNull = (value: unknown): number | null =>
|
|||||||
const asBool = (value: unknown): boolean => value === true
|
const asBool = (value: unknown): boolean => value === true
|
||||||
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
|
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
|
||||||
|
|
||||||
|
const usageProjection = (value: unknown): BackupInventoryUsage => {
|
||||||
|
const entry = record(value) ? value : {}
|
||||||
|
const complete = asBool(entry.complete)
|
||||||
|
const measured = asBool(entry.measured) && complete && asNumberOrNull(entry.actual_bytes) !== null
|
||||||
|
return {
|
||||||
|
root: asString(entry.root),
|
||||||
|
measured,
|
||||||
|
complete,
|
||||||
|
actual_bytes: measured ? asNumberOrNull(entry.actual_bytes) : null,
|
||||||
|
apparent_bytes: measured ? asNumberOrNull(entry.apparent_bytes) : null,
|
||||||
|
file_count: measured ? asNumberOrNull(entry.file_count) : null,
|
||||||
|
dir_count: measured ? asNumberOrNull(entry.dir_count) : null,
|
||||||
|
error: asString(entry.error) || (measured ? '' : '采集器未上报备份根占用(需要升级采集器)'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const manifestState = (value: unknown): BackupManifestState =>
|
const manifestState = (value: unknown): BackupManifestState =>
|
||||||
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
|
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
|
||||||
|
|
||||||
@@ -186,10 +218,16 @@ function inventoryProjection(value: unknown): BackupInventory {
|
|||||||
},
|
},
|
||||||
root: asString(value.root),
|
root: asString(value.root),
|
||||||
host_root: asString(value.host_root),
|
host_root: asString(value.host_root),
|
||||||
|
backup_root: asString(value.backup_root),
|
||||||
source: asString(value.source),
|
source: asString(value.source),
|
||||||
observed_at: asString(value.observed_at),
|
observed_at: asString(value.observed_at),
|
||||||
error: asString(value.error),
|
error: asString(value.error),
|
||||||
measurement: asString(value.measurement),
|
measurement: asString(value.measurement),
|
||||||
|
usage: usageProjection(value.usage),
|
||||||
|
quota_bytes: asNumberOrNull(value.quota_bytes),
|
||||||
|
quota_error:
|
||||||
|
asString(value.quota_error) ||
|
||||||
|
(asNumberOrNull(value.quota_bytes) === null ? '采集器未上报备份配额(需要升级采集器)' : ''),
|
||||||
mount: {
|
mount: {
|
||||||
container_root: asString(mount.container_root),
|
container_root: asString(mount.container_root),
|
||||||
mount_verified: asBool(mount.mount_verified),
|
mount_verified: asBool(mount.mount_verified),
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ describe('knowledgeBaseBindings', () => {
|
|||||||
expect(parsed.test.base_url).toBe('https://test.example')
|
expect(parsed.test.base_url).toBe('https://test.example')
|
||||||
expect(parsed.production.internal_kb_name).toBe('内部资料')
|
expect(parsed.production.internal_kb_name).toBe('内部资料')
|
||||||
expect(parsed.storage_ready).toBe(true)
|
expect(parsed.storage_ready).toBe(true)
|
||||||
expect(parsed.secret_entry_allowed).toBe(true)
|
expect((parsed as unknown as Record<string, unknown>).secret_entry_allowed).toBeUndefined()
|
||||||
const asRecord = parsed.test as unknown as Record<string, unknown>
|
const asRecord = parsed.test as unknown as Record<string, unknown>
|
||||||
expect(asRecord.api_key).toBeUndefined()
|
expect(asRecord.api_key).toBeUndefined()
|
||||||
expect(asRecord.key_ciphertext).toBeUndefined()
|
expect(asRecord.key_ciphertext).toBeUndefined()
|
||||||
@@ -55,14 +55,7 @@ describe('knowledgeBaseBindings', () => {
|
|||||||
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
|
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('leaves the capability absent when an older API does not report it', () => {
|
it('ignores the removed legacy transport capability', () => {
|
||||||
const parsed = parseKBBindingSnapshot({
|
|
||||||
data: { environments: [binding('test'), binding('production')], storage_ready: true },
|
|
||||||
})
|
|
||||||
expect(parsed.secret_entry_allowed).toBeUndefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps an explicit refusal distinguishable from a missing field', () => {
|
|
||||||
const parsed = parseKBBindingSnapshot({
|
const parsed = parseKBBindingSnapshot({
|
||||||
data: {
|
data: {
|
||||||
environments: [binding('test'), binding('production')],
|
environments: [binding('test'), binding('production')],
|
||||||
@@ -70,7 +63,7 @@ describe('knowledgeBaseBindings', () => {
|
|||||||
secret_entry_allowed: false,
|
secret_entry_allowed: false,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
expect(parsed.secret_entry_allowed).toBe(false)
|
expect((parsed as unknown as Record<string, unknown>).secret_entry_allowed).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows a short id next to the name so same-name bases are distinguishable', () => {
|
it('shows a short id next to the name so same-name bases are distinguishable', () => {
|
||||||
|
|||||||
@@ -34,9 +34,6 @@ export interface KBBindingSnapshot {
|
|||||||
test: KBEnvironmentBinding
|
test: KBEnvironmentBinding
|
||||||
production: KBEnvironmentBinding
|
production: KBEnvironmentBinding
|
||||||
storage_ready: boolean
|
storage_ready: boolean
|
||||||
// Absent stays absent: an older API must not be reported as an untrusted
|
|
||||||
// proxy, and it must still fail closed for key entry.
|
|
||||||
secret_entry_allowed?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface KBCatalogOption {
|
export interface KBCatalogOption {
|
||||||
@@ -137,8 +134,6 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
|
|||||||
test,
|
test,
|
||||||
production,
|
production,
|
||||||
storage_ready: bool(value.data.storage_ready),
|
storage_ready: bool(value.data.storage_ready),
|
||||||
secret_entry_allowed:
|
|
||||||
typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ export function secretEntryAllowed(location: { protocol: string; hostname: strin
|
|||||||
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
|
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
|
||||||
}
|
}
|
||||||
|
|
||||||
// True when a key typed here would cross a network in the clear, even though
|
// True when a key typed here would cross a network in the clear. The knowledge
|
||||||
// the server presently allows it. Drives the warning only, never the gate:
|
// base page uses this for its warning only; QA AI still uses secretEntryAllowed
|
||||||
// the gate is the server-reported capability.
|
// as a hard gate.
|
||||||
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
|
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
|
||||||
return !secretEntryAllowed(location)
|
return !secretEntryAllowed(location)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||||
import type { LibraryStorage } from './librarySnapshots'
|
|
||||||
import {
|
import {
|
||||||
DISK_CRITICAL_AVAILABLE_PERCENT,
|
DISK_CRITICAL_AVAILABLE_PERCENT,
|
||||||
batchOutcome,
|
batchOutcome,
|
||||||
@@ -70,6 +69,7 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
|||||||
},
|
},
|
||||||
root: '/srv/kb-backups/rds-logical',
|
root: '/srv/kb-backups/rds-logical',
|
||||||
host_root: '/srv/kb-backups/rds-logical',
|
host_root: '/srv/kb-backups/rds-logical',
|
||||||
|
backup_root: '/srv/kb-backups',
|
||||||
source: 'host',
|
source: 'host',
|
||||||
observed_at: '2026-11-24T10:18:00Z',
|
observed_at: '2026-11-24T10:18:00Z',
|
||||||
measurement: 'host-reported',
|
measurement: 'host-reported',
|
||||||
@@ -90,6 +90,18 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
|||||||
available_bytes: 1.2 * TB,
|
available_bytes: 1.2 * TB,
|
||||||
used_bytes: 0.8 * TB,
|
used_bytes: 0.8 * TB,
|
||||||
},
|
},
|
||||||
|
usage: {
|
||||||
|
root: '/srv/kb-backups',
|
||||||
|
measured: true,
|
||||||
|
complete: true,
|
||||||
|
actual_bytes: 22.65 * GIB,
|
||||||
|
apparent_bytes: 20 * GIB,
|
||||||
|
file_count: 1000,
|
||||||
|
dir_count: 40,
|
||||||
|
error: '',
|
||||||
|
},
|
||||||
|
quota_bytes: 50 * GIB,
|
||||||
|
quota_error: '',
|
||||||
batches: [batch()],
|
batches: [batch()],
|
||||||
totals: {
|
totals: {
|
||||||
batch_count: 1,
|
batch_count: 1,
|
||||||
@@ -106,30 +118,6 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
|||||||
...overrides,
|
...overrides,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
|
|
||||||
available: true,
|
|
||||||
archive_root: '/var/lib/knowledge-governance/library',
|
|
||||||
versions: [],
|
|
||||||
content_bytes: 41_231_686_042,
|
|
||||||
blob_file_bytes: 0,
|
|
||||||
blob_allocated_bytes: 0,
|
|
||||||
unreferenced_blobs: 0,
|
|
||||||
unreferenced_bytes: 0,
|
|
||||||
manifest_file_bytes: 0,
|
|
||||||
policy: { keep_versions: 0, keep_days: 0 },
|
|
||||||
capacity: {
|
|
||||||
budget_bytes: 100 * GIB,
|
|
||||||
current_bytes: 41_231_686_042,
|
|
||||||
required_bytes: 0,
|
|
||||||
projected_bytes: 41_231_686_042,
|
|
||||||
configured: true,
|
|
||||||
ok: true,
|
|
||||||
},
|
|
||||||
automatic_cleanup: false,
|
|
||||||
notes: [],
|
|
||||||
...overrides,
|
|
||||||
})
|
|
||||||
|
|
||||||
const unreported = (): BackupInventory =>
|
const unreported = (): BackupInventory =>
|
||||||
inventory({
|
inventory({
|
||||||
wired: false,
|
wired: false,
|
||||||
@@ -151,6 +139,19 @@ const unreported = (): BackupInventory =>
|
|||||||
},
|
},
|
||||||
root: '',
|
root: '',
|
||||||
host_root: '',
|
host_root: '',
|
||||||
|
backup_root: '',
|
||||||
|
usage: {
|
||||||
|
root: '',
|
||||||
|
measured: false,
|
||||||
|
complete: false,
|
||||||
|
actual_bytes: null,
|
||||||
|
apparent_bytes: null,
|
||||||
|
file_count: null,
|
||||||
|
dir_count: null,
|
||||||
|
error: '采集器未上报备份根占用(需要升级采集器)',
|
||||||
|
},
|
||||||
|
quota_bytes: null,
|
||||||
|
quota_error: '采集器未上报备份配额(需要升级采集器)',
|
||||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||||
batches: [],
|
batches: [],
|
||||||
totals: {
|
totals: {
|
||||||
@@ -230,48 +231,57 @@ describe('recentOutcome', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('summaryCards', () => {
|
describe('summaryCards', () => {
|
||||||
it('shows real values when the host reported and the archive is available', () => {
|
it('shows real values from the host snapshot for backup occupancy and quota', () => {
|
||||||
const cards = summaryCards(inventory(), archive(), false)
|
const cards = summaryCards(inventory())
|
||||||
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
|
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
|
||||||
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
|
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
|
||||||
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
|
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
|
||||||
expect(byKey.failure).toBe('无')
|
expect(byKey.failure).toBe('无')
|
||||||
expect(byKey.archive).toBe('38.4 GB')
|
expect(byKey.backup).toBe(formatSize(22.65 * GIB))
|
||||||
expect(byKey.disk).toBe('1.2 TB')
|
expect(byKey.disk).toBe('1.2 TB')
|
||||||
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
|
expect(cards.find((card) => card.key === 'backup')?.note).toBe('配额 50 GB')
|
||||||
|
expect(cards.some((card) => card.label === '归档占用')).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
|
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
|
||||||
const cards = summaryCards(unreported(), archive({ available: false }), false)
|
const cards = summaryCards(unreported())
|
||||||
for (const key of ['root', 'success', 'failure', 'disk']) {
|
for (const key of ['root', 'success', 'failure', 'backup', 'disk']) {
|
||||||
const card = cards.find((item) => item.key === key)!
|
const card = cards.find((item) => item.key === key)!
|
||||||
expect(card.value).toBe('主机未上报')
|
expect(card.value).toBe('主机未上报')
|
||||||
expect(card.note).toBe('上次上报 —')
|
expect(card.note).toBe('上次上报 —')
|
||||||
}
|
}
|
||||||
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
|
|
||||||
expect(cards.some((card) => card.value === '0 B')).toBe(false)
|
expect(cards.some((card) => card.value === '0 B')).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
|
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
|
||||||
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
|
const cards = summaryCards(
|
||||||
|
inventory({
|
||||||
|
metadata: { ...inventory().metadata, complete: false },
|
||||||
|
usage: {
|
||||||
|
...inventory().usage,
|
||||||
|
measured: false,
|
||||||
|
complete: false,
|
||||||
|
actual_bytes: null,
|
||||||
|
error: '备份根占用未知:遍历失败',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
|
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
|
||||||
|
expect(cards.find((card) => card.key === 'backup')?.value).toBe('—')
|
||||||
|
expect(cards.find((card) => card.key === 'backup')?.note).toBe('备份根占用未知:遍历失败')
|
||||||
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
|
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
|
||||||
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
|
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('storageAlerts', () => {
|
describe('storageAlerts', () => {
|
||||||
it('judges disk and quota independently and counts pending rows', () => {
|
it('judges disk and backup quota independently and counts pending rows', () => {
|
||||||
const healthy = storageAlerts(inventory(), archive(), false)
|
const healthy = storageAlerts(inventory())
|
||||||
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
|
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
|
||||||
expect(pendingAlertCount(healthy)).toBe(0)
|
expect(pendingAlertCount(healthy)).toBe(0)
|
||||||
|
|
||||||
const nearQuota = storageAlerts(
|
const nearQuota = storageAlerts(
|
||||||
inventory(),
|
inventory({ usage: { ...inventory().usage, actual_bytes: 45 * GIB }, quota_bytes: 50 * GIB })
|
||||||
archive({
|
|
||||||
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
|
|
||||||
}),
|
|
||||||
false
|
|
||||||
)
|
)
|
||||||
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
|
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
|
||||||
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
|
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
|
||||||
@@ -288,9 +298,9 @@ describe('storageAlerts', () => {
|
|||||||
available_bytes: 0.01 * TB,
|
available_bytes: 0.01 * TB,
|
||||||
used_bytes: 1.99 * TB,
|
used_bytes: 1.99 * TB,
|
||||||
},
|
},
|
||||||
}),
|
usage: { ...inventory().usage, actual_bytes: 100 * GIB },
|
||||||
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
|
quota_bytes: 100 * GIB,
|
||||||
false
|
})
|
||||||
)
|
)
|
||||||
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
|
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
|
||||||
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
|
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
|
||||||
@@ -300,7 +310,7 @@ describe('storageAlerts', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('never claims a conclusion without numbers', () => {
|
it('never claims a conclusion without numbers', () => {
|
||||||
const alerts = storageAlerts(unreported(), null, true)
|
const alerts = storageAlerts(unreported())
|
||||||
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
|
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
|
||||||
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
|
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
|
||||||
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
|
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
|
||||||
|
|||||||
+42
-49
@@ -1,9 +1,7 @@
|
|||||||
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
|
// 「存储与备份」只读摘要的纯逻辑:唯一数据源是宿主采集器快照
|
||||||
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
|
// /api/v1/backup-schedule/inventory (批次、备份根占用、配额与文件系统容量)
|
||||||
// /api/v1/library/storage (归档库自身的占用与配额)
|
|
||||||
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
|
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
|
||||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||||
import type { LibraryStorage } from './librarySnapshots'
|
|
||||||
|
|
||||||
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
|
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
|
||||||
// 磁盘:可用空间 < 5% 红,< 10% 黄
|
// 磁盘:可用空间 < 5% 红,< 10% 黄
|
||||||
@@ -159,11 +157,7 @@ export interface SummaryCard {
|
|||||||
const lastReportNote = (inventory: BackupInventory): string =>
|
const lastReportNote = (inventory: BackupInventory): string =>
|
||||||
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
|
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
|
||||||
|
|
||||||
export function summaryCards(
|
export function summaryCards(inventory: BackupInventory | null): SummaryCard[] {
|
||||||
inventory: BackupInventory | null,
|
|
||||||
archive: LibraryStorage | null,
|
|
||||||
archiveFailed: boolean
|
|
||||||
): SummaryCard[] {
|
|
||||||
const state = hostState(inventory)
|
const state = hostState(inventory)
|
||||||
const facts = state === 'ready' || state === 'incomplete'
|
const facts = state === 'ready' || state === 'incomplete'
|
||||||
const sizes = state === 'ready'
|
const sizes = state === 'ready'
|
||||||
@@ -181,7 +175,20 @@ export function summaryCards(
|
|||||||
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||||
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
|
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
|
||||||
|
|
||||||
const archiveKnown = Boolean(archive?.available) && !archiveFailed
|
const usage = inventory?.usage
|
||||||
|
const usageKnown =
|
||||||
|
facts && Boolean(usage?.measured) && usage?.actual_bytes !== null && usage?.actual_bytes !== undefined
|
||||||
|
const quotaBytes = inventory?.quota_bytes
|
||||||
|
const quotaKnown = usageKnown && (quotaBytes ?? 0) > 0
|
||||||
|
const backupNote = !pending
|
||||||
|
? UNKNOWN
|
||||||
|
: !facts
|
||||||
|
? hostNote
|
||||||
|
: usageKnown
|
||||||
|
? quotaKnown
|
||||||
|
? `配额 ${formatSize(quotaBytes)}`
|
||||||
|
: inventory!.quota_error || '配额未上报'
|
||||||
|
: usage?.error || '本次上报不完整'
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -207,17 +214,11 @@ export function summaryCards(
|
|||||||
unknown: !recent,
|
unknown: !recent,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'archive',
|
key: 'backup',
|
||||||
label: '归档占用',
|
label: '备份占用',
|
||||||
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
|
value: usageKnown ? formatSize(usage!.actual_bytes) : facts ? UNKNOWN : hostValue,
|
||||||
note: archiveFailed
|
note: backupNote,
|
||||||
? '归档读取失败'
|
unknown: !usageKnown,
|
||||||
: !archive || !archive.available
|
|
||||||
? '归档不可用'
|
|
||||||
: archive.capacity.configured
|
|
||||||
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
|
|
||||||
: '配额未设置',
|
|
||||||
unknown: !archiveKnown,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'disk',
|
key: 'disk',
|
||||||
@@ -244,23 +245,21 @@ export interface SummaryAlert {
|
|||||||
export interface StorageFacts {
|
export interface StorageFacts {
|
||||||
diskAvailableBytes: number | null
|
diskAvailableBytes: number | null
|
||||||
diskTotalBytes: number | null
|
diskTotalBytes: number | null
|
||||||
archiveUsedBytes: number | null
|
backupUsedBytes: number | null
|
||||||
archiveBudgetBytes: number | null
|
backupQuotaBytes: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function storageFacts(
|
export function storageFacts(inventory: BackupInventory | null): StorageFacts {
|
||||||
inventory: BackupInventory | null,
|
|
||||||
archive: LibraryStorage | null,
|
|
||||||
archiveFailed: boolean
|
|
||||||
): StorageFacts {
|
|
||||||
const capacity = inventory?.capacity
|
const capacity = inventory?.capacity
|
||||||
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||||
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
|
const usage = inventory?.usage
|
||||||
|
const used = usage?.measured && usage.actual_bytes !== null ? usage.actual_bytes : null
|
||||||
|
const quota = inventory?.quota_bytes ?? null
|
||||||
return {
|
return {
|
||||||
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
|
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
|
||||||
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
|
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
|
||||||
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
|
backupUsedBytes: used,
|
||||||
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
|
backupQuotaBytes: quota !== null && quota > 0 ? quota : null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,13 +269,9 @@ const tonePercent = (value: number, warn: number, critical: number): Tone =>
|
|||||||
const conclusionText = (tone: Tone): string =>
|
const conclusionText = (tone: Tone): string =>
|
||||||
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
|
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
|
||||||
|
|
||||||
export function storageAlerts(
|
export function storageAlerts(inventory: BackupInventory | null): SummaryAlert[] {
|
||||||
inventory: BackupInventory | null,
|
|
||||||
archive: LibraryStorage | null,
|
|
||||||
archiveFailed: boolean
|
|
||||||
): SummaryAlert[] {
|
|
||||||
const state = hostState(inventory)
|
const state = hostState(inventory)
|
||||||
const facts = storageFacts(inventory, archive, archiveFailed)
|
const facts = storageFacts(inventory)
|
||||||
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
|
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
|
||||||
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
|
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
|
||||||
const diskTone: Tone = diskKnown
|
const diskTone: Tone = diskKnown
|
||||||
@@ -287,16 +282,16 @@ export function storageAlerts(
|
|||||||
: 'ok'
|
: 'ok'
|
||||||
: 'none'
|
: 'none'
|
||||||
|
|
||||||
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
|
const quotaKnown = facts.backupUsedBytes !== null && (facts.backupQuotaBytes ?? 0) > 0
|
||||||
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
|
const usedPercent = quotaKnown ? Math.round((facts.backupUsedBytes! / facts.backupQuotaBytes!) * 100) : 0
|
||||||
const quotaTone: Tone = quotaKnown
|
const quotaTone: Tone = quotaKnown
|
||||||
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
|
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
|
||||||
: 'none'
|
: 'none'
|
||||||
const bothTone: Tone =
|
const bothTone: Tone =
|
||||||
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
|
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
|
||||||
const overPhysical: Tone =
|
const overPhysical: Tone =
|
||||||
diskKnown && facts.archiveBudgetBytes !== null
|
diskKnown && facts.backupQuotaBytes !== null
|
||||||
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
|
? facts.backupQuotaBytes > facts.diskAvailableBytes!
|
||||||
? 'bad'
|
? 'bad'
|
||||||
: 'ok'
|
: 'ok'
|
||||||
: 'none'
|
: 'none'
|
||||||
@@ -315,11 +310,9 @@ export function storageAlerts(
|
|||||||
key: 'quota_low',
|
key: 'quota_low',
|
||||||
label: '配额不足',
|
label: '配额不足',
|
||||||
value: quotaKnown
|
value: quotaKnown
|
||||||
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
|
? `${formatSize(facts.backupUsedBytes)} / ${formatSize(facts.backupQuotaBytes)}(${usedPercent}%)`
|
||||||
: archiveFailed
|
: inventory?.quota_error
|
||||||
? UNKNOWN
|
? '配额未上报'
|
||||||
: archive?.available
|
|
||||||
? '配额未设置'
|
|
||||||
: UNKNOWN,
|
: UNKNOWN,
|
||||||
tone: quotaTone,
|
tone: quotaTone,
|
||||||
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
|
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
|
||||||
@@ -335,11 +328,11 @@ export function storageAlerts(
|
|||||||
key: 'quota_over_physical',
|
key: 'quota_over_physical',
|
||||||
label: '配额超出物理空闲',
|
label: '配额超出物理空闲',
|
||||||
value:
|
value:
|
||||||
diskKnown && facts.archiveBudgetBytes !== null
|
diskKnown && facts.backupQuotaBytes !== null
|
||||||
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
? `配额 ${formatSize(facts.backupQuotaBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
||||||
: UNKNOWN,
|
: UNKNOWN,
|
||||||
tone: overPhysical,
|
tone: overPhysical,
|
||||||
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
conclusion: diskKnown && facts.backupQuotaBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user