Compare commits
64 Commits
5ff6768027
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5af9b14a11 | |||
| 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 | |||
| e6a9acc32c | |||
| a3dcaa2f5b | |||
| c33c7e2700 | |||
| 91f9e00010 | |||
| 9952412eff | |||
| 4a12b20e9b | |||
| 8d873680cc | |||
| edd90b253e | |||
| d3c435183e | |||
| aa75dc6d44 | |||
| 25d574f3de | |||
| c96189db1b | |||
| 1dfa4fa7fc | |||
| d76363c117 | |||
| b2248a9b64 | |||
| 8c84c9c601 | |||
| 660320d646 | |||
| 0e33f21206 | |||
| 83bba09cde | |||
| 868924d074 | |||
| 03e622e9c7 | |||
| 9eef078ed0 | |||
| 2ca98a6a35 | |||
| 746b982c43 | |||
| e892bfdd48 | |||
| 768ad53fe2 | |||
| 7d91343e5f | |||
| cb026e8dd1 | |||
| 4b615abe53 | |||
| 341c3154ac | |||
| 63984dbfbe | |||
| 033f702d41 | |||
| 9eacf6473e | |||
| 6444814123 | |||
| 6ae5150fdf | |||
| 1f5bf72aec | |||
| ce2a155ebc | |||
| df69b278ce |
@@ -24,6 +24,12 @@ DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT=20m
|
||||
# Independent governance AI: endpoint/model/write-only API key are stored via the admin page.
|
||||
# Mount the same 32-byte regular 0600 master-key file into API and ordinary worker.
|
||||
QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||
# 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
||||
QA_AI_DNS_OVER_TLS=
|
||||
# Only opt in behind an already trusted TLS-terminating same-origin reverse proxy.
|
||||
|
||||
@@ -80,3 +80,39 @@ jobs:
|
||||
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
||||
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
||||
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
||||
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 "上报结束(通知失败不改变发布结论)"
|
||||
|
||||
+384
@@ -1,5 +1,389 @@
|
||||
# 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.417(知识治理发布助理接收提测交接)
|
||||
|
||||
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
|
||||
- 负责人回复预览确认范围,候选验收报告按实际归档归集到发布单。
|
||||
|
||||
## 开发快照 0.1.416(成员管理:新增成员改为右侧抽屉)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **新增入口移到标题栏**:成员表格下方常驻表单改为「成员与角色」标题右侧的
|
||||
`新增成员` 按钮,点击从右侧滑出抽屉;桌面宽 480px,窄屏铺满,表单字段与
|
||||
重置密码弹层共用同一套控件与校验提示。
|
||||
- **关闭前确认未保存输入**:Esc、取消、关闭按钮与遮罩点击在草稿非空时先确认;
|
||||
清空草稿后直接关闭并把焦点还给触发按钮;创建请求进行中忽略一切关闭请求。
|
||||
- **创建失败留在抽屉**:409 固定到用户名行,400 收敛为表单级提示,二者都保留
|
||||
已填内容;成功后关闭抽屉、刷新列表,页级错误/成功条只承载加载与行内操作。
|
||||
|
||||
### Changed
|
||||
|
||||
- **请求错误带 HTTP 状态**:`web/src/members.ts` 的失败改为 `MembersRequestError`
|
||||
(含 `status`),组件按 409/400 分流,不再依赖错误文案匹配。
|
||||
|
||||
## 开发快照 0.1.415(系统设置:刷新策略改为按模块分组的参数设置)
|
||||
|
||||
### Changed
|
||||
|
||||
- **入口改为「参数设置」**:系统设置左侧子导航与页面标题由「刷新策略」替换为「参数设置」,
|
||||
旧入口不再出现。
|
||||
- **参数按模块分组**:按产品归属固定为「来源与目录」(文档状态刷新间隔 15/30/60 秒、
|
||||
资源刷新间隔 30/60 秒)与「解析监控」(解析停滞阈值 30/60 分钟、入库并发上限 1..16);
|
||||
分组标题下不叠加说明段。
|
||||
- **数值输入与就地校验**:四个下拉改为文本数值输入;空值、非整数、`+15`/`1e1`、全角数字
|
||||
与越界值当场红字提示并禁用保存,不发请求;并发不再受旧下拉六档限制。
|
||||
- **保留现状说明与保存边界**:每项保留单位与调大/调小后果;解析停滞阈值保留 worker 1 分钟
|
||||
内生效说明;保存仍只提交参数分区,且原样回传未展示的 `finalizing_after_seconds` 与连接字段。
|
||||
- **去掉无消费者的收尾超时展示**:本页不再展示「收尾超时告警」,成功消息与底部摘要也不再
|
||||
播报它;API/DB/worker 与 `finalizing` 处理状态均未改动。
|
||||
|
||||
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **私网 http 控制台无法录入 API Key**:页面过去只看浏览器 URL 决定能否录入,而服务端写侧
|
||||
已按 `WEKNORA_ALLOW_PRIVATE_HTTP` 放行私网 http,导致「开关开着、输入框仍禁用」。GET
|
||||
`/api/v1/kb-bindings` 现在返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
|
||||
开关与受信反代判定;API 未返回该字段时前端按不可录入处理(失败关闭)。写侧判定不变。
|
||||
- **明文录入没有风险提示**:能力位开启且页面经非回环 http 打开时,Key 输入下方常驻提示密钥
|
||||
将明文传输;HTTPS 反代未配置 `QA_AI_TRUST_TLS_PROXY` 时改为提示该配置,不再笼统要求 HTTPS。
|
||||
- **`Host: [::1]`(无端口)被误判为非回环**:地址规范化统一去掉 IPv6 方括号与可选端口,
|
||||
回环写入不再被拒;受信反代能力位对 GET 只依赖 `X-Forwarded-Proto`(浏览器无法伪造该头)。
|
||||
|
||||
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **生产绑定保存重排待入库**:保存生产「知识库绑定」时,同一事务内把还没上传、
|
||||
原本瞄准旧生产目标库的待入库项改指向新库,并在保存提示里回报迁移条数;已经
|
||||
开始执行的发布项目标仍保持冻结,不会被改写。
|
||||
- **测试侧保存不再误搬生产作业**:两边共用 `test_publications` 待入库通道,重排
|
||||
现在只搬「上一次生效目标 → 新目标」成对的项;测试侧改绑不会再带走瞄准生产库的
|
||||
待入库项,生产侧也不猜「同 ID 语义」下的空目标。
|
||||
|
||||
## 开发快照 0.1.412(知识库绑定:清密钥保留名称与绑定身份)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **清除密钥保留知识库名称**:`key_action=clear` 不再把 `internal_kb_name` /
|
||||
`external_kb_name` 写成空串,改取事务内锁定行的旧值,且只在库 ID 未变时沿用
|
||||
(「同时改指向又清密钥」不会把旧库名贴到新库上);页面因此不再回落显示短 ID。
|
||||
生产侧同时保留已冻结的实例地址与租户,执行器的实例一致性检查不会把「只是没
|
||||
密钥」误判成换了实例。
|
||||
- **只填一端即可保存的存量用例对齐新语义**:留空 = 取消该方向绑定,不再断言
|
||||
`ErrInvalid`;用例改为断言保存成功、该侧为空、回退来源字段写明回退到哪、
|
||||
revision 递增,后续修订期望随之前移。
|
||||
- **清除后的真实库回归**:新增用例断言 `key_configured=false`、
|
||||
`verification=not_configured`、名称/库 ID/租户不变、`Resolve()` 失败关闭且不
|
||||
回落到部署文件里的旧 Key,历史表那一行只记布尔、不含任何密钥。该用例与既有
|
||||
集成用例一起登记进 `scripts/test-scope.json`(需显式一次性测试库,普通 CI 跳过)。
|
||||
|
||||
## 开发快照 0.1.411(知识库连接:四态验证、尾号回显与私网 http)
|
||||
|
||||
### Added
|
||||
|
||||
- **测试连接区分四态**:`POST /api/v1/kb-bindings/{environment}/catalog` 现在把
|
||||
401 与 403 分开返回「密钥无效」与「密钥无权限读取知识库列表」,与「地址不可达」
|
||||
「成功(读到 N 个库)」互不混淆,页面对应四种提示。
|
||||
- **密钥只回显尾 4 位**:绑定视图新增 `key_tail`,只用于展示;服务端不存尾号、
|
||||
不存明文,主密钥不可用时该字段为空而不是猜。
|
||||
- **清除密钥是独立动作**:`key_action=clear` 保留地址与内外库绑定,只把该侧凭据
|
||||
清空(需二次确认),消费者解析随后失败关闭,不会回落到服务器文件里的旧 Key。
|
||||
- **留空 = 取消绑定并回报回退**:视图新增 `internal_fallback` / `external_fallback`,
|
||||
测试侧回退到部署默认库、生产侧回退到「同 ID 语义」,保存提示里写明退到哪。
|
||||
- **生产绑定回报冻结计数**:`frozen` / `retargetable` 按在飞执行统计,已冻结的
|
||||
`release_item_executions.target_knowledge_base_id` 不被改写。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增 `WEKNORA_ALLOW_PRIVATE_HTTP`:只放行 RFC1918/回环/链路本地 http,公网 http
|
||||
仍拒绝。客户端、监控探活与连接页共用 `weknora.HTTPAllowed` 这一份判定,生产
|
||||
`18093` 同网段反代因此可用,页面不再出现「卡片可达、列库失败」。
|
||||
- 私网治理台(明文 http)录入密钥改用同源校验(Origin 与 Host 完全一致),
|
||||
仍拒绝跨站与公网来源。
|
||||
|
||||
## 开发快照 0.1.410(存储页快照状态区分)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 快照超过 15 分钟后不再把目录区写成“元数据快照未接线”:按接口字段区分
|
||||
未配置、缺失、过期、无效、不完整,目录与历史分别标注真实状态。
|
||||
- 过期快照不展示旧批次路径、旧目录路径或旧容量预测;目录输入清空并提示等待宿主
|
||||
重新采集;历史区只说明过期原因,不回退冒充“没有备份”。
|
||||
- 读取源/采集时间/读回时间按同一快照状态展示:过期仍显示当时的采集时间与年龄,
|
||||
读回时间单独取 API 时间,不混用。
|
||||
- 增加过期与未配置反例回归,覆盖旧批次/旧容量不得复用。
|
||||
|
||||
## 开发快照 0.1.409(存储与备份页面显示口径修正)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 完整快照不再把宿主备份文件系统可写当成部署错误:去掉“挂载可写 / 需改 :ro”提示,
|
||||
明确备份盘由备份主机写入,API 只读元数据快照。
|
||||
- 容量已实测且完整时磁盘告警为正常,不再出现“缺主机磁盘读数”;配额相关三项仅标注
|
||||
配额字段未接线,摘要区分“磁盘项正常”与“磁盘项无法判定”。
|
||||
- 采集时间(宿主快照)与读回时间(API)分列;快照年龄/新鲜度取快照字段;
|
||||
“重新盘点”明确只重读 `metadata.json`,不会让宿主重新采集。
|
||||
- 空间预测注明以上次整批实际占盘为参考,不是接口预测。
|
||||
- 小文件不足 0.05 MiB 显示 KiB,避免非零体积被舍成 0.0 MiB。
|
||||
|
||||
## 开发快照 0.1.408(备份盘点改宿主采集器:权限失败不再产出部分字节)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复 API 以 uid 1000 遍历 root:root 0700 备份目录时 `sizes_complete=false` 但
|
||||
`Database.ActualBytes` 仍保留部分计数的问题:API 不再遍历备份目录,只读宿主快照;
|
||||
快照不完整/陈旧/缺失时批次与子库字节全部为 `null`,页面不画容量图、不使用部分字节。
|
||||
- 容量图与任何可写预测只在“快照新鲜 + 完整 + 路径校验通过 + 容量实测”时出现;
|
||||
权限失败回归覆盖采集器注入 `PermissionError` 与 API 拒绝部分字段。
|
||||
- 单库 `696320` 只作现场核对值,代码与测试不写死。
|
||||
|
||||
### Added
|
||||
|
||||
- `scripts/collect_backup_metadata.py`:宿主单次只读采集器,stat/du + MANIFEST,
|
||||
原子写 `metadata.json`,不读数据库内容、不跟随符号链接、权限失败置空字节。
|
||||
统计口径与 `du -sB1` 对齐:目录自身计入、树内硬链接按 `(dev,ino)` 去重、
|
||||
单库与整批各自独立测量;MANIFEST 只接受批次目录内常规非符号链接文件,
|
||||
打开带 `O_NOFOLLOW`。
|
||||
- `GET /api/v1/backup-schedule/inventory` 读取并校验快照:schema、root、批次/子库路径、
|
||||
采集时效、完整性;批次/子库字节可空。
|
||||
- 文档改为 28189 快照挂载、采集器安装/定时、可验证字段与写能力清单。
|
||||
|
||||
## 开发快照 0.1.407(备份盘点:只读挂载读真实批次与容量)
|
||||
|
||||
### Added
|
||||
|
||||
- `GET /api/v1/backup-schedule/inventory`:只读盘点 `rds-logical` 批次、MANIFEST 状态、每个
|
||||
子库完整主机路径、表观/实际占盘,以及只读挂载文件系统的实测容量。
|
||||
- 新包 `internal/backupinventory`:批次按目录戳倒序,`*.incomplete` 不计入;清单缺失/损坏
|
||||
逐批标注;实际占盘按 `st_blocks×512`;容量用 `statfs`,并与容器根盘比较设备号。
|
||||
- 系统设置 → 存储与备份接入盘点:整盘色带、批次列表、子库路径复制、清单失败与未接线分开;
|
||||
SSH 计划读回与文件盘点独立加载,互不掩盖失败。
|
||||
- 文档 `docs/STORAGE_BACKUP_READONLY_API.md`:28189 候选接口契约、`:ro` 最小挂载与权限要求、
|
||||
可验证字段、现有写路径与尚未实现的后端写能力。
|
||||
|
||||
### Changed
|
||||
|
||||
- 备份策略目录改为只读展示盘点到的 `host_root`;配额/预留仍无后端字段,保留占位并标未知。
|
||||
- 磁盘告警只在“挂载与容器根盘分离 + 容量实测 + 有批次占盘参考”时判定;容器根盘读数只作排障。
|
||||
|
||||
### Security
|
||||
|
||||
- 盘点不执行远端文件命令、不写备份目录;只接受只读挂载,拒绝跟随符号链接批次,扫描有上限。
|
||||
|
||||
## 开发快照 0.1.406(备份主机状态不得由历史推断)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 平台未挂载主机凭据时不再断言「定时计划不会执行」:改为无法确认当前主机计划,
|
||||
远端 cron 可能仍在执行;历史下发记录不能代替实时状态。
|
||||
- 「最后下发」明确标为历史记录,只证明当时下发过,不能代表当前主机计划或执行状态。
|
||||
- 未探测与探测失败分开:只读计划先返回时显示「尚未探测」,不误报「连接失败」;
|
||||
「与设置是否一致」只在真正读回主机计划后判定,未读到时显示无法比对。
|
||||
- 回归:无凭据但存在有效历史下发、已接线但尚未探测两例都不得出现执行断言。
|
||||
|
||||
## 开发快照 0.1.405(存储与备份:单页对齐真实接口)
|
||||
|
||||
### Added
|
||||
|
||||
- 「系统设置 → 存储与备份」按已批准交互稿落成单页:范围与读写方向、整盘占用与四项告警、
|
||||
备份策略、最近批次与子库清单、运行进度、恢复验证;立即备份按钮明确标注"整批全部业务库"。
|
||||
- 整盘色带与四项告警(磁盘不足/配额不足/两者同时/配额超出物理空闲)抽成纯函数,用隔离夹具
|
||||
覆盖正常、单项不足、同时不足与缺读数分支;生产页面在无磁盘接口时只显示"未接线"。
|
||||
- 策略区保留原型里的目录、总配额、磁盘预留位置,并逐项标注后端无对应字段、不会被保存。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「立即备份一次」不再显示成单库动作:`POST /api/v1/backup-schedule/run` 没有单库参数,
|
||||
单库按钮会触发整批,因此页面禁用单库动作并说明"范围未经证实"。
|
||||
- 备份记录只展示主机 MANIFEST 的最近一批与库名;历史批次、子库路径、恢复验证没有接口,
|
||||
保留位置并注明原因,不拼造路径或假成功。
|
||||
- 「归档占用」改名为"版本快照,不是数据库备份",与数据库整库备份分开计量,避免把两者相加。
|
||||
|
||||
## 开发快照 0.1.404(单次任务固定同一 WeKnora 连接)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 上传、轮询、验收、移除先 `BeginTask` 解析一次并核验对象租户,返回的 context 钉住同一
|
||||
不可变连接;后续上传、列库恢复、查询、chunk 读取、删除与删除后重查都复用它,不再
|
||||
各自 `Resolve`。任务开始后页面改绑实例,旧任务也不会中途切到新实例。
|
||||
- 回归:真实客户端假端点断言一次处理只解析一次且全部打到同一实例;四个 handler 用
|
||||
TaskConnector 假客户端断言所有业务调用携带同一连接令牌,含上传恢复和删除重查。
|
||||
|
||||
## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例)
|
||||
|
||||
### Added
|
||||
|
||||
- 迁移 000082:`production_kb_bindings` 冻结每个方向核验时的实例地址与租户,
|
||||
`release_item_executions` 冻结 `target_instance_url/target_tenant_id`,
|
||||
`test_publications` 记录对象实际写入的测试实例地址/租户。
|
||||
- 文档发布执行器在 `Contract/Prepare/Activate/Restore/Compensate` 前统一核对实例身份:
|
||||
网页在实例 A 列库、执行器连实例 B 时,即使知识库 ID/租户相同也以
|
||||
`release_contract_mismatch` 失败关闭,不写目标;整库发布目标不变。
|
||||
- 测试入库的上传/轮询/验收/移除按对象记录的身份核对当前连接;改绑实例或租户后,
|
||||
旧对象不会在克隆实例上继续轮询、验收或删除。
|
||||
- 回归:实例 A/B 同名同 ID 的隔离夹具、绑定身份写入计划、四个测试 handler 的正反例。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「知识库绑定」保存必须为对内/对外各选一个库;显式“未绑定”不再回落部署默认 ID,
|
||||
避免换绑实例后把旧实例的默认库带到新实例。旧页面留下的既有绑定行保持原语义。
|
||||
|
||||
### Security
|
||||
|
||||
- 实例身份不匹配一律失败关闭;旧发布项缺少身份信息时也不再猜测,避免写错克隆实例。
|
||||
|
||||
## 开发快照 0.1.402(知识库绑定:按环境一次保存连接与内外库)
|
||||
|
||||
### Added
|
||||
|
||||
- 「系统设置 → 知识库绑定」:测试 090 / 生产 090 分环境工作区,同一时间只编辑一个环境;顶部只读显示当前生效的对内/对外库。
|
||||
- 草稿可填写本环境服务地址与 API Key;「验证并读取知识库」由服务器真实列库(分页),明确区分可读、空库、无权限、不可达。
|
||||
- 列表按「名称 + 短 ID」区分同名库;对内与对外选同一个库会被拒绝。一次保存同时写入连接与内外绑定,并回读真实生效值。
|
||||
- 新增 `GET /api/v1/kb-bindings`、`POST /api/v1/kb-bindings/{environment}/catalog`、`PUT /api/v1/kb-bindings/{environment}`;读写分离,写仅管理员。
|
||||
- 迁移 000081:`weknora_environment_bindings` 与修订历史;密钥只存 AES-256-GCM 密文,主密钥来自独立 `WEKNORA_BINDING_MASTER_KEY_FILE`。
|
||||
- 保存会校验所选库属于候选实例(同一地址与密钥读取),并在同一事务内镜像测试路由/生产文档级绑定;测试环境同时重排未上传的待入库项并回报数量。
|
||||
|
||||
### Changed
|
||||
|
||||
- 原「知识库映射 → WeKnora 连接」入口并入「知识库绑定」;探活、封存源、整库发布目标与旧文档级目标收进折叠诊断,保留入口但不再提供第二个保存路径。
|
||||
- 消费者(readiness、上传/轮询、列库、监控探活、生产列库)统一从加密存储解析当前连接;没有新行时继续使用旧部署的文件凭据与默认绑定。
|
||||
- 整库发布实际目标仍只读,并明确由部署配置决定;本页保存不触发生产写入、导入、发布或停服。
|
||||
|
||||
### Security
|
||||
|
||||
- API Key 不回显、不写日志/URL/浏览器存储;更换地址必须重新录入密钥,旧密钥不会转发到新地址,也不会跨环境取用。
|
||||
- 保存使用修订号与行锁:并发或失败时旧绑定保持不变,未保存草稿不影响当前生效值。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 生产 WeKnora 健康探活改为跟随当前有效端点(原实现绕过 resolver,改地址后仍探旧值)。
|
||||
|
||||
## 开发快照 0.1.401(AI 模型连接:当前生效 + 独立草稿)
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → AI 模型连接」按交互稿重排:顶部只读「当前生效」(模型 + 服务端真实核验态与地址),
|
||||
下方地址/模型是独立草稿;测试草稿只回显核验结果,不更新当前连接,「测试中」与「保存中」分开提示。
|
||||
- 保存成功一律用服务端响应回显当前信息;草稿改动或版本冲突(409)都会作废上一次草稿测试,
|
||||
冲突时载入最新已保存配置并要求按新版本重测。
|
||||
- 已配置密钥默认收起不回显,只有「更换密钥」或首次录入才出现输入框;更换基础地址强制重新录入密钥,
|
||||
取消更换无副作用。安全传输与独立密钥存储限制保持不变。
|
||||
- 「清除密钥并停用」收进单独折叠区,写明对问答分析与中文翻译的影响并二次确认;只提交已保存连接,
|
||||
未保存草稿不会被夹带,取消不产生任何请求。
|
||||
- 合并分区标题与组件内重复的说明文字,模型连接说明只保留一处。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 模型连接的测试/保存不再共用同一个忙碌状态,避免把草稿测试结果误当成已生效配置。
|
||||
|
||||
## 开发快照 0.1.399(系统设置分区调整:AI 模型连接 / 知识库映射)
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -77,7 +77,7 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|
||||
|---|---|---|
|
||||
| React/Vite + Web Nginx | 提供静态页面,同源转发 `/api/` 和 `/health` | [前端开发代理](web/vite.config.ts)、[Compose 的 Nginx 配置](deploy/nginx.conf) |
|
||||
| Go API + 治理 PostgreSQL | 认证、角色、来源、绑定、审核、任务与发布记录。云测试使用独立逻辑库 `knowledge_governance_test` | [API](cmd/api)、[接口契约](api/openapi.yaml) |
|
||||
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源接入](docs/OPERATIONS_RUNBOOK.md#接入外部平台) |
|
||||
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源接入](docs/OPERATIONS_RUNBOOK.md#接入外部平台)、[来源认证](docs/SOURCE_AUTH_CONFIGURATION.md) |
|
||||
| 发布 worker + 生产 WeKnora | 按已锁定的批次和目标执行受控发布与读回。问答端通过下游服务使用已发布知识 | [发布 worker](cmd/release-worker)、[操作手册](docs/OPERATIONS_RUNBOOK.md) |
|
||||
|
||||
从自己的电脑做系统设置验收,使用 SSH 转发后的 `http://127.0.0.1:28189/`。云测试主控制台使用受限内网入口 `http://100.85.111.121:8088/`。仓内 Compose 则将宿主 `8088` 映射到 Web 容器 `8080`。选择入口时先确认要看的部署。隧道命令、生产 `090` 服务地址和 HTTPS 反代示例见[运维手册](docs/OPERATIONS_RUNBOOK.md#入口与反向代理)。
|
||||
@@ -109,7 +109,7 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|
||||
|
||||
## 开发与 CI
|
||||
|
||||
本机和 QA 虚拟机的依赖安装、前后端启动、测试命令及 PostgreSQL 测试库准备见 [开发与测试指南](docs/DEVELOPMENT_AND_TESTING.md)。
|
||||
本机和 QA 虚拟机的依赖安装、前后端启动、测试命令及 PostgreSQL 测试库准备见 [开发与测试指南](docs/DEVELOPMENT_AND_TESTING.md)。页面验收标准见[运维手册](docs/OPERATIONS_RUNBOOK.md#开发测试和现场验收)。
|
||||
|
||||
```bash
|
||||
make verify # 完整检查入口:本地与 CI 使用同一套规则
|
||||
@@ -122,7 +122,7 @@ make list # 查看检查清单与适用范围
|
||||
|
||||
## 问答运营模型配置
|
||||
|
||||
管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。页面顶部显示当前已保存的模型与服务端核验结果,下方编辑的是独立草稿:测试连接只核验草稿,保存才更新当前连接,保存成功后按服务端响应回显。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显、默认收起,只有「更换密钥」或首次录入才显示输入框,更换基础地址须重新录入密钥;「清除密钥并停用」在单独折叠区里二次确认,只作用于已保存连接。录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
|
||||
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
|
||||
|
||||
|
||||
@@ -1972,6 +1972,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/backup-schedule/inventory": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getBackupScheduleInventory",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、备份根累计占用、配额与文件系统容量(陈旧/不完整一律未知)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/ServiceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/backup-schedule/apply": {
|
||||
"post": {
|
||||
"tags": [
|
||||
@@ -3707,6 +3730,61 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings": {
|
||||
"get": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "getKBBindings",
|
||||
"summary": "读取测试/生产环境的 WeKnora 连接与内外库绑定(密钥不回显)",
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings/{environment}/catalog": {
|
||||
"post": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "catalogKBBindingConnection",
|
||||
"summary": "用草稿地址与密钥真实列库(管理员,只读,分页)",
|
||||
"parameters": [
|
||||
{"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBCatalogInput"}}}
|
||||
},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"409": {"$ref": "#/components/responses/Conflict"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/kb-bindings/{environment}": {
|
||||
"put": {
|
||||
"tags": ["Settings"],
|
||||
"operationId": "saveKBBinding",
|
||||
"summary": "一次保存当前环境的连接与内外库绑定(管理员)",
|
||||
"parameters": [
|
||||
{"name": "environment", "in": "path", "required": true, "schema": {"type": "string", "enum": ["test", "production"]}}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/KBBindingSaveInput"}}}
|
||||
},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"409": {"$ref": "#/components/responses/Conflict"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"$ref": "#/components/responses/ServiceUnavailable"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/production-kb-bindings": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -6084,6 +6162,74 @@
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"KBBindingEnvironmentView": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["environment", "revision", "base_url", "key_configured", "internal_kb_id", "external_kb_id", "verification", "storage_ready", "source"],
|
||||
"properties": {
|
||||
"environment": {"type": "string", "enum": ["test", "production"]},
|
||||
"revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_configured": {"type": "boolean"},
|
||||
"key_source": {"type": "string", "enum": ["sealed", "file", "none"]},
|
||||
"internal_kb_id": {"type": "string"},
|
||||
"internal_kb_name": {"type": "string"},
|
||||
"external_kb_id": {"type": "string"},
|
||||
"external_kb_name": {"type": "string"},
|
||||
"verification": {"type": "string"},
|
||||
"checked_at": {"type": ["string", "null"]},
|
||||
"updated_by": {"type": "string"},
|
||||
"updated_at": {"type": ["string", "null"]},
|
||||
"source": {"type": "string", "enum": ["web", "legacy"]},
|
||||
"storage_ready": {"type": "boolean"},
|
||||
"replanned": {"type": "integer", "minimum": 0},
|
||||
"retired_duplicates": {"type": "integer", "minimum": 0}
|
||||
}
|
||||
},
|
||||
"KBBindingSnapshot": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["environments", "storage_ready"],
|
||||
"properties": {
|
||||
"environments": {"type": "array", "items": {"$ref": "#/components/schemas/KBBindingEnvironmentView"}},
|
||||
"storage_ready": {"type": "boolean"}
|
||||
}
|
||||
},
|
||||
"KBCatalogInput": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["base_url", "key_action", "page", "page_size"],
|
||||
"properties": {
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_action": {"type": "string", "enum": ["keep", "replace"]},
|
||||
"api_key": {"type": "string", "writeOnly": true, "maxLength": 4096},
|
||||
"page": {"type": "integer", "minimum": 1},
|
||||
"page_size": {"type": "integer", "minimum": 1, "maximum": 100}
|
||||
}
|
||||
},
|
||||
"KBBindingSaveInput": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["base_url", "key_action", "internal_kb_id", "external_kb_id"],
|
||||
"properties": {
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_url": {"type": "string"},
|
||||
"key_action": {"type": "string", "enum": ["keep", "replace"]},
|
||||
"api_key": {"type": "string", "writeOnly": true, "maxLength": 4096},
|
||||
"internal_kb_id": {"type": "string"},
|
||||
"external_kb_id": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"KBCatalogOption": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"knowledge_count": {"type": "integer"}
|
||||
}
|
||||
},
|
||||
"PPConnectionDraft": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
|
||||
+117
-39
@@ -8,6 +8,8 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -15,8 +17,10 @@ import (
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
@@ -53,6 +57,25 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s
|
||||
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
|
||||
}
|
||||
|
||||
// 宿主快照的展示路径必须与采集 root 同一份:容器内快照路径不可给操作者复制,
|
||||
// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。
|
||||
func backupInventoryHostRoot(config appconfig.Config) string {
|
||||
if config.BackupHostReadonlyHostPath != "" {
|
||||
return config.BackupHostReadonlyHostPath
|
||||
}
|
||||
return path.Join(config.BackupHostRoot, "rds-logical")
|
||||
}
|
||||
|
||||
func backupInventorySource(config appconfig.Config) string {
|
||||
if config.BackupHostReadonlySource != "" {
|
||||
return config.BackupHostReadonlySource
|
||||
}
|
||||
if config.BackupHostTarget == "" {
|
||||
return ""
|
||||
}
|
||||
return config.BackupHostTarget + ":" + backupInventoryHostRoot(config)
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -98,57 +121,102 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
// 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在
|
||||
// release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。
|
||||
actionStore := postgresstore.NewStore(pool)
|
||||
productionEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.ProductionWeKnoraBaseURL
|
||||
}
|
||||
testEndpointResolver := func(resolveCtx context.Context) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
// P10 readiness 与执行链看同一目标:网页保存的端点、当前持久化绑定、同一份
|
||||
// API Key。启动时只捕获 resolver,不捕获任何一项的值(F13:旧 env 绑定 404)。
|
||||
readinessResolver := newWeKnoraReadinessResolver(
|
||||
func(resolveCtx context.Context) string {
|
||||
if saved := testEndpointResolver(resolveCtx); saved != "" {
|
||||
return saved
|
||||
kbBindings := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
|
||||
Timeout: 10 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
|
||||
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
},
|
||||
AllowPrivateHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.WeKnoraAllowPrivateHTTP,
|
||||
kbbinding.EnvProduction: config.WeKnoraAllowPrivateHTTP,
|
||||
},
|
||||
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
|
||||
settings, err := actionStore.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if env == kbbinding.EnvProduction {
|
||||
if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.ProductionWeKnoraBaseURL
|
||||
}
|
||||
if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
config.InternalRoutingKnowledgeBaseID,
|
||||
func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, err
|
||||
LegacyKey: func(env string) (string, error) {
|
||||
path := config.TestWeKnoraAPIKeyFile
|
||||
if env == kbbinding.EnvProduction {
|
||||
path = config.ProductionWeKnoraAPIKeyFile
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
return weknora.ReadAPIKeyFile(path)
|
||||
},
|
||||
func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
)
|
||||
LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) {
|
||||
if env == kbbinding.EnvProduction {
|
||||
internal, external, _, err := actionStore.LoadProductionKBBindings(resolveCtx)
|
||||
return internal, external, err
|
||||
}
|
||||
internal, external, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
return internal, external, err
|
||||
},
|
||||
})
|
||||
productionEndpointResolver := func(resolveCtx context.Context) string {
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction)
|
||||
}
|
||||
testEndpointResolver := func(resolveCtx context.Context) string {
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest)
|
||||
}
|
||||
// P10 readiness 与执行链看同一目标:当前持久化绑定、当前有效连接(加密存储优先、
|
||||
// 旧部署 file 凭据兜底)。任何一项读取失败都必须显式报错,不能静默退回旧值。
|
||||
readinessResolver := func(resolveCtx context.Context) (readiness.Target, error) {
|
||||
target := readiness.Target{KnowledgeBaseID: config.InternalRoutingKnowledgeBaseID}
|
||||
stored, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
if err != nil {
|
||||
return readiness.Target{}, fmt.Errorf("读取当前知识库绑定失败")
|
||||
}
|
||||
if strings.TrimSpace(stored) != "" {
|
||||
target.KnowledgeBaseID = strings.TrimSpace(stored)
|
||||
}
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
if err != nil {
|
||||
return readiness.Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err)
|
||||
}
|
||||
target.BaseURL, target.APIKey = connection.BaseURL, connection.APIKey
|
||||
return target, nil
|
||||
}
|
||||
readinessProber := readiness.Prober{
|
||||
Resolve: readinessResolver,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
Resolve: readinessResolver,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
weknoraProbe := func(probeCtx context.Context) (string, error) {
|
||||
result := readinessProber.Check(probeCtx)
|
||||
return result.Target, result.Err
|
||||
}
|
||||
knowledgeBaseLister := &weKnoraLister{
|
||||
endpoint: func(resolveCtx context.Context) string {
|
||||
if saved := testEndpointResolver(resolveCtx); saved != "" {
|
||||
return saved
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
resolve: func(resolveCtx context.Context) (string, string, error) {
|
||||
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return connection.BaseURL, connection.APIKey, err
|
||||
},
|
||||
readKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -160,6 +228,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
TestAllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
ProductionAllowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
})
|
||||
productionKnowledgeBases := &productionKnowledgeBaseLister{bindings: kbBindings, timeout: 10 * time.Second, allowDockerHTTP: config.ProductionWeKnoraAllowDockerHTTP}
|
||||
// 「版本记录」:只读查询面在 API 侧接线;真正的抓取在 worker 侧(未配置来源即未接线)。
|
||||
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
@@ -227,7 +296,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
RoutingBindings: postgresstore.NewStore(pool),
|
||||
KnowledgeBases: knowledgeBaseLister,
|
||||
ProductionBindings: postgresstore.NewStore(pool),
|
||||
ProductionKnowledgeBases: serviceTargetVerifier,
|
||||
ProductionKnowledgeBases: productionKnowledgeBases,
|
||||
KBBindings: kbBindings,
|
||||
WeKnoraAllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL,
|
||||
ServiceTargetVerifier: serviceTargetVerifier,
|
||||
ProductionReleaseRequestsEnabled: config.ProductionReleaseRequestsEnabled,
|
||||
@@ -275,6 +346,13 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ScriptDir: config.BackupHostScriptDir,
|
||||
Root: config.BackupHostRoot,
|
||||
}),
|
||||
BackupInventory: backupinventory.New(backupinventory.Config{
|
||||
MetadataPath: config.BackupHostMetadataPath,
|
||||
HostRoot: config.BackupHostReadonlyHostPath,
|
||||
BackupRoot: config.BackupHostRoot,
|
||||
Source: backupInventorySource(config),
|
||||
MaxAge: config.BackupHostMetadataMaxAge,
|
||||
}),
|
||||
Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour},
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
+47
-11
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
@@ -51,29 +52,64 @@ func newWeKnoraReadinessResolver(
|
||||
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
|
||||
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
|
||||
type weKnoraLister struct {
|
||||
endpoint func(context.Context) string
|
||||
readKey func() (string, error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
|
||||
baseURL := ""
|
||||
if lister.endpoint != nil {
|
||||
baseURL = strings.TrimSpace(lister.endpoint(ctx))
|
||||
if lister.resolve == nil {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
baseURL, apiKey, err := lister.resolve(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
baseURL = strings.TrimSpace(baseURL)
|
||||
if baseURL == "" {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
apiKey, err := lister.readKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if strings.TrimSpace(apiKey) == "" {
|
||||
return nil, fmt.Errorf("WeKnora API Key 未配置")
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP})
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.ListKnowledgeBases(ctx)
|
||||
}
|
||||
|
||||
// productionKnowledgeBaseLister 列生产端知识库时使用「生产环境」保存的连接
|
||||
// (加密密钥),而不是另一条文件凭据。显式传入的地址必须与已保存连接一致,
|
||||
// 防止把生产密钥发往另一个地址。
|
||||
type productionKnowledgeBaseLister struct {
|
||||
bindings *kbbinding.Store
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (lister *productionKnowledgeBaseLister) ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error) {
|
||||
if lister.bindings == nil {
|
||||
return nil, fmt.Errorf("生产知识库连接存储未接线")
|
||||
}
|
||||
target, err := lister.bindings.Resolve(ctx, kbbinding.EnvProduction)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if explicit := strings.TrimSpace(baseURL); explicit != "" && explicit != target.BaseURL {
|
||||
return nil, fmt.Errorf("生产地址与已保存的连接不一致:请在生产工作区重新保存连接")
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: target.BaseURL, APIKey: target.APIKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP, AllowPrivateHTTP: lister.allowPrivateHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -96,9 +96,8 @@ func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) {
|
||||
defer second.Close()
|
||||
endpoint := first.URL
|
||||
lister := &weKnoraLister{
|
||||
endpoint: func(context.Context) string { return endpoint },
|
||||
readKey: func() (string, error) { return "key-1", nil },
|
||||
timeout: time.Second,
|
||||
resolve: func(context.Context) (string, string, error) { return endpoint, "key-1", nil },
|
||||
timeout: time.Second,
|
||||
}
|
||||
bases, err := lister.ListKnowledgeBases(context.Background())
|
||||
if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" {
|
||||
|
||||
@@ -163,7 +163,12 @@ func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot release
|
||||
if err != nil {
|
||||
return cleanup(errors.New("create target WeKnora verifier"))
|
||||
}
|
||||
documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
|
||||
documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{
|
||||
Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch,
|
||||
Objects: objectImporter, Verifier: verifier,
|
||||
TargetInstanceURL: route.Target.WeKnora.BaseURL,
|
||||
TargetTenantID: route.TenantID,
|
||||
})
|
||||
if err != nil {
|
||||
return cleanup(errors.New("create v0.7.1 document target"))
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
|
||||
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("release-executor workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -74,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
TestWeKnoraEnabled: true,
|
||||
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
|
||||
}
|
||||
if _, err := workerHandlers(nil, capture); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err)
|
||||
}
|
||||
capture.TestWeKnoraEnabled = false
|
||||
capture.PPScanEnabled = false
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture)
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("capture workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
+66
-14
@@ -19,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
@@ -173,6 +174,54 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
}
|
||||
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID).
|
||||
WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot)
|
||||
kbBindings := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: config.WeKnoraBindingMasterKeyFile,
|
||||
Timeout: 10 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{
|
||||
kbbinding.EnvTest: config.TestWeKnoraAllowDockerHTTP,
|
||||
kbbinding.EnvProduction: config.ProductionWeKnoraAllowDockerHTTP,
|
||||
},
|
||||
LegacyBaseURL: func(resolveCtx context.Context, env string) string {
|
||||
settings, err := store.GetActiveUISettings(resolveCtx)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if env == kbbinding.EnvProduction {
|
||||
if value := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.ProductionWeKnoraBaseURL
|
||||
}
|
||||
if value := strings.TrimSpace(settings.TestWeKnoraBaseURL); value != "" {
|
||||
return value
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LegacyKey: func(env string) (string, error) {
|
||||
path := config.TestWeKnoraAPIKeyFile
|
||||
if env == kbbinding.EnvProduction {
|
||||
path = config.ProductionWeKnoraAPIKeyFile
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
return weknora.ReadAPIKeyFile(path)
|
||||
},
|
||||
LegacyBinding: func(resolveCtx context.Context, env string) (string, string, error) {
|
||||
if env == kbbinding.EnvProduction {
|
||||
internal, external, _, err := store.LoadProductionKBBindings(resolveCtx)
|
||||
return internal, external, err
|
||||
}
|
||||
internal, external, _, err := store.LoadRoutingKBBindings(resolveCtx)
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
return internal, external, err
|
||||
},
|
||||
})
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
|
||||
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
|
||||
@@ -211,7 +260,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
} else if repaired > 0 {
|
||||
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
|
||||
}
|
||||
handlers, err := workerHandlers(store, config)
|
||||
handlers, err := workerHandlers(store, config, kbBindings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -324,7 +373,7 @@ func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersiste
|
||||
return nil
|
||||
}
|
||||
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) {
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) {
|
||||
handlers := map[string]jobs.Handler{
|
||||
"demo": func(_ context.Context, job jobs.Job) error {
|
||||
log.Printf("completed demo job id=%s", job.ID)
|
||||
@@ -526,24 +575,27 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
return handlers, nil
|
||||
}
|
||||
// 启动只验证凭据“存在”(缺失像以前一样拒绝启动);具体值仍由 resolver 每次调用重读。
|
||||
if _, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); err != nil {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", err)
|
||||
// 启动只验证“有一条可用凭据”:旧部署是文件,新部署可以是加密存储里的连接。
|
||||
// 两者都没有时不再静默启动,仍像以前一样拒绝;具体值由 resolver 每次重读。
|
||||
storageReady := kbBindings != nil && kbBindings.StorageReady()
|
||||
if _, fileErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); fileErr != nil && !storageReady {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", fileErr)
|
||||
}
|
||||
// 与 API 探测共用同一有效目标:网页保存的端点优先、env 只作未配置兜底;
|
||||
// 当前持久化绑定优先、env 兜底;凭据每次调用重读同一 key 文件。
|
||||
// 与 API 探测共用同一有效目标:加密存储里的连接优先、旧部署文件/端点兜底;
|
||||
// 当前持久化绑定优先、env 兜底。
|
||||
remoteResolver := readiness.Resolver{
|
||||
Endpoint: func(resolveCtx context.Context) string {
|
||||
if settings, settingsErr := store.GetActiveUISettings(resolveCtx); settingsErr == nil && strings.TrimSpace(settings.TestWeKnoraBaseURL) != "" {
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, bindingErr
|
||||
},
|
||||
ReadKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
if kbBindings == nil {
|
||||
key, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
|
||||
return config.TestWeKnoraBaseURL, key, err
|
||||
}
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
}
|
||||
client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) {
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{})
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
PPScanLedgerPath: filepath.Join(root, "state.jsonl"),
|
||||
PPScanManifestPath: filepath.Join(root, "manifest.json"),
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
|
||||
func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) {
|
||||
config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"}
|
||||
_, err := workerHandlers(nil, config)
|
||||
_, err := workerHandlers(nil, config, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) {
|
||||
TestWeKnoraMaxUploadBytes: 1024,
|
||||
TestAcceptancePolicyVersion: "structural-v1",
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -16,9 +16,17 @@ services:
|
||||
BACKUP_HOST_TARGET: weknora-test
|
||||
BACKUP_HOST_SCRIPT_DIR: /opt/weknora-test
|
||||
BACKUP_HOST_ROOT: /srv/kb-backups
|
||||
# 只读盘点(批次/子库路径/实测容量)与上面的 SSH 计划读回独立。
|
||||
# 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开:
|
||||
# 宿主采集器原子写 metadata.json,API 只读挂载输出目录(不挂备份目录):
|
||||
# BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
|
||||
# BACKUP_HOST_METADATA_MAX_AGE: 15m
|
||||
# BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
|
||||
# BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
|
||||
volumes:
|
||||
- ./secrets/release-sim:/run/release-secrets:ro
|
||||
- ./secrets/backup-host:/run/backup-host:ro
|
||||
# - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
|
||||
|
||||
release-worker:
|
||||
environment:
|
||||
|
||||
@@ -52,11 +52,25 @@ services:
|
||||
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
|
||||
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
|
||||
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
|
||||
# 「存储与备份」摘要页的归档配额(字节)。留空 = 未设置,页面显示"配额未设置";
|
||||
# 显式写 0 会被 appconfig 拒绝(必须为正整数),所以只能用空串表示未设置。
|
||||
LIBRARY_CAPACITY_BUDGET_BYTES: "${LIBRARY_CAPACITY_BUDGET_BYTES:-}"
|
||||
# 宿主每 5 分钟上报的整库备份元数据快照(collector 写入,平台只读)。
|
||||
# 留空 = 未接线,页面按验收显示"主机未上报";路径必须是宿主机侧绝对路径。
|
||||
BACKUP_HOST_METADATA_PATH: "${BACKUP_HOST_METADATA_PATH:-}"
|
||||
BACKUP_HOST_METADATA_MAX_AGE: "${BACKUP_HOST_METADATA_MAX_AGE:-15m}"
|
||||
BACKUP_HOST_READONLY_HOST_PATH: "${BACKUP_HOST_READONLY_HOST_PATH:-}"
|
||||
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
|
||||
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
|
||||
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
|
||||
# Mount this independent master-key file read-only using the deployment overlay.
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
||||
# 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
|
||||
# P10 readiness probe reads the routing KB with the same scoped key.
|
||||
|
||||
@@ -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,14 @@
|
||||
# 知识治理候选和批次验收
|
||||
|
||||
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
|
||||
## 需求单的六个状态
|
||||
|
||||
## 发起候选
|
||||
新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
|
||||
|
||||
## 在原需求单发布
|
||||
|
||||
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
||||
|
||||
## 旧版独立发布单的存量操作
|
||||
|
||||
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
||||
|
||||
@@ -28,7 +34,21 @@
|
||||
|
||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||
|
||||
运维按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)将已验收归档传到主站只读收件目录并核对摘要。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
### 候选访问测试 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 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
|
||||
@@ -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` |
|
||||
@@ -55,15 +55,33 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
|
||||
|
||||
| 平台与用途 | 管理员或运维怎样接 | 接通的证据 |
|
||||
|---|---|---|
|
||||
| 钉钉知识库,取目录和文件 | 系统设置 → 数据源配置 → 钉钉授权。用 DWS 设备授权,以来源账号选择组织、空间和范围。API 与 worker 使用部署约定的 DWS 身份目录 | 登录后读回预期空间,选一个有权限的目录校验。登记来源、扫描完成和文件取件分别核验。 |
|
||||
| 钉钉知识库,取目录和文件 | 系统设置 → 数据源配置 → 钉钉授权。用 DWS 设备授权,以来源账号选择组织、空间和范围。API 与 worker 使用部署约定的 DWS 身份目录 | 登录后读回预期空间,选一个有权限的目录校验。登记来源、扫描完成和文件取件分别核验。[授权手册](DWS_LOGIN.md) |
|
||||
| AList,取工业或教育资料 | 按来源登记服务根地址和允许的目录。普通 worker 读取专用令牌文件。目录接口 `POST /api/fs/list` 使用 `X-Gateway-Token` | 在来源页扫描已知根目录,对照一个子目录和一份文件。下载遵循来源签名链接,凭据和签名 URL 仅留在受控运行环境。[目录与取件](SOURCE_CATALOG_LIVE_ROUTING_ACCEPTANCE.md) |
|
||||
| PP 资料门户 | 在数据源配置填写 HTTPS 根地址和来源账号,点「测试连接」后「保存并校验」。API 和 worker 共享 `PP_AUTH_STATE_FILE` 所在目录 | 真实登录并读取一条目录记录,刷新后核对生效配置。超时或限流时查看待验证状态。 |
|
||||
| PP 资料门户 | 在数据源配置填写 HTTPS 根地址和来源账号,点「测试连接」后「保存并校验」。API 和 worker 共享 `PP_AUTH_STATE_FILE` 所在目录 | 真实登录并读取一条目录记录,刷新后核对生效配置。超时或限流时查看待验证状态。[认证、保存与扫描契约](SOURCE_AUTH_CONFIGURATION.md) |
|
||||
| WeKnora 测试 090,处理与验收 | 系统设置 → 知识库绑定 → 测试 090。当前测试 API 地址 `http://127.0.0.1:8092`,由治理服务器访问。输入该实例的专用 Key 或使用已配置凭据 | 「验证并读取知识库」能列出预期库。核对名称和 ID,为对内、对外选择不同的目标,保存后刷新读回 |
|
||||
| WeKnora 生产 090,列库与映射 | 在同页切到生产 090,使用下节的转发入口与生产专用 Key。新连接的安全存储由 `WEKNORA_BINDING_MASTER_KEY_FILE` 提供 | 读取生产目录并核对两个目标 ID,保存后重新进入生产页核实。执行发布另按 §5–6 授权 |
|
||||
| 问答 AI 模型 | 系统设置 → AI 模型连接,填写 OpenAI 兼容基础地址(含服务要求的 `/v1`)、模型名及专用 Key。API 与普通 worker 使用同一 `QA_AI_MASTER_KEY_FILE` | 点「测试连接」等待成功,需生效时再保存并刷新检查模型名。存储密钥、权限与 DNS 配置见 [README](../README.md#问答运营模型配置) |
|
||||
|
||||
**生产 090 的两段地址。** 生产机私网 IP 为 `172.29.151.11`,其 WeKnora API 对宿主回环发布 `127.0.0.1:18092`。测试治理机上已有 SSH 本地转发,治理 API 使用 host 网络,故页面的生产服务地址填写 **`http://127.0.0.1:18092`**。请求从治理 API 发出,经测试机的回环监听到生产机的回环 API。浏览器所在电脑的 `127.0.0.1:28189` 则用于打开治理页面。迁到 bridge 网络时要从新 API 容器重新验证上游可达性。
|
||||
|
||||
**直连反代(18093)与隧道(18092)二选一。** 若生产机已按前置要求提供
|
||||
`172.29.151.11:18093`(只放行测试机),页面就填 `http://172.29.151.11:18093`,并在
|
||||
部署侧设置 `WEKNORA_ALLOW_PRIVATE_HTTP=true` —— 它只放行 RFC1918/回环/链路本地
|
||||
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
|
||||
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
|
||||
|
||||
**页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。
|
||||
|
||||
**保存留审计。** 每次保存成功,`weknora_environment_binding_history` 在同一事务写入
|
||||
操作人、时间、环境、客户端地址(`source_address`)与控制台来源(`source_origin`)。来源字段
|
||||
只用于事后取证,不参与放行;地址解析不出来就留空,不用推测值填充。
|
||||
|
||||
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
|
||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
|
||||
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
|
||||
「同 ID 语义」,提示里会写明。
|
||||
|
||||
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
|
||||
|
||||
```bash
|
||||
@@ -77,7 +95,7 @@ curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'catalog %{http_code}\n' htt
|
||||
1. 在开发机运行 `make list` 查看门禁,`make verify` 做整套检查。以 `ci-report.json` 的 `commit_sha` 对照 `git rev-parse HEAD`,记录失败或跳过项。前端启动和组件测试见 [开发与 CI](../README.md#开发与-ci)。
|
||||
2. 针对后端改动,在独立测试逻辑库核对 `SELECT current_database(), max(version) FROM schema_migrations;` 与候选版本的迁移目录。云端多个候选可能共用治理 RDS。只改静态页面时单独切换 Web,保留原资源和代理配置供回滚。
|
||||
3. 在指定入口以真实账号分别验证。来源页读取一条已知记录,模型页测试到成功终态,知识库绑定在正确环境列库,保存后刷新核对。存储页按最近批次和子库目录分别与 `du -sB1 -- <目录>` 对账。记录入口、Web/API 提交、时间和结果。
|
||||
4. 候选备份页读取宿主采集的 `metadata.json`,API 只读挂载输出目录。「重新盘点」只重读文件。超过 `BACKUP_HOST_METADATA_MAX_AGE` 时,目录、占盘和预测转为未知。宿主重新采集后核对采集时间是否前进、批次是否恢复。测试现场使用按次采集、15 分钟有效期。采集脚本和挂载参数以同批测试候选交付物为准。
|
||||
4. 候选备份页读取宿主采集的 `metadata.json`,API 只读挂载输出目录。「重新盘点」只重读文件。超过 `BACKUP_HOST_METADATA_MAX_AGE` 时,目录、占盘和预测转为未知。宿主重新采集后核对采集时间是否前进、批次是否恢复。测试现场使用按次采集、15 分钟有效期。采集命令和挂载契约见 [备份只读接口](STORAGE_BACKUP_READONLY_API.md)。
|
||||
|
||||
| 症状 | 第一步怎么查 | 如何判定 |
|
||||
|---|---|---|
|
||||
@@ -91,7 +109,7 @@ curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'catalog %{http_code}\n' htt
|
||||
## 0. 开工前:环境与凭据自检
|
||||
| 项 | 怎么做 | 成功标志 |
|
||||
|---|---|---|
|
||||
| 测试/生产 WeKnora | 系统设置 → 知识库映射 → WeKnora 连接 | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 测试/生产 WeKnora | 系统设置 → 知识库绑定(选择测试 090 / 生产 090) | 生产端"已启用 · 可提交生产请求";测试端探测正常 |
|
||||
| 钉钉取件凭据 **【新】** | 容器内 `HOME=/data/home dws auth status --readonly -f json` | `authenticated:true`、`refresh_token_valid:true`(**必须带 `HOME=/data/home`,否则误报未登录**) |
|
||||
| 备份主机接线 | 系统设置 → 存储与备份 | "目标主机 weknora-test · 已连接" |
|
||||
|
||||
@@ -161,11 +179,10 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
|
||||
|
||||
| 分区 | 谁 | 现在要管什么 |
|
||||
|---|---|---|
|
||||
| 知识库映射 → WeKnora 连接 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) |
|
||||
| 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) |
|
||||
| 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) |
|
||||
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
|
||||
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
|
||||
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
|
||||
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
|
||||
| 参数设置 | 文档工程师 | 「来源与目录」文档/资源刷新间隔;「解析监控」停滞阈值、入库并发上限(1..16,版本化 + 原子切换);finalizing 设置仅在 API/DB 保留,页面不展示 |
|
||||
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
|
||||
|
||||
## 9. 备份与恢复运维 **【新】**
|
||||
|
||||
@@ -91,13 +91,36 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
||||
|
||||
- 页面:系统设置 → 存储与备份(管理员可改;保存 = 写入库并立刻下发;另有"重新下发当前设置"与"立即备份一次")。
|
||||
- 接口:`GET /api/v1/backup-schedule`(不探测主机,首屏快)、`GET …/host`(SSH 读回主机 cron 与最近一次结果)、
|
||||
`GET …/inventory`(宿主采集器快照读全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
|
||||
`PUT`(校验时间 `HH:MM` 与 1~365 天 / 0~24 月,非法值直接 400 且不落库不下发)、`POST …/apply`、`POST …/run`。
|
||||
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
||||
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
|
||||
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
|
||||
- **配额(按字节,硬上限)**:`/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),
|
||||
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
||||
`scripts/collect_backup_metadata.py` 原子写 `metadata.json`,API 用
|
||||
`BACKUP_HOST_METADATA_PATH / BACKUP_HOST_READONLY_HOST_PATH` 只读快照,见
|
||||
`docs/STORAGE_BACKUP_READONLY_API.md`。
|
||||
- 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`,
|
||||
所以"最近一次备份"永远不会显示一份半成品。
|
||||
- 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
```
|
||||
|
||||
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
|
||||
5. 在首次发布前,由运维把四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
|
||||
5. HiFox 触发器在派发 Gitea 前自动通过执行机的 `weknora-test` SSH 通道交接四个文件,并用主站控制器校验。人工 Actions 入口仍须由运维提前将四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
|
||||
|
||||
## 在 HiFox 确认发布
|
||||
|
||||
@@ -49,5 +49,5 @@
|
||||
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
|
||||
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
|
||||
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
|
||||
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py,cd_bundle_handoff.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
# 存储与备份:宿主元数据采集器、只读接口与 28189 接线
|
||||
|
||||
「备份记录 / 整盘占用」不遍历备份目录。备份目录通常是 `root:root 0700`,API 容器
|
||||
用户 `uid 1000` 进不去;容器里遍历只会得到 permission denied 的部分字节。真实闭环是:
|
||||
|
||||
1. 备份主机上由**有读权限的宿主进程**运行 `scripts/collect_backup_metadata.py` 单次采集;
|
||||
只做 `stat`/`du` 元数据和读 `MANIFEST.json`,不读数据库内容文件。
|
||||
2. 采集器用同目录临时文件 + `fsync` + `os.replace` **原子写出** `metadata.json`。
|
||||
3. API 只读挂载这个 JSON,校验 schema、批次/子库路径、主机根、时效、完整性。
|
||||
4. 快照陈旧/缺失/不完整时,批次字节为 `null`,页面显示未知,不画容量图、不做可写预测。
|
||||
|
||||
主机 cron 计划读回仍是原来的 SSH 通道(`/host`),与快照完全独立;API 不借用 SSH
|
||||
读文件,也不获得备份目录的容器权限。
|
||||
|
||||
## 1. 采集器(宿主运行)
|
||||
|
||||
脚本:`scripts/collect_backup_metadata.py`(Python 3 标准库,无第三方依赖)
|
||||
|
||||
```sh
|
||||
python3 collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--usage-root /srv/kb-backups \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical
|
||||
```
|
||||
|
||||
- 备份根与配额来自 `/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`;
|
||||
**不打开任何 `.dat/.gz` 数据文件**。
|
||||
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
||||
- 口径与 `du -sB1` 对齐:目录自身块计入;遍历整棵子树而非只求和文件;
|
||||
常规文件硬链接按 `(st_dev, st_ino)` 只算一次;**每个子库与整批各自独立测量**,
|
||||
所以单库字节与该子库自己的 `du` 一致、整批与整批 `du` 一致(不会把整批去重结果
|
||||
摊回单库)。
|
||||
- `MANIFEST.json` 只接受批次目录内的常规非符号链接文件;`lstat` + `O_NOFOLLOW`
|
||||
打开,符号链接/非普通文件一律 `invalid`,不会被跟随到别处。
|
||||
- 权限失败会写入 `batch.errors` 并把 `actual_bytes/apparent_bytes/file_count` 置 `null`;
|
||||
绝不把已数到的部分字节当占盘。
|
||||
|
||||
建议由宿主定时器每 5 分钟跑一次(root 或备份目录所有者;不改任何备份权限):
|
||||
|
||||
```cron
|
||||
*/5 * * * * /usr/bin/python3 /opt/knowledge-governance/collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical \
|
||||
>> /var/log/knowledge-governance-backup-metadata.log 2>&1
|
||||
```
|
||||
|
||||
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
||||
采集器自己读 `/etc/knowledge-governance/backup.env` 拿 `KB_BACKUP_ROOT`/`KB_BACKUP_QUOTA_BYTES`,
|
||||
所以配额调整不需要改 cron;只想临时覆盖时再加 `--usage-root`/`--quota-bytes`。
|
||||
|
||||
### 快照 schema(version 1)
|
||||
|
||||
关键字段:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `schema_version` | `1`;API 不认识就整块拒绝 |
|
||||
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
||||
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
||||
| `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 |
|
||||
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
||||
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
||||
| `batches[].actual_bytes` | `st_blocks×512` 实际分配,仅完整批有值 |
|
||||
| `batches[].databases[].path` | 子库完整宿主路径,必须等于 `<batch>/<name>.dir` |
|
||||
| `batches[].manifest_state` | `ok` / `missing` / `invalid`(清单是元数据,不影响权限统计) |
|
||||
|
||||
## 2. 接口契约
|
||||
|
||||
`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西)
|
||||
|
||||
始终 200 + `data`;未接线/快照缺失/陈旧/不完整/路径不一致都写在字段里。
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"wired": true,
|
||||
"metadata": {
|
||||
"configured": true, "present": true, "valid": true,
|
||||
"fresh": true, "complete": true,
|
||||
"path": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"collected_at": "2026-11-20T01:00:00Z",
|
||||
"age_seconds": 10, "max_age_seconds": 900,
|
||||
"schema_version": 1, "generation": "20261120T010000Z-abc123",
|
||||
"host": "weknora-test", "collector_version": "backup-metadata/1",
|
||||
"error": ""
|
||||
},
|
||||
"root": "/srv/kb-backups/rds-logical",
|
||||
"host_root": "/srv/kb-backups/rds-logical",
|
||||
"backup_root": "/srv/kb-backups",
|
||||
"source": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"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_verified": true, "read_only": false,
|
||||
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
||||
"evidence": "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录"
|
||||
},
|
||||
"capacity": {
|
||||
"measured": true, "total_bytes": 1000, "free_bytes": 400,
|
||||
"available_bytes": 350, "used_bytes": 600
|
||||
},
|
||||
"batches": [{
|
||||
"stamp": "20261118T193001Z",
|
||||
"path": "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
"host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
"manifest_state": "ok",
|
||||
"actual_bytes": 4096, "apparent_bytes": 300, "file_count": 3,
|
||||
"sizes_complete": true,
|
||||
"databases": [{
|
||||
"name": "weknora_v090prod",
|
||||
"path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
"host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
"present": true, "failed": false, "in_manifest": true,
|
||||
"actual_bytes": 4096, "apparent_bytes": 250, "file_count": 2
|
||||
}]
|
||||
}],
|
||||
"totals": {
|
||||
"batch_count": 8, "database_count": 0,
|
||||
"actual_bytes": 12000000000, "apparent_bytes": 11141651752,
|
||||
"latest_stamp": "20261118T193001Z", "latest_actual_bytes": 1500000000,
|
||||
"complete": true
|
||||
},
|
||||
"incomplete_count": 0, "skipped": [], "truncated": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 示例中的容量/字节只说明字段形状,**不是现场读数**;候选现场已核实的事实只有:
|
||||
> 8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。单库 `696320` 是现场核对值,
|
||||
> 代码与测试都不写死。
|
||||
|
||||
### 语义与页面行为
|
||||
|
||||
| 条件 | API | 页面 |
|
||||
| --- | --- | --- |
|
||||
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
||||
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
||||
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
|
||||
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有批次 `*_bytes=null` | 列出路径与清单状态;批次/容量“未知”,不画色带;根占用若自身完整仍可显示 |
|
||||
| 根占用遍历失败 | `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`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
||||
|
||||
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
||||
`<batch>/<name>.dir`;重复、分隔符、`..`、`.incomplete` 一律拒绝。
|
||||
|
||||
## 3. 28189 候选 API 的最小接线
|
||||
|
||||
API 只挂**采集器输出目录**,不挂备份目录:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
|
||||
BACKUP_HOST_METADATA_MAX_AGE: 15m
|
||||
BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
|
||||
BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
|
||||
volumes:
|
||||
- /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
|
||||
```
|
||||
|
||||
- `BACKUP_HOST_METADATA_PATH` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
|
||||
(用 target + host path 拼)。缺任一拒绝启动,避免“看起来接线”或复制猜的路径。
|
||||
- 只挂元数据目录,`uid 1000` 只需要读 `metadata.json`,**不需要**进入 root:root 0700 的备份目录。
|
||||
- 采集器由宿主 root/备份所有者运行;不新增 API SSH 权限,不改备份目录权限。
|
||||
- 主机 cron 计划仍走 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;与快照独立。
|
||||
|
||||
### 部署后核验
|
||||
|
||||
宿主:
|
||||
|
||||
```sh
|
||||
ls -l /var/lib/knowledge-governance/backup-metadata/metadata.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
d=json.load(open('/var/lib/knowledge-governance/backup-metadata/metadata.json'))
|
||||
print(d['schema_version'], d['collected_at'], d['complete'], d['root'], len(d['batches']))
|
||||
print(d['batches'][0]['stamp'], [x['name'] for x in d['batches'][0]['databases']][:5])
|
||||
PY
|
||||
```
|
||||
|
||||
API 容器:
|
||||
|
||||
```sh
|
||||
cat /var/lib/knowledge-governance/backup-host/metadata.json >/dev/null && echo readable
|
||||
curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
||||
```
|
||||
|
||||
字段核对(以现场为准,示例值不写死):
|
||||
|
||||
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看批次字节与容量。
|
||||
- `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`。
|
||||
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
||||
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
|
||||
- `capacity.measured=true` 且与宿主 `df -B1 /srv/kb-backups` 一致。
|
||||
- 若 `complete=false`:先看 `metadata.error` 里的 permission/遍历错误;**不要**用
|
||||
`latest_actual_bytes` 或部分 `databases[].actual_bytes` 做容量判断(它们应为 null)。
|
||||
|
||||
## 4. 与主机计划读回的关系
|
||||
|
||||
- `/host`:SSH 读 cron/脚本/计划 + MANIFEST 最近一次摘要。
|
||||
- `/inventory`:宿主快照读全部批次、子库路径、实际占盘、容量。
|
||||
|
||||
前端分别加载:快照不可用时计划区仍可显示;SSH 连不上时历史区仍可用快照。历史与子库
|
||||
路径以快照为准,SSH 的“最近一次”只作历史参考。
|
||||
|
||||
## 5. 现有写路径(本次未改)
|
||||
|
||||
| 路径 | 写什么 | 权限 |
|
||||
| --- | --- | --- |
|
||||
| `PUT /api/v1/backup-schedule` | 计划写库;`apply=true` 时 SSH 下发 cron | 管理员 |
|
||||
| `POST /api/v1/backup-schedule/apply` | SSH 重写主机 cron/计划参数 | 管理员 |
|
||||
| `POST /api/v1/backup-schedule/run` | 在主机执行 `logical-backup.sh`(写备份目录/RDS dump) | 管理员 |
|
||||
| `BackupScheduleStore.SaveBackupSchedule` | 计划落库 | 服务内部 |
|
||||
| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 |
|
||||
| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 |
|
||||
|
||||
本接口与采集器没有写备份目录、删批次、改 cron 的代码路径。
|
||||
|
||||
## 6. 还需单独确认的后端写能力
|
||||
|
||||
1. 配额 / 磁盘预留的持久化:配额已按部署配置(`backup.env`)执行并上报;**平台页面编辑/下发**仍未实现(需 DB 字段与写接口)。
|
||||
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
||||
3. 备份目录迁移/切换。
|
||||
4. 单库备份/单库恢复(现有 run 是整批)。
|
||||
5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。
|
||||
6. MANIFEST 修复/重建。
|
||||
7. 采集器安装/权限变更自动化(属部署与主机权限,必须人工批准)。
|
||||
8. 写操作角色细分(目前统一管理员)。
|
||||
@@ -255,20 +255,25 @@
|
||||
|
||||
## D. 系统设置
|
||||
|
||||
### D1 知识库映射 → WeKnora 连接(测试 / 生产端点与 ID)
|
||||
- 入口:**系统设置 → 知识库映射 → WeKnora 连接**(管理员)
|
||||
- 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读
|
||||
- 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试)
|
||||
### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库)
|
||||
- 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读)
|
||||
- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库;**两个方向都必须选择**)→ **保存该环境绑定**
|
||||
- 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库
|
||||
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
|
||||
- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
|
||||
- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
|
||||
- 单次任务连接:`TestBeginTaskPinsOneResolvedConnectionForAllCalls`;`TestPollUsesOneVerifiedConnectionForAllCalls`、`TestValidateUsesOneVerifiedConnectionForAllCalls`、`TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack`、`TestUploadUsesOneVerifiedConnectionForWrite`、`TestUploadRecoveryUsesTheSameVerifiedConnection`
|
||||
- 状态:✅ 本地验证(未做业务验收)
|
||||
|
||||
### D2 测试知识库绑定(对内 / 对外)
|
||||
- 入口:**系统设置 → 测试知识库绑定** → 选库 → 保存绑定
|
||||
- 期望:保存立即生效并重排"还没上传"的待入库项;对内 ≠ 对外
|
||||
- 状态:✅ 本期实测
|
||||
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
|
||||
- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断**
|
||||
- 期望:保留入库目标/封存源一致性对照与重新读取;不再提供第二个保存入口(保存统一走 D1)
|
||||
- 状态:✅ 诊断展示保留
|
||||
|
||||
### D3 生产知识库绑定(源库 → 目标库)
|
||||
- 入口:**系统设置 → 生产知识库绑定** → 对内/对外各选一个生产库
|
||||
- 期望:发布写入被冻结到该项的 `target_knowledge_base_id`;未绑定时按同 ID 语义并在契约检查处失败关闭
|
||||
- 状态:✅(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044)
|
||||
### D3 生产知识库绑定(折叠诊断;整库目标只读)
|
||||
- 入口:**系统设置 → 知识库绑定 → 连接与绑定诊断**
|
||||
- 期望:整库发布实际目标来自部署配置、只读;生产 090 工作区的 D1 保存只写文档级语义(源库 → 目标库),不触发整库发布或生产写入
|
||||
- 状态:✅ 诊断展示保留(`P8_PRODUCTION_KB_MAPPING_ACCEPTANCE.md`;迁移 000044)
|
||||
|
||||
### D4 存储与备份(整库逻辑备份的定时)★本期新增
|
||||
- 入口:**系统设置 → 存储与备份**(管理员)
|
||||
@@ -279,10 +284,14 @@
|
||||
- 立即备份:按钮变"备份进行中…"→ 约 50 秒后自动刷出新结果(异步 202 + 在途单飞,重复点击不会跑两次)
|
||||
- 状态:✅ 2026-10-09 面板实测(写操作仅管理员:`PUT/POST /api/v1/backup-schedule*`)
|
||||
|
||||
### D5 刷新策略
|
||||
- 入口:**系统设置 → 刷新策略**(文档工程师可改)
|
||||
- 期望:文档/资源刷新间隔、停滞判定、finalizing 时长;保存先验证再原子启用、旧版本留审计
|
||||
- 状态:✅(`ui_settings` 版本化激活测试)
|
||||
### D5 参数设置
|
||||
- 入口:**系统设置 → 参数设置**(文档工程师可改)
|
||||
- 期望:按「来源与目录」「解析监控」两组呈现。来源与目录:文档状态刷新间隔(15/30/60 秒)、
|
||||
资源刷新间隔(30/60 秒);解析监控:解析停滞阈值(30/60 分钟)、入库并发上限(1..16)。
|
||||
四项以数值输入呈现,单位与调大/调小后果常驻,越界就地提示并禁用保存;保存先验证再原子
|
||||
启用、旧版本留审计。收尾超时告警不再在页面任何位置出现;API/DB 的
|
||||
`finalizing_after_seconds` 与 `finalizing` 处理状态不变。
|
||||
- 状态:✅(`ui_settings` 版本化激活测试;本任务补数值校验与浏览器实测)
|
||||
|
||||
### D6 成员与角色
|
||||
- 入口:**系统设置 → 成员与角色**(管理员)
|
||||
|
||||
@@ -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 |
|
||||
| 2 main 单线、串行修改 | §2 |
|
||||
| 2 分支 + PR、串行修改 | §2 |
|
||||
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
|
||||
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
|
||||
| 5 不可变与回退规则 | §5 |
|
||||
@@ -30,11 +30,12 @@
|
||||
角色约束是**流程约束**,不是技术 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` 要求修复外不再改动。
|
||||
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
|
||||
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
|
||||
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
|
||||
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` 收尾。
|
||||
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
|
||||
|
||||
|
||||
@@ -28,6 +28,21 @@
|
||||
|
||||
既有目标历史软删除行按原 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. 资源引用的实际格式
|
||||
|
||||
只读参考源码:`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_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
|
||||
| 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) |
|
||||
| resources | **不映射** | resource_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 不改写;本地自增列
|
||||
(如 `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` 计算;
|
||||
|
||||
@@ -47,16 +47,22 @@ type Config struct {
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
TestWeKnoraAPIKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// WeKnoraAllowPrivateHTTP 放行同网段 http(生产 18093 反代);只接受
|
||||
// RFC1918/回环/链路本地,公网 http 仍拒绝。监控探活与列库共用同一判定。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
|
||||
TestAutoReviewPolicy string
|
||||
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
|
||||
@@ -65,6 +71,12 @@ type Config struct {
|
||||
BackupHostTarget string
|
||||
BackupHostScriptDir string
|
||||
BackupHostRoot string
|
||||
// BackupHostMetadataPath 是容器内挂载的宿主 metadata.json(单次采集器的原子快照)。
|
||||
// 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
|
||||
BackupHostMetadataPath string
|
||||
BackupHostMetadataMaxAge time.Duration
|
||||
BackupHostReadonlyHostPath string
|
||||
BackupHostReadonlySource string
|
||||
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
|
||||
// (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库,
|
||||
// 不接受任何调用方传入的 URL;本功能**不使用凭据**。
|
||||
@@ -181,6 +193,10 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer")
|
||||
}
|
||||
embeddingDimension := int(embeddingDimension64)
|
||||
metadataMaxAge, err := durationOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_METADATA_MAX_AGE")), 15*time.Minute)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
|
||||
}
|
||||
config := Config{
|
||||
DatabaseURL: getenv("DATABASE_URL"),
|
||||
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
|
||||
@@ -203,6 +219,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
|
||||
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
|
||||
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
|
||||
@@ -219,6 +236,10 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
|
||||
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
|
||||
BackupHostMetadataPath: strings.TrimSpace(getenv("BACKUP_HOST_METADATA_PATH")),
|
||||
BackupHostMetadataMaxAge: metadataMaxAge,
|
||||
BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
|
||||
BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
@@ -344,6 +365,15 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("PRODUCTION_WEKNORA_API_KEY_FILE must be an absolute path")
|
||||
}
|
||||
}
|
||||
if raw := getenv("WEKNORA_ALLOW_PRIVATE_HTTP"); raw != "" {
|
||||
config.WeKnoraAllowPrivateHTTP, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("WEKNORA_ALLOW_PRIVATE_HTTP: %w", err)
|
||||
}
|
||||
}
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
|
||||
config.PPScanEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
@@ -511,6 +541,28 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
|
||||
}
|
||||
config.TestAutoReviewPolicy = string(normalizedPolicy)
|
||||
// 宿主采集器快照接线与生产发布开关无关:测试栈也要先读通历史批次。
|
||||
if config.BackupHostMetadataPath != "" && !filepath.IsAbs(config.BackupHostMetadataPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
|
||||
}
|
||||
if config.BackupHostMetadataPath != "" && config.BackupHostReadonlyHostPath == "" {
|
||||
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when metadata path is set")
|
||||
}
|
||||
if config.BackupHostMetadataPath == "" &&
|
||||
(config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_PATH is required when host path/source is set")
|
||||
}
|
||||
if config.BackupHostMetadataMaxAge <= 0 || config.BackupHostMetadataMaxAge > 24*time.Hour {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be between 1s and 24h")
|
||||
}
|
||||
for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
return Config{}, errors.New("backup inventory display path/source contains control characters")
|
||||
}
|
||||
}
|
||||
if config.ProductionReleaseRequestsEnabled {
|
||||
// 目标主机凭据要么都给要么都不给:只给一半会把"未接线"伪装成"已接线"。
|
||||
if (config.BackupHostSSHConfig == "") != (config.BackupHostTarget == "") {
|
||||
|
||||
@@ -53,6 +53,49 @@ func TestLoadUsesSafeDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadValidatesBackupInventoryMount(t *testing.T) {
|
||||
base := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
load := func(extra map[string]string) (Config, error) {
|
||||
values := map[string]string{}
|
||||
for key, value := range base {
|
||||
values[key] = value
|
||||
}
|
||||
for key, value := range extra {
|
||||
values[key] = value
|
||||
}
|
||||
return Load(func(key string) string { return values[key] })
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "relative/path"}); err == nil {
|
||||
t.Fatal("relative metadata path must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json"}); err == nil {
|
||||
t.Fatal("metadata path without host root must be rejected (paths must not be guessed)")
|
||||
}
|
||||
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
|
||||
t.Fatal("host path without metadata path must be rejected")
|
||||
}
|
||||
if _, err := load(map[string]string{
|
||||
"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_METADATA_MAX_AGE": "nope",
|
||||
}); err == nil {
|
||||
t.Fatal("invalid metadata max age must be rejected")
|
||||
}
|
||||
config, err := load(map[string]string{
|
||||
"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
|
||||
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"BACKUP_HOST_METADATA_MAX_AGE": "5m",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("valid inventory snapshot config rejected: %v", err)
|
||||
}
|
||||
if config.BackupHostMetadataPath == "" || config.BackupHostReadonlyHostPath == "" ||
|
||||
config.BackupHostReadonlySource == "" || config.BackupHostMetadataMaxAge != 5*time.Minute {
|
||||
t.Fatalf("inventory snapshot fields lost: %#v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseURL(t *testing.T) {
|
||||
if _, err := Load(func(string) string { return "" }); err == nil {
|
||||
t.Fatal("Load() error = nil, want missing DATABASE_URL error")
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
// Package backupinventory 读取**宿主采集器**产出的备份元数据快照。
|
||||
//
|
||||
// 为什么不在 API 里遍历备份目录:备份目录通常是 root:root 0700,API 容器用户
|
||||
// 没有进入权限;容器里遍历只能得到 permission denied 的部分字节,绝不能把部分
|
||||
// 计数当成实际占盘。这里只读宿主进程原子写出的 metadata.json,并校验 schema、
|
||||
// 批次路径、主机根、时效与完整性。API 不接触备份目录,也不借用 SSH/容器特权。
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SchemaVersion = 1
|
||||
defaultMaxAge = 15 * time.Minute
|
||||
defaultMaxBytes = 16 << 20
|
||||
futureTolerance = 2 * time.Minute
|
||||
measurementLabel = "host_collector"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
// MetadataPath 是 API 容器内挂载的 metadata.json(宿主采集器原子写出)。
|
||||
MetadataPath string
|
||||
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
||||
HostRoot string
|
||||
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
|
||||
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
|
||||
BackupRoot string
|
||||
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
||||
Source string
|
||||
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
||||
MaxAge time.Duration
|
||||
// MaxBytes 防止异常大文件拖死 API。
|
||||
MaxBytes int64
|
||||
}
|
||||
|
||||
type ManifestState string
|
||||
|
||||
const (
|
||||
ManifestOK ManifestState = "ok"
|
||||
ManifestMissing ManifestState = "missing"
|
||||
ManifestInvalid ManifestState = "invalid"
|
||||
)
|
||||
|
||||
type MetadataInfo struct {
|
||||
Configured bool `json:"configured"`
|
||||
Present bool `json:"present"`
|
||||
Valid bool `json:"valid"`
|
||||
Fresh bool `json:"fresh"`
|
||||
Complete bool `json:"complete"`
|
||||
Path string `json:"path"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
AgeSeconds int64 `json:"age_seconds"`
|
||||
MaxAgeSeconds int64 `json:"max_age_seconds"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Generation string `json:"generation"`
|
||||
Host string `json:"host"`
|
||||
CollectorVersion string `json:"collector_version"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type MountInfo struct {
|
||||
ContainerRoot string `json:"container_root"`
|
||||
MountVerified bool `json:"mount_verified"`
|
||||
LivesOnContainerRoot bool `json:"lives_on_container_root"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Evidence string `json:"evidence"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Device string `json:"device"`
|
||||
FSType string `json:"fs_type"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Capacity struct {
|
||||
Measured bool `json:"measured"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
UsedBytes int64 `json:"used_bytes"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// 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 {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
}
|
||||
|
||||
type Batch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
HostPath string `json:"host_path"`
|
||||
ManifestState ManifestState `json:"manifest_state"`
|
||||
ManifestPath string `json:"manifest_path"`
|
||||
ManifestError string `json:"manifest_error,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
SizesComplete bool `json:"sizes_complete"`
|
||||
SizesError string `json:"sizes_error,omitempty"`
|
||||
Databases []Database `json:"databases"`
|
||||
}
|
||||
|
||||
type Skipped struct {
|
||||
Name string `json:"name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type Totals struct {
|
||||
BatchCount int `json:"batch_count"`
|
||||
DatabaseCount int `json:"database_count"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
LatestStamp string `json:"latest_stamp"`
|
||||
LatestActualBytes *int64 `json:"latest_actual_bytes"`
|
||||
Complete bool `json:"complete"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Wired bool `json:"wired"`
|
||||
Metadata MetadataInfo `json:"metadata"`
|
||||
Root string `json:"root"`
|
||||
HostRoot string `json:"host_root"`
|
||||
BackupRoot string `json:"backup_root"`
|
||||
Source string `json:"source"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Measurement string `json:"measurement"`
|
||||
Mount MountInfo `json:"mount"`
|
||||
Capacity Capacity `json:"capacity"`
|
||||
Usage Usage `json:"usage"`
|
||||
QuotaBytes *int64 `json:"quota_bytes"`
|
||||
QuotaError string `json:"quota_error,omitempty"`
|
||||
Batches []Batch `json:"batches"`
|
||||
Totals Totals `json:"totals"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
type Reader struct {
|
||||
config Config
|
||||
now func() time.Time
|
||||
read func(string) ([]byte, error)
|
||||
}
|
||||
|
||||
func New(config Config) *Reader {
|
||||
if config.MaxAge <= 0 {
|
||||
config.MaxAge = defaultMaxAge
|
||||
}
|
||||
if config.MaxBytes <= 0 {
|
||||
config.MaxBytes = defaultMaxBytes
|
||||
}
|
||||
return &Reader{config: config, now: time.Now, read: os.ReadFile}
|
||||
}
|
||||
|
||||
func (r *Reader) Available() bool {
|
||||
return r != nil && strings.TrimSpace(r.config.MetadataPath) != ""
|
||||
}
|
||||
|
||||
// ---- 宿主快照文件(collector 的输出;只读、字段可验证) ----
|
||||
|
||||
type metadata struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
CollectorVersion string `json:"collector_version"`
|
||||
Generation string `json:"generation"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
Host string `json:"host"`
|
||||
Source string `json:"source"`
|
||||
Root string `json:"root"`
|
||||
BackupRoot string `json:"backup_root"`
|
||||
Usage metadataUsage `json:"usage"`
|
||||
QuotaBytes *int64 `json:"quota_bytes"`
|
||||
QuotaError string `json:"quota_error"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
Filesystem metadataFilesystem `json:"filesystem"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
Skipped []Skipped `json:"skipped"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Batches []metadataBatch `json:"batches"`
|
||||
}
|
||||
|
||||
type 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 {
|
||||
MountPoint string `json:"mount_point"`
|
||||
MountSource string `json:"mount_source"`
|
||||
FSType string `json:"fs_type"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
FreeBytes int64 `json:"free_bytes"`
|
||||
AvailableBytes int64 `json:"available_bytes"`
|
||||
}
|
||||
|
||||
type metadataBatch struct {
|
||||
Stamp string `json:"stamp"`
|
||||
Path string `json:"path"`
|
||||
ManifestState string `json:"manifest_state"`
|
||||
ManifestError string `json:"manifest_error"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
StartedAt string `json:"started_at"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
Databases []metadataDatabase `json:"databases"`
|
||||
}
|
||||
|
||||
type metadataDatabase struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
Path string `json:"path"`
|
||||
Present bool `json:"present"`
|
||||
Failed bool `json:"failed"`
|
||||
InManifest bool `json:"in_manifest"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
}
|
||||
|
||||
// Snapshot 只返回可验证的事实:陈旧/缺失/不完整一律不给批次字节与容量。
|
||||
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
|
||||
snapshot := Snapshot{
|
||||
Wired: r.Available(),
|
||||
Measurement: measurementLabel,
|
||||
Batches: []Batch{},
|
||||
Skipped: []Skipped{},
|
||||
ObservedAt: r.observedAt(),
|
||||
Metadata: MetadataInfo{
|
||||
Configured: r.Available(),
|
||||
MaxAgeSeconds: int64(r.config.MaxAge / time.Second),
|
||||
},
|
||||
}
|
||||
if r == nil || !r.Available() {
|
||||
snapshot.Metadata.Error = "元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)"
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Metadata.Path = r.config.MetadataPath
|
||||
snapshot.HostRoot = r.config.HostRoot
|
||||
snapshot.Source = r.config.Source
|
||||
if ctx.Err() != nil {
|
||||
snapshot.Metadata.Error = "读取被取消:" + ctx.Err().Error()
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
raw, err := r.read(r.config.MetadataPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
snapshot.Metadata.Error = "宿主元数据快照不存在:需要先运行 collect_backup_metadata.py"
|
||||
} else {
|
||||
snapshot.Metadata.Error = "宿主元数据快照不可读:" + err.Error()
|
||||
}
|
||||
snapshot.Error = snapshot.Metadata.Error
|
||||
return snapshot
|
||||
}
|
||||
snapshot.Metadata.Present = true
|
||||
if int64(len(raw)) > r.config.MaxBytes {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据快照超过 %d 字节读取上限", r.config.MaxBytes))
|
||||
}
|
||||
var file metadata
|
||||
if err := json.Unmarshal(raw, &file); err != nil {
|
||||
return invalid(snapshot, "元数据快照无法解析:"+err.Error())
|
||||
}
|
||||
snapshot.Metadata.SchemaVersion = file.SchemaVersion
|
||||
snapshot.Metadata.Generation = file.Generation
|
||||
snapshot.Metadata.Host = file.Host
|
||||
snapshot.Metadata.CollectorVersion = file.CollectorVersion
|
||||
snapshot.Metadata.CollectedAt = file.CollectedAt
|
||||
snapshot.Metadata.Complete = file.Complete
|
||||
if file.Source != "" {
|
||||
snapshot.Source = file.Source
|
||||
}
|
||||
if file.SchemaVersion != SchemaVersion {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 schema_version=%d,API 只支持 %d", file.SchemaVersion, SchemaVersion))
|
||||
}
|
||||
collectedAt, err := time.Parse(time.RFC3339, file.CollectedAt)
|
||||
if err != nil {
|
||||
return invalid(snapshot, "元数据 collected_at 非法:"+file.CollectedAt)
|
||||
}
|
||||
age := r.now().UTC().Sub(collectedAt.UTC())
|
||||
if age < -futureTolerance {
|
||||
return invalid(snapshot, "元数据 collected_at 在未来,拒绝使用")
|
||||
}
|
||||
snapshot.Metadata.AgeSeconds = int64(age / time.Second)
|
||||
if age > r.config.MaxAge {
|
||||
snapshot.Metadata.Fresh = false
|
||||
return invalid(snapshot, fmt.Sprintf("元数据已陈旧:采集于 %s,超过 %s", file.CollectedAt, r.config.MaxAge))
|
||||
}
|
||||
snapshot.Metadata.Fresh = true
|
||||
if strings.TrimSpace(r.config.HostRoot) == "" {
|
||||
return invalid(snapshot, "宿主根路径未配置:无法校验批次路径")
|
||||
}
|
||||
expectedRoot := path.Clean(strings.TrimSpace(r.config.HostRoot))
|
||||
snapshot.HostRoot = expectedRoot
|
||||
root := strings.TrimSpace(file.Root)
|
||||
if !path.IsAbs(root) || path.Clean(root) != root {
|
||||
return invalid(snapshot, "元数据 root 不是规范绝对路径:"+root)
|
||||
}
|
||||
if root != expectedRoot {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
|
||||
}
|
||||
snapshot.Root = root
|
||||
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 {
|
||||
return invalid(snapshot, err.Error())
|
||||
}
|
||||
snapshot.Metadata.Valid = true
|
||||
snapshot.IncompleteCount = file.IncompleteCount
|
||||
snapshot.Skipped = append(snapshot.Skipped, file.Skipped...)
|
||||
snapshot.Truncated = file.Truncated
|
||||
snapshot.Mount = MountInfo{
|
||||
Evidence: "宿主采集器上报:" + file.Host,
|
||||
MountPoint: file.Filesystem.MountPoint,
|
||||
Device: file.Filesystem.MountSource,
|
||||
FSType: file.Filesystem.FSType,
|
||||
ReadOnly: file.Filesystem.ReadOnly,
|
||||
}
|
||||
if file.Filesystem.MountPoint == "" || !path.IsAbs(file.Filesystem.MountPoint) {
|
||||
snapshot.Mount.Error = "宿主采集器没有给出文件系统挂载点"
|
||||
} else if root != file.Filesystem.MountPoint && !strings.HasPrefix(root, strings.TrimSuffix(file.Filesystem.MountPoint, "/")+"/") {
|
||||
snapshot.Mount.Error = "批次根不在采集器上报的挂载点下"
|
||||
} else {
|
||||
snapshot.Mount.MountVerified = true
|
||||
snapshot.Mount.Evidence = fmt.Sprintf("宿主采集器:%s 挂在 %s(%s),API 不遍历备份目录",
|
||||
file.Filesystem.MountSource, file.Filesystem.MountPoint, file.Filesystem.FSType)
|
||||
}
|
||||
|
||||
// 快照不完整/截断:路径与清单状态可展示,但所有字节与容量一律未知,
|
||||
// 绝不用部分 counts 或完整批次的局部字节拼总量。
|
||||
complete := file.Complete && !file.Truncated && snapshot.Mount.MountVerified && allBatchesComplete(file.Batches)
|
||||
if !complete {
|
||||
snapshot.Metadata.Complete = false
|
||||
snapshot.Metadata.Error = incompleteReason(file)
|
||||
snapshot.Capacity = Capacity{Error: "采集快照不完整:容量与占盘未知"}
|
||||
snapshot.Mount.MountVerified = false
|
||||
snapshot.Mount.Error = "采集快照不完整,不能据此判定文件系统与占盘"
|
||||
snapshot.Batches = projectBatches(root, file.Batches, false)
|
||||
snapshot.Totals = totals(snapshot.Batches, false)
|
||||
snapshot.Error = ""
|
||||
return snapshot
|
||||
}
|
||||
|
||||
snapshot.Metadata.Complete = true
|
||||
snapshot.Capacity = projectCapacity(file.Filesystem)
|
||||
snapshot.Batches = projectBatches(root, file.Batches, true)
|
||||
snapshot.Totals = totals(snapshot.Batches, true)
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (r *Reader) observedAt() string {
|
||||
if r == nil || r.now == nil {
|
||||
return ""
|
||||
}
|
||||
return r.now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
snapshot.Metadata.Valid = false
|
||||
snapshot.Metadata.Complete = false
|
||||
snapshot.Metadata.Error = reason
|
||||
snapshot.Error = reason
|
||||
snapshot.Batches = []Batch{}
|
||||
snapshot.Capacity = Capacity{Error: reason}
|
||||
snapshot.Totals = Totals{}
|
||||
snapshot.Usage = Usage{Error: reason}
|
||||
snapshot.QuotaBytes = nil
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func incompleteReason(file metadata) string {
|
||||
if len(file.Errors) > 0 {
|
||||
return "采集不完整:" + strings.Join(limit(file.Errors, 3), ";")
|
||||
}
|
||||
for _, batch := range file.Batches {
|
||||
if len(batch.Errors) > 0 {
|
||||
return "采集不完整:" + strings.Join(limit(batch.Errors, 3), ";")
|
||||
}
|
||||
}
|
||||
return "采集不完整:存在无法遍历/统计的目录,占盘与容量未知"
|
||||
}
|
||||
|
||||
func limit(items []string, n int) []string {
|
||||
if len(items) <= n {
|
||||
return items
|
||||
}
|
||||
return items[:n]
|
||||
}
|
||||
|
||||
func allBatchesComplete(batches []metadataBatch) bool {
|
||||
for _, batch := range batches {
|
||||
if !batch.Complete || batch.ActualBytes == nil || batch.ApparentBytes == nil || batch.FileCount == nil {
|
||||
return false
|
||||
}
|
||||
for _, database := range batch.Databases {
|
||||
if database.ActualBytes == nil || database.ApparentBytes == nil || database.FileCount == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 校验的是"快照里的路径能否被安全地当成这台主机的批次/子库":
|
||||
// 根必须精确匹配配置,批次必须精确等于 root/<stamp>,子库必须精确等于
|
||||
// batch/<name>.dir,且不允许重复、分隔符、.incomplete。
|
||||
func validateBatches(root string, batches []metadataBatch) error {
|
||||
seen := map[string]bool{}
|
||||
for _, batch := range batches {
|
||||
stamp := strings.TrimSpace(batch.Stamp)
|
||||
if err := safeSegment(stamp); err != nil {
|
||||
return fmt.Errorf("批次名不合法:%q(%v)", stamp, err)
|
||||
}
|
||||
if strings.HasSuffix(stamp, ".incomplete") {
|
||||
return fmt.Errorf("批次 %q 是未完成目录,不应进入快照", stamp)
|
||||
}
|
||||
if seen[stamp] {
|
||||
return fmt.Errorf("批次 %q 重复", stamp)
|
||||
}
|
||||
seen[stamp] = true
|
||||
expected := path.Join(root, stamp)
|
||||
if batch.Path != expected || !path.IsAbs(batch.Path) {
|
||||
return fmt.Errorf("批次 %q 路径 %q 不等于 %q", stamp, batch.Path, expected)
|
||||
}
|
||||
switch ManifestState(batch.ManifestState) {
|
||||
case ManifestOK, ManifestMissing, ManifestInvalid:
|
||||
default:
|
||||
return fmt.Errorf("批次 %q 的 manifest_state 不认识:%q", stamp, batch.ManifestState)
|
||||
}
|
||||
databaseSeen := map[string]bool{}
|
||||
for _, database := range batch.Databases {
|
||||
name := strings.TrimSpace(database.Name)
|
||||
if err := safeSegment(name); err != nil {
|
||||
return fmt.Errorf("批次 %q 子库名不合法:%q", stamp, name)
|
||||
}
|
||||
if databaseSeen[name] {
|
||||
return fmt.Errorf("批次 %q 子库 %q 重复", stamp, name)
|
||||
}
|
||||
databaseSeen[name] = true
|
||||
expectedDir := path.Join(expected, name+".dir")
|
||||
if database.DirName != name+".dir" || database.Path != expectedDir || !path.IsAbs(database.Path) {
|
||||
return fmt.Errorf("批次 %q 子库 %q 路径不合法:%q", stamp, name, database.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeSegment(value string) error {
|
||||
if value == "" || value == "." || value == ".." {
|
||||
return errors.New("空值或相对路径")
|
||||
}
|
||||
for _, r := range value {
|
||||
if r == '/' || r == '\\' || r == 0 || r == '\n' || r == '\r' {
|
||||
return errors.New("包含路径分隔符或控制字符")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func projectBatches(root string, batches []metadataBatch, complete bool) []Batch {
|
||||
result := make([]Batch, 0, len(batches))
|
||||
for _, batch := range batches {
|
||||
item := Batch{
|
||||
Stamp: batch.Stamp,
|
||||
Path: path.Join(root, batch.Stamp),
|
||||
HostPath: path.Join(root, batch.Stamp),
|
||||
ManifestState: ManifestState(batch.ManifestState),
|
||||
ManifestPath: path.Join(root, batch.Stamp, "MANIFEST.json"),
|
||||
ManifestError: batch.ManifestError,
|
||||
Kind: batch.Kind,
|
||||
CreatedAt: batch.CreatedAt,
|
||||
StartedAt: batch.StartedAt,
|
||||
DurationSeconds: batch.DurationSeconds,
|
||||
SizesComplete: complete && batch.Complete,
|
||||
Databases: []Database{},
|
||||
}
|
||||
if complete && batch.Complete {
|
||||
item.ManifestTotalBytes = batch.ManifestTotalBytes
|
||||
item.ApparentBytes = batch.ApparentBytes
|
||||
item.ActualBytes = batch.ActualBytes
|
||||
item.FileCount = batch.FileCount
|
||||
}
|
||||
for _, database := range batch.Databases {
|
||||
entry := Database{
|
||||
Name: database.Name,
|
||||
DirName: database.DirName,
|
||||
Path: path.Join(root, batch.Stamp, database.DirName),
|
||||
HostPath: path.Join(root, batch.Stamp, database.DirName),
|
||||
Present: database.Present,
|
||||
Failed: database.Failed,
|
||||
InManifest: database.InManifest,
|
||||
}
|
||||
if complete && batch.Complete {
|
||||
entry.ApparentBytes = database.ApparentBytes
|
||||
entry.ActualBytes = database.ActualBytes
|
||||
entry.FileCount = database.FileCount
|
||||
}
|
||||
item.Databases = append(item.Databases, entry)
|
||||
}
|
||||
if !item.SizesComplete {
|
||||
item.SizesError = "宿主采集器该项不完整,占盘未知"
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return result[i].Stamp > result[j].Stamp })
|
||||
return result
|
||||
}
|
||||
|
||||
func totals(batches []Batch, complete bool) Totals {
|
||||
result := Totals{BatchCount: len(batches), Complete: complete}
|
||||
if len(batches) > 0 {
|
||||
result.LatestStamp = batches[0].Stamp
|
||||
}
|
||||
for _, batch := range batches {
|
||||
result.DatabaseCount += len(batch.Databases)
|
||||
}
|
||||
if !complete {
|
||||
return result
|
||||
}
|
||||
var apparent, actual int64
|
||||
for _, batch := range batches {
|
||||
if batch.ApparentBytes != nil {
|
||||
apparent += *batch.ApparentBytes
|
||||
}
|
||||
if batch.ActualBytes != nil {
|
||||
actual += *batch.ActualBytes
|
||||
}
|
||||
}
|
||||
result.ApparentBytes = &apparent
|
||||
result.ActualBytes = &actual
|
||||
if len(batches) > 0 {
|
||||
result.LatestActualBytes = batches[0].ActualBytes
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func projectCapacity(filesystem metadataFilesystem) Capacity {
|
||||
if filesystem.TotalBytes <= 0 {
|
||||
return Capacity{Error: "宿主采集器没有给出文件系统容量"}
|
||||
}
|
||||
used := filesystem.TotalBytes - filesystem.FreeBytes
|
||||
if used < 0 {
|
||||
used = 0
|
||||
}
|
||||
return Capacity{
|
||||
Measured: true,
|
||||
TotalBytes: filesystem.TotalBytes,
|
||||
FreeBytes: filesystem.FreeBytes,
|
||||
AvailableBytes: filesystem.AvailableBytes,
|
||||
UsedBytes: used,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package backupinventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const hostRoot = "/srv/kb-backups/rds-logical"
|
||||
|
||||
func int64p(value int64) *int64 { return &value }
|
||||
func intp(value int) *int { return &value }
|
||||
|
||||
func validMetadata() metadata {
|
||||
latest := hostRoot + "/20261118T193001Z"
|
||||
broken := hostRoot + "/20261117T193001Z"
|
||||
without := hostRoot + "/20261116T193001Z"
|
||||
return metadata{
|
||||
SchemaVersion: SchemaVersion,
|
||||
CollectorVersion: "backup-metadata/1",
|
||||
Generation: "20261120T010000Z-abc123",
|
||||
CollectedAt: "2026-11-20T01:00:00Z",
|
||||
Host: "weknora-test",
|
||||
Source: "weknora-test:" + hostRoot,
|
||||
Root: hostRoot,
|
||||
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,
|
||||
Errors: []string{},
|
||||
Filesystem: metadataFilesystem{
|
||||
MountPoint: "/srv/kb-backups",
|
||||
MountSource: "/dev/sdb1",
|
||||
FSType: "ext4",
|
||||
ReadOnly: false,
|
||||
TotalBytes: 1000,
|
||||
FreeBytes: 400,
|
||||
AvailableBytes: 350,
|
||||
},
|
||||
IncompleteCount: 1,
|
||||
Skipped: []Skipped{{Name: "notes.txt", Reason: "不是批次目录"}},
|
||||
Batches: []metadataBatch{
|
||||
{
|
||||
Stamp: "20261118T193001Z",
|
||||
Path: latest,
|
||||
ManifestState: "ok",
|
||||
Kind: "rds-logical-backup",
|
||||
CreatedAt: "20261118T193001Z",
|
||||
StartedAt: "20261118T192908Z",
|
||||
DurationSeconds: 53,
|
||||
ManifestTotalBytes: int64p(300),
|
||||
Complete: true,
|
||||
ApparentBytes: int64p(300),
|
||||
ActualBytes: int64p(4096),
|
||||
FileCount: intp(3),
|
||||
Databases: []metadataDatabase{
|
||||
{
|
||||
Name: "weknora_v090prod", DirName: "weknora_v090prod.dir",
|
||||
Path: latest + "/weknora_v090prod.dir", Present: true, InManifest: true,
|
||||
ApparentBytes: int64p(250), ActualBytes: int64p(4096), FileCount: intp(2),
|
||||
},
|
||||
{
|
||||
Name: "weknora_test", DirName: "weknora_test.dir",
|
||||
Path: latest + "/weknora_test.dir", Present: true, InManifest: true, Failed: true,
|
||||
ApparentBytes: int64p(50), ActualBytes: int64p(0), FileCount: intp(1),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Stamp: "20261117T193001Z",
|
||||
Path: broken,
|
||||
ManifestState: "invalid", ManifestError: "清单无法解析:unexpected end",
|
||||
Complete: true, ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
|
||||
Databases: []metadataDatabase{{
|
||||
Name: "weknora_prod", DirName: "weknora_prod.dir",
|
||||
Path: broken + "/weknora_prod.dir", Present: true,
|
||||
ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
|
||||
}},
|
||||
},
|
||||
{
|
||||
Stamp: "20261116T193001Z",
|
||||
Path: without,
|
||||
ManifestState: "missing",
|
||||
Complete: true, ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
|
||||
Databases: []metadataDatabase{{
|
||||
Name: "weknora_archive", DirName: "weknora_archive.dir",
|
||||
Path: without + "/weknora_archive.dir", Present: true,
|
||||
ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func writeMetadata(t *testing.T, value metadata) string {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filename := filepath.Join(t.TempDir(), "metadata.json")
|
||||
if err := os.WriteFile(filename, raw, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return filename
|
||||
}
|
||||
|
||||
func readerAt(filename string, now time.Time) *Reader {
|
||||
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, BackupRoot: "/srv/kb-backups", Source: "configured", MaxAge: 15 * time.Minute})
|
||||
reader.now = func() time.Time { return now }
|
||||
return reader
|
||||
}
|
||||
|
||||
func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
|
||||
filename := writeMetadata(t, validMetadata())
|
||||
now := time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)
|
||||
snapshot := readerAt(filename, now).Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Error != "" || !snapshot.Metadata.Valid || !snapshot.Metadata.Fresh || !snapshot.Metadata.Complete {
|
||||
t.Fatalf("应接受新鲜的完整快照: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || snapshot.Mount.MountPoint != "/srv/kb-backups" {
|
||||
t.Fatalf("宿主挂载判定不对: %+v", snapshot.Mount)
|
||||
}
|
||||
if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
|
||||
t.Fatalf("容量不对: %+v", snapshot.Capacity)
|
||||
}
|
||||
if snapshot.Metadata.AgeSeconds != 300 || snapshot.Metadata.Generation == "" || snapshot.Metadata.Host != "weknora-test" {
|
||||
t.Fatalf("元数据字段不对: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 || len(snapshot.Skipped) != 1 {
|
||||
t.Fatalf("批次计数不对: %+v", snapshot)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK || latest.SizesComplete != true {
|
||||
t.Fatalf("最近批次不对: %+v", latest)
|
||||
}
|
||||
if latest.HostPath != hostRoot+"/20261118T193001Z" || latest.ManifestTotalBytes == nil || *latest.ManifestTotalBytes != 300 {
|
||||
t.Fatalf("批次路径/清单不对: %+v", latest)
|
||||
}
|
||||
prod := latest.Databases[0]
|
||||
if prod.HostPath != hostRoot+"/20261118T193001Z/weknora_v090prod.dir" || prod.ActualBytes == nil || *prod.ActualBytes != 4096 {
|
||||
t.Fatalf("子库完整路径/占盘不对: %+v", prod)
|
||||
}
|
||||
if !latest.Databases[1].Failed {
|
||||
t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
|
||||
}
|
||||
if snapshot.Batches[1].ManifestState != ManifestInvalid || snapshot.Batches[1].ManifestError == "" {
|
||||
t.Fatalf("损坏清单没有如实标记: %+v", snapshot.Batches[1])
|
||||
}
|
||||
if snapshot.Batches[2].ManifestState != ManifestMissing {
|
||||
t.Fatalf("缺清单没有如实标记: %+v", snapshot.Batches[2])
|
||||
}
|
||||
if snapshot.Totals.ActualBytes == nil || *snapshot.Totals.ActualBytes != 4096+2048+1024 || !snapshot.Totals.Complete {
|
||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||
}
|
||||
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
|
||||
t.Fatalf("来源/测量方式不对: %+v", snapshot.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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotStaleIsUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.CollectedAt = "2026-11-20T00:00:00Z"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || snapshot.Metadata.Fresh || snapshot.Metadata.Complete {
|
||||
t.Fatalf("陈旧快照不能算有效: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 0 || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
|
||||
t.Fatalf("陈旧快照不能给批次/容量/占盘: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "陈旧") {
|
||||
t.Fatalf("陈旧原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotMissingMetadata(t *testing.T) {
|
||||
reader := New(Config{MetadataPath: filepath.Join(t.TempDir(), "missing.json"), HostRoot: hostRoot})
|
||||
snapshot := reader.Snapshot(context.Background())
|
||||
if !snapshot.Wired || snapshot.Metadata.Present || snapshot.Metadata.Valid {
|
||||
t.Fatalf("缺失快照不能算有效: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "不存在") {
|
||||
t.Fatalf("缺失原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotPermissionFailureNeverUsesPartialBytes(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Complete = false
|
||||
value.Errors = nil
|
||||
value.Batches[0].Complete = false
|
||||
value.Batches[0].Errors = []string{"遍历失败:PermissionError: Permission denied ('.../weknora_v090prod.dir')"}
|
||||
// 模拟采集器在权限失败前已经数到的部分字节;API 绝不能把它们当占盘。
|
||||
value.Batches[0].ActualBytes = int64p(100)
|
||||
value.Batches[0].Databases[0].ActualBytes = int64p(100)
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if !snapshot.Metadata.Valid || snapshot.Metadata.Complete {
|
||||
t.Fatalf("不完整快照应 valid=true/complete=false: %+v", snapshot.Metadata)
|
||||
}
|
||||
if snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil || snapshot.Totals.ApparentBytes != nil {
|
||||
t.Fatalf("不完整快照不能给容量/总量: %+v", snapshot)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 {
|
||||
t.Fatalf("路径仍应列出: %+v", snapshot.Batches)
|
||||
}
|
||||
latest := snapshot.Batches[0]
|
||||
if latest.ActualBytes != nil || latest.ApparentBytes != nil || latest.FileCount != nil || latest.SizesComplete {
|
||||
t.Fatalf("不完整批次不能保留部分字节: %+v", latest)
|
||||
}
|
||||
if latest.Databases[0].ActualBytes != nil || latest.Databases[0].ApparentBytes != nil {
|
||||
t.Fatalf("不完整子库不能保留部分字节: %+v", latest.Databases[0])
|
||||
}
|
||||
if !strings.Contains(snapshot.Metadata.Error, "Permission") {
|
||||
t.Fatalf("权限失败原因丢失: %q", snapshot.Metadata.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotTruncatedIsUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Truncated = true
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Complete || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
|
||||
t.Fatalf("截断快照不能算完整/容量: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsPathMismatch(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Batches[0].Path = "/srv/kb-backups/rds-logical/../evil"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("路径不一致必须整块拒绝: %+v", snapshot.Metadata)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "路径") {
|
||||
t.Fatalf("路径错误原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsUnsupportedSchema(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.SchemaVersion = 99
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || !strings.Contains(snapshot.Error, "schema_version") {
|
||||
t.Fatalf("不支持的 schema 必须拒绝: %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotUnconfigured(t *testing.T) {
|
||||
snapshot := New(Config{}).Snapshot(context.Background())
|
||||
if snapshot.Wired || snapshot.Error == "" || len(snapshot.Batches) != 0 {
|
||||
t.Fatalf("未接线必须给出原因且不伪造批次: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "未接线") {
|
||||
t.Fatalf("未接线原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// 宿主采集器的权限失败回归:self-test 用注入 walker 模拟 PermissionError,
|
||||
// 断言不完整时字节为 null 且不产生部分统计。
|
||||
func TestCollectorSelfTest(t *testing.T) {
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("python3 not available")
|
||||
}
|
||||
command := exec.Command(python, "../../scripts/collect_backup_metadata.py", "--self-test")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("collector self-test failed: %v\n%s", err, output)
|
||||
}
|
||||
if !strings.Contains(string(output), "self-test ok") {
|
||||
t.Fatalf("collector self-test output unexpected: %s", output)
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,11 @@ func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 「知识库绑定」saves a connection (address + key) and both bindings for one
|
||||
// environment in one write: same authority as the annotation binding.
|
||||
if strings.HasPrefix(path, "/api/v1/kb-bindings") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Choosing the production base a release writes into is a production
|
||||
// authority change, exactly like the annotation binding above.
|
||||
if path == "/api/v1/production-kb-bindings" && method != http.MethodGet {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
// BackupInventoryReader 读取宿主采集器写出的元数据快照。它与 SSH 主机计划读回完全独立:
|
||||
// 快照缺失/陈旧不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
|
||||
type BackupInventoryReader interface {
|
||||
Available() bool
|
||||
Snapshot(context.Context) backupinventory.Snapshot
|
||||
}
|
||||
|
||||
// handleBackupInventory 返回宿主采集器快照里的批次、子库路径与容量。
|
||||
// 未接线/快照缺失/陈旧/不完整/路径不一致都作为 200 的字段返回,由页面区分原因;
|
||||
// 只有投影本身失败才 500。
|
||||
func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
|
||||
snapshot := config.BackupInventory.Snapshot(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": snapshot})
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
)
|
||||
|
||||
type fakeBackupInventory struct {
|
||||
snapshot backupinventory.Snapshot
|
||||
}
|
||||
|
||||
func (fake fakeBackupInventory) Available() bool { return fake.snapshot.Wired }
|
||||
|
||||
func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapshot {
|
||||
return fake.snapshot
|
||||
}
|
||||
|
||||
func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
actual := int64(1024)
|
||||
databaseActual := int64(512)
|
||||
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
|
||||
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{
|
||||
MountVerified: true,
|
||||
ReadOnly: true,
|
||||
Evidence: "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4)",
|
||||
},
|
||||
Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
|
||||
Batches: []backupinventory.Batch{{
|
||||
Stamp: "20261118T193001Z",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
|
||||
ManifestState: backupinventory.ManifestOK,
|
||||
ActualBytes: &actual,
|
||||
Databases: []backupinventory.Database{{
|
||||
Name: "weknora_v090prod",
|
||||
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
|
||||
Present: true,
|
||||
ActualBytes: &databaseActual,
|
||||
}},
|
||||
}},
|
||||
Totals: backupinventory.Totals{BatchCount: 1, ActualBytes: &actual, LatestStamp: "20261118T193001Z", Complete: true},
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !payload.Data.Wired || !payload.Data.Mount.MountVerified || !payload.Data.Capacity.Measured {
|
||||
t.Fatalf("接线/挂载/容量字段丢失: %+v", payload.Data)
|
||||
}
|
||||
if len(payload.Data.Batches) != 1 ||
|
||||
payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
|
||||
t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
|
||||
}
|
||||
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
|
||||
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
||||
}
|
||||
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) {
|
||||
config := Config{BackupInventory: backupinventory.New(backupinventory.Config{})}
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("未接线不应 500: %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
Data backupinventory.Snapshot `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Data.Wired || payload.Data.Error == "" || payload.Data.Batches == nil {
|
||||
t.Fatalf("未接线必须给原因且批次为空数组: %+v", payload.Data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
// KBBindingStore is the environment-scoped 「知识库绑定」capability. Save does
|
||||
// the real candidate read itself, so the HTTP layer decides no policy beyond
|
||||
// status/role.
|
||||
type KBBindingStore interface {
|
||||
List(context.Context) ([]kbbinding.View, error)
|
||||
Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error)
|
||||
Save(context.Context, string, kbbinding.SaveInput, string, time.Time) (kbbinding.View, error)
|
||||
ResolveBaseURL(context.Context, string) string
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
views, err := config.KBBindings.List(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load knowledge base bindings"})
|
||||
return
|
||||
}
|
||||
storageReady := false
|
||||
for _, view := range views {
|
||||
storageReady = storageReady || view.StorageReady
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"environments": views,
|
||||
"storage_ready": storageReady,
|
||||
}})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.CatalogInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
|
||||
return
|
||||
}
|
||||
catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": catalog})
|
||||
}
|
||||
|
||||
func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KBBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "knowledge base binding storage unavailable"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "kb-bindings" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "knowledge base binding write intent is required"})
|
||||
return
|
||||
}
|
||||
env := r.PathValue("environment")
|
||||
if !kbbinding.ValidEnvironment(env) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown environment"})
|
||||
return
|
||||
}
|
||||
var input kbbinding.SaveInput
|
||||
if err := decodeJSONStrict(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
|
||||
return
|
||||
}
|
||||
input.SourceAddress, input.SourceOrigin = requestAuditSource(r)
|
||||
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeKBBindingError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view, "operation": "saved"})
|
||||
}
|
||||
|
||||
func writeKBBindingError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, kbbinding.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "绑定参数不合法:请检查地址、密钥与内外库选择"})
|
||||
case errors.Is(err, kbbinding.ErrConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "该环境的绑定已被其他保存更新;草稿未写入,旧绑定保持不变,请重新读取后再试"})
|
||||
case errors.Is(err, kbbinding.ErrKeyForwarding):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址"})
|
||||
case errors.Is(err, kbbinding.ErrNotConfigured):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "这个地址还没有可用 API Key:请输入密钥或先选择已配置的连接"})
|
||||
case errors.Is(err, kbbinding.ErrStorage):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "独立安全存储未就绪(WEKNORA_BINDING_MASTER_KEY_FILE);未写入任何绑定"})
|
||||
case errors.Is(err, kbbinding.ErrRejected):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrRejected.Error()+":")})
|
||||
case errors.Is(err, kbbinding.ErrUnreachable):
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": strings.TrimPrefix(err.Error(), kbbinding.ErrUnreachable.Error()+":")})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
)
|
||||
|
||||
type fakeKBBindings struct {
|
||||
views []kbbinding.View
|
||||
catalog kbbinding.Catalog
|
||||
saveErr error
|
||||
catalogErr error
|
||||
lastSave kbbinding.SaveInput
|
||||
lastActor string
|
||||
}
|
||||
|
||||
func (fake *fakeKBBindings) List(context.Context) ([]kbbinding.View, error) {
|
||||
return fake.views, nil
|
||||
}
|
||||
func (fake *fakeKBBindings) Catalog(context.Context, string, kbbinding.CatalogInput) (kbbinding.Catalog, error) {
|
||||
return fake.catalog, fake.catalogErr
|
||||
}
|
||||
func (fake *fakeKBBindings) Save(_ context.Context, _ string, input kbbinding.SaveInput, actor string, _ time.Time) (kbbinding.View, error) {
|
||||
fake.lastSave = input
|
||||
fake.lastActor = actor
|
||||
if fake.saveErr != nil {
|
||||
return kbbinding.View{}, fake.saveErr
|
||||
}
|
||||
return fake.views[0], nil
|
||||
}
|
||||
func (fake *fakeKBBindings) ResolveBaseURL(context.Context, string) string { return "" }
|
||||
|
||||
func kbBindingHandler(t *testing.T, store KBBindingStore) *Config {
|
||||
t.Helper()
|
||||
config := &Config{KBBindings: store, Now: func() time.Time { return time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC) }}
|
||||
return config
|
||||
}
|
||||
|
||||
func TestKBBindingsReadNeverEchoesSecretsAndWriteRequiresIntent(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{
|
||||
Environment: kbbinding.EnvTest, Revision: 2, BaseURL: "https://weknora.test.example",
|
||||
KeyConfigured: true, KeySource: "sealed", InternalKBID: "kb-in", InternalKBName: "内部",
|
||||
ExternalKBID: "kb-out", ExternalKBName: "对外", Source: "web", StorageReady: true,
|
||||
}}}
|
||||
config := kbBindingHandler(t, store)
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, forbidden := range []string{"api_key", "key_ciphertext", "sealed-key-value"} {
|
||||
if strings.Contains(body, forbidden) {
|
||||
t.Fatalf("read response exposes %q: %s", forbidden, body)
|
||||
}
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("save without intent status = %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
|
||||
store := &fakeKBBindings{
|
||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}},
|
||||
saveErr: kbbinding.ErrConflict,
|
||||
}
|
||||
config := kbBindingHandler(t, store)
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/kb-bindings/test", bytes.NewBufferString(`{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingSave(response, request)
|
||||
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "旧绑定保持不变") {
|
||||
t.Fatalf("conflict status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingCatalogAndSaveAcceptTypedKeysOnPlainHTTP(t *testing.T) {
|
||||
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)
|
||||
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(catalogBody))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("plain HTTP catalog status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "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) {
|
||||
for _, path := range []string{"/api/v1/kb-bindings/test", "/api/v1/kb-bindings/test/catalog"} {
|
||||
if role := classifyRole(http.MethodPut, path); role != roleAdmin {
|
||||
t.Fatalf("PUT %s role = %s, want admin", path, role)
|
||||
}
|
||||
if role := classifyRole(http.MethodGet, "/api/v1/kb-bindings"); role != roleViewer {
|
||||
t.Fatalf("GET bindings role = %s, want viewer", role)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingsReadDoesNotReportTransportCapability(t *testing.T) {
|
||||
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
|
||||
config := kbBindingHandler(t, store)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
|
||||
request.Host = "172.29.151.11:28188"
|
||||
response := httptest.NewRecorder()
|
||||
config.handleKBBindings(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "secret_entry_allowed") {
|
||||
t.Fatalf("read response still reports the removed capability: %s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) {
|
||||
const (
|
||||
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"}`
|
||||
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{
|
||||
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
|
||||
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
|
||||
}
|
||||
for _, allow := range []bool{false, true} {
|
||||
config := kbBindingHandler(t, store)
|
||||
config.WeKnoraAllowPrivateHTTP = allow
|
||||
|
||||
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("save with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
|
||||
}
|
||||
if store.lastSave.APIKey != "typed-key" {
|
||||
t.Fatalf("save with toggle=%v did not forward the typed key: %q", allow, store.lastSave.APIKey)
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
|
||||
request.SetPathValue("environment", "test")
|
||||
request.Header.Set("X-Governance-Action", "kb-bindings")
|
||||
response = httptest.NewRecorder()
|
||||
config.handleKBBindingCatalog(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
|
||||
switch value := node.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range value {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" {
|
||||
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" && path != "components.schemas.KBBindingEnvironmentView.properties" && path != "components.schemas.KBCatalogInput.properties" && path != "components.schemas.KBBindingSaveInput.properties" {
|
||||
t.Fatalf("unapproved endpoint exposure at %s", path)
|
||||
}
|
||||
next := key
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
"knowledge-governance/internal/pgdsn"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
@@ -88,6 +89,11 @@ func (config Config) libraryPublishTarget() libraryPublishTargetView {
|
||||
// productionTargetBaseURL is the production endpoint the picker reads from: the
|
||||
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
|
||||
func (config Config) productionTargetBaseURL(ctx context.Context) string {
|
||||
if config.KBBindings != nil {
|
||||
if resolved := strings.TrimSpace(config.KBBindings.ResolveBaseURL(ctx, kbbinding.EnvProduction)); resolved != "" {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
|
||||
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
|
||||
return resolved
|
||||
|
||||
@@ -2,11 +2,9 @@ package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
)
|
||||
|
||||
func qaAIError(w http.ResponseWriter, err error) {
|
||||
@@ -42,24 +40,7 @@ func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool {
|
||||
return true
|
||||
}
|
||||
func qaAISecretTransport(r *http.Request, c Config) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := r.Host
|
||||
if parsed, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = parsed
|
||||
}
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return true
|
||||
}
|
||||
if c.QAAITrustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
return err == nil && origin.Scheme == "https"
|
||||
}
|
||||
return false
|
||||
return secretTransportAllowed(r, c.QAAITrustTLSProxy)
|
||||
}
|
||||
func registerQAAIRoutes(mux *http.ServeMux, c Config) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -17,7 +17,7 @@ type RoutingBindingStore interface {
|
||||
SaveRoutingKBBindings(context.Context, string, string, string) error
|
||||
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
|
||||
// were still waiting for the previous knowledge base (same transaction).
|
||||
SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||||
SaveRoutingKBBindingsWithReplan(ctx context.Context, save postgresstore.RoutingBindingSave, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||||
}
|
||||
|
||||
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
|
||||
@@ -196,6 +196,9 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
|
||||
// The saved binding re-routes FUTURE annotations; pending 待入库 items that
|
||||
// have never been uploaded are re-pointed in the same transaction, otherwise
|
||||
// they would keep aiming at the previous (possibly removed) knowledge base.
|
||||
// Only items aimed at the PREVIOUS effective target of this side move, so a
|
||||
// test-side save cannot carry off production-side pending work.
|
||||
previousInternal, previousExternal := config.effectiveRoutingTargets(r.Context())
|
||||
effectiveInternal := internal
|
||||
if effectiveInternal == "" {
|
||||
effectiveInternal = config.InternalRoutingKnowledgeBaseID
|
||||
@@ -204,7 +207,12 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
|
||||
if effectiveExternal == "" {
|
||||
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), internal, external, effectiveInternal, effectiveExternal, actorFor(r), config.Now().UTC())
|
||||
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), postgresstore.RoutingBindingSave{
|
||||
InternalID: internal, ExternalID: external,
|
||||
Previous: postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
|
||||
Effective: postgresstore.EffectiveKBIDs{Internal: effectiveInternal, External: effectiveExternal},
|
||||
UpdatedBy: actorFor(r),
|
||||
}, config.Now().UTC())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
|
||||
return
|
||||
|
||||
@@ -18,7 +18,8 @@ type bindingStoreFake struct {
|
||||
external string
|
||||
saver string
|
||||
// replan records what the last save asked for, so tests can assert that the
|
||||
// effective (env-fallback aware) targets were used.
|
||||
// effective (env-fallback aware) targets and the previous pair were used.
|
||||
replanPrevious [2]string
|
||||
replanEffective [2]string
|
||||
replanResult postgresstore.RoutingBindingReplanResult
|
||||
replanCallCount int
|
||||
@@ -33,9 +34,10 @@ func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, internal, external, effectiveInternal, effectiveExternal, updatedBy string, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
|
||||
fake.internal, fake.external, fake.saver = internal, external, updatedBy
|
||||
fake.replanEffective = [2]string{effectiveInternal, effectiveExternal}
|
||||
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, save postgresstore.RoutingBindingSave, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
|
||||
fake.internal, fake.external, fake.saver = save.InternalID, save.ExternalID, save.UpdatedBy
|
||||
fake.replanPrevious = [2]string{save.Previous.Internal, save.Previous.External}
|
||||
fake.replanEffective = [2]string{save.Effective.Internal, save.Effective.External}
|
||||
fake.replanCallCount++
|
||||
return fake.replanResult, nil
|
||||
}
|
||||
@@ -134,6 +136,9 @@ func TestRoutingBindingsSaveReportsReplanAndUsesEffectiveTargets(t *testing.T) {
|
||||
if store.replanEffective != [2]string{"kb-in", "env-external"} {
|
||||
t.Fatalf("effective targets = %#v, want the env fallback on the unbound side", store.replanEffective)
|
||||
}
|
||||
if store.replanPrevious != [2]string{"env-internal", "env-external"} {
|
||||
t.Fatalf("previous targets = %#v, want the pre-save effective pair", store.replanPrevious)
|
||||
}
|
||||
var envelope struct {
|
||||
Data struct {
|
||||
Replanned int `json:"replanned"`
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// secretTransportAllowed is the strict rule for QA AI model keys: a real TLS
|
||||
// connection, a loopback request, or a same-origin HTTPS request that a trusted
|
||||
// reverse proxy forwarded. The browser's origin scheme must agree, so a
|
||||
// plain-HTTP page behind a misconfigured proxy cannot submit a key even if it
|
||||
// spoofs X-Forwarded-Proto. Knowledge base keys deliberately do not use it.
|
||||
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
if loopbackHost(r.Host) {
|
||||
return true
|
||||
}
|
||||
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
|
||||
origin, err := url.Parse(r.Header.Get("Origin"))
|
||||
return err == nil && origin.Scheme == "https"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// requestHostname strips the optional port and IPv6 brackets. Brackets come
|
||||
// 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,
|
||||
// so they stay untouched and keep failing the address checks.
|
||||
func requestHostname(host string) string {
|
||||
host = strings.TrimSpace(host)
|
||||
if strings.HasPrefix(host, "[") {
|
||||
end := strings.Index(host, "]")
|
||||
if end <= 0 {
|
||||
return host
|
||||
}
|
||||
ip := net.ParseIP(host[1:end])
|
||||
if ip == nil || ip.To4() != nil {
|
||||
return host
|
||||
}
|
||||
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
|
||||
return host
|
||||
}
|
||||
return ip.String()
|
||||
}
|
||||
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
|
||||
return parsedHost
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// loopbackHost is the address-only part of the secret transport rule: a
|
||||
// request from this machine never crosses a network.
|
||||
func loopbackHost(host string) bool {
|
||||
host = requestHostname(host)
|
||||
if strings.EqualFold(host, "localhost") {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||
request.Host = "[::1]"
|
||||
if !secretTransportAllowed(request, false) {
|
||||
t.Fatal("bare [::1] Host was rejected as a loopback transport")
|
||||
}
|
||||
request.Host = "console.example"
|
||||
if secretTransportAllowed(request, false) {
|
||||
t.Fatal("public name without TLS was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
|
||||
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.Host = host
|
||||
if secretTransportAllowed(request, false) {
|
||||
t.Fatalf("Host %q was accepted as a loopback transport", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
|
||||
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
|
||||
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
|
||||
request.Host = host
|
||||
if secretTransportAllowed(request, false) {
|
||||
t.Fatalf("Host %q was accepted as a loopback transport", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/backupinventory"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
@@ -137,6 +138,13 @@ type Config struct {
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
KnowledgeBases KnowledgeBaseLister
|
||||
// KBBindings is the environment-scoped 「知识库绑定」store: connection +
|
||||
// internal/external bindings saved together. Nil keeps the page read-only
|
||||
// and reports unavailable, never a fake success.
|
||||
KBBindings KBBindingStore
|
||||
// WeKnoraAllowPrivateHTTP 决定客户端/探活是否放行同网段 http(生产 18093 反代);
|
||||
// 不再参与控制台密钥录入判定。
|
||||
WeKnoraAllowPrivateHTTP bool
|
||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
|
||||
@@ -194,10 +202,13 @@ type Config struct {
|
||||
// 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。
|
||||
LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error)
|
||||
// LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
LibraryRetentionVersions int
|
||||
LibraryRetentionDays int
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
// BackupInventory 读的是只读挂载的 rds-logical 目录(批次/子库/实测容量)。
|
||||
// 与 BackupHost 的 SSH 计划读回分离,任一侧失败都不能影响另一侧。
|
||||
BackupInventory BackupInventoryReader
|
||||
BackupRuns *BackupRunTracker
|
||||
ProductionBindings ProductionBindingStore
|
||||
ProductionKnowledgeBases ProductionKnowledgeBaseLister
|
||||
@@ -247,6 +258,10 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
// 未挂载主机凭据:Available()=false,页面显示"未接线"而不是 500。
|
||||
config.BackupHost = backuphost.New(backuphost.Config{})
|
||||
}
|
||||
if config.BackupInventory == nil {
|
||||
// 未挂载只读备份目录:批次/容量显示"未接线",独立于 SSH 计划读回。
|
||||
config.BackupInventory = backupinventory.New(backupinventory.Config{})
|
||||
}
|
||||
for _, knowledgeBaseID := range []string{config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID} {
|
||||
if knowledgeBaseID != "" && !validCatalogID(knowledgeBaseID) {
|
||||
return nil, errors.New("routing knowledge base ID is invalid")
|
||||
@@ -404,6 +419,15 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleSaveRoutingBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/kb-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/kb-bindings/{environment}/catalog", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindingCatalog(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/kb-bindings/{environment}", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleKBBindingSave(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.BackupSchedule == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
|
||||
@@ -418,6 +442,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleBackupScheduleHost(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/backup-schedule/inventory", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleBackupInventory(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.BackupSchedule == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
// Package kbbinding 是「知识库绑定」的唯一服务端入口:按环境保存连接
|
||||
// (地址 + 加密后的 API Key)和对内/对外知识库绑定,并提供候选人列库、
|
||||
// 选库归属校验与消费者解析。旧的部署文件凭据/默认绑定在没有任何新行时
|
||||
// 继续生效,所以升级不需要回填数据。
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
const (
|
||||
EnvTest = "test"
|
||||
EnvProduction = "production"
|
||||
)
|
||||
|
||||
func Environments() []string { return []string{EnvTest, EnvProduction} }
|
||||
|
||||
func ValidEnvironment(value string) bool {
|
||||
return value == EnvTest || value == EnvProduction
|
||||
}
|
||||
|
||||
func EnvironmentLabel(value string) string {
|
||||
if value == EnvProduction {
|
||||
return "生产 090"
|
||||
}
|
||||
return "测试 090"
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("invalid knowledge base binding")
|
||||
ErrConflict = errors.New("knowledge base binding revision conflict")
|
||||
ErrKeyForwarding = errors.New("old key must not follow a new address")
|
||||
ErrNotConfigured = errors.New("weknora connection is not configured")
|
||||
ErrStorage = errors.New("secure binding storage is not ready")
|
||||
ErrRejected = errors.New("weknora rejected the candidate connection")
|
||||
ErrUnreachable = errors.New("weknora candidate connection is unreachable")
|
||||
)
|
||||
|
||||
// View is the public projection. It never carries a key, ciphertext or any
|
||||
// value derived from the key beyond "configured or not".
|
||||
type View struct {
|
||||
Environment string `json:"environment"`
|
||||
Revision int64 `json:"revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyConfigured bool `json:"key_configured"`
|
||||
KeySource string `json:"key_source"`
|
||||
// KeyTail is the only part of the key the page may show. It is derived at
|
||||
// read time and never stored, so a rotated master key cannot resurrect it.
|
||||
KeyTail string `json:"key_tail"`
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
Verification string `json:"verification"`
|
||||
CheckedAt *time.Time `json:"checked_at"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
// Source says where this effective configuration comes from: a row saved on
|
||||
// this page, or the pre-existing deployment file/default binding.
|
||||
Source string `json:"source"`
|
||||
StorageReady bool `json:"storage_ready"`
|
||||
// Replanned / RetiredDuplicates only report what a save just did to 待入库
|
||||
// rows that had never been uploaded; a plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
// 留空绑定 = 取消绑定,页面必须说清回退到了哪里:测试侧回退到部署默认库,
|
||||
// 生产侧回退到「同 ID 语义」。空串表示该方向仍有显式绑定。
|
||||
InternalFallback string `json:"internal_fallback"`
|
||||
ExternalFallback string `json:"external_fallback"`
|
||||
// 生产侧冻结计数:执行已开始的发布项目标已钉死,保存绑定不会改写它们。
|
||||
Frozen int `json:"frozen"`
|
||||
Retargetable int `json:"retargetable"`
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
}
|
||||
|
||||
type Catalog struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
Options []Option `json:"options"`
|
||||
}
|
||||
|
||||
type CatalogInput struct {
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyAction string `json:"key_action"`
|
||||
APIKey string `json:"api_key"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
type SaveInput struct {
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
BaseURL string `json:"base_url"`
|
||||
KeyAction string `json:"key_action"`
|
||||
APIKey string `json:"api_key"`
|
||||
InternalKBID string `json:"internal_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
|
||||
// reach the effective instance. It never leaves the server.
|
||||
type Target struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Revision int64
|
||||
Source string
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
MasterKeyFile string
|
||||
Timeout time.Duration
|
||||
// AllowDockerHTTP mirrors the per-environment client policy (a single-label
|
||||
// docker host may be reached over plain HTTP in the internal network).
|
||||
AllowDockerHTTP map[string]bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses
|
||||
// (production 18093 reverse proxy). Public http stays refused.
|
||||
AllowPrivateHTTP map[string]bool
|
||||
// LegacyBaseURL resolves the pre-existing endpoint (web setting first, then
|
||||
// the deployment env value). It is only consulted when no row exists.
|
||||
LegacyBaseURL func(context.Context, string) string
|
||||
// LegacyKey reads the deployment credential file. It is only consulted when
|
||||
// no row exists, or when a keep action targets exactly that legacy address.
|
||||
LegacyKey func(string) (string, error)
|
||||
// LegacyBinding resolves the pre-existing internal/external binding ids.
|
||||
LegacyBinding func(context.Context, string) (string, string, error)
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type DB interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db DB
|
||||
options Options
|
||||
}
|
||||
|
||||
func New(db DB, options Options) *Store {
|
||||
if options.Timeout <= 0 {
|
||||
options.Timeout = 10 * time.Second
|
||||
}
|
||||
if options.Now == nil {
|
||||
options.Now = time.Now
|
||||
}
|
||||
return &Store{db: db, options: options}
|
||||
}
|
||||
|
||||
type stored struct {
|
||||
Environment string
|
||||
Revision int64
|
||||
BaseURL string
|
||||
KeyCiphertext []byte
|
||||
InternalKBID string
|
||||
ExternalKBID string
|
||||
InternalKBName string
|
||||
ExternalKBName string
|
||||
Verification string
|
||||
CheckedAt *time.Time
|
||||
UpdatedBy string
|
||||
UpdatedAt *time.Time
|
||||
}
|
||||
|
||||
const bindingColumns = `environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at`
|
||||
|
||||
func scanStored(row pgx.Row) (stored, bool, error) {
|
||||
var value stored
|
||||
err := row.Scan(&value.Environment, &value.Revision, &value.BaseURL, &value.KeyCiphertext,
|
||||
&value.InternalKBID, &value.ExternalKBID, &value.InternalKBName, &value.ExternalKBName,
|
||||
&value.Verification, &value.CheckedAt, &value.UpdatedBy, &value.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return stored{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return stored{}, false, err
|
||||
}
|
||||
return value, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) load(ctx context.Context, env string) (stored, bool, error) {
|
||||
if !ValidEnvironment(env) {
|
||||
return stored{}, false, ErrInvalid
|
||||
}
|
||||
return scanStored(s.db.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1`, env))
|
||||
}
|
||||
|
||||
func (s *Store) StorageReady() bool {
|
||||
return s.loadBox() != nil
|
||||
}
|
||||
|
||||
func (s *Store) loadBox() *secretbox.Box {
|
||||
box, err := secretbox.Load(s.options.MasterKeyFile)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return box
|
||||
}
|
||||
|
||||
func (s *Store) legacyBaseURL(ctx context.Context, env string) string {
|
||||
if s.options.LegacyBaseURL == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(s.options.LegacyBaseURL(ctx, env))
|
||||
}
|
||||
|
||||
func (s *Store) legacyKey(env string) (string, error) {
|
||||
if s.options.LegacyKey == nil {
|
||||
return "", nil
|
||||
}
|
||||
value, err := s.options.LegacyKey(env)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(value), nil
|
||||
}
|
||||
|
||||
// List returns both environments' effective views for the page header and the
|
||||
// environment switch. Names are best-effort: an unreachable instance yields
|
||||
// short ids instead of hiding the binding.
|
||||
func (s *Store) List(ctx context.Context) ([]View, error) {
|
||||
views := make([]View, 0, 2)
|
||||
for _, env := range Environments() {
|
||||
view, err := s.Get(ctx, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return views, nil
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, env string) (View, error) {
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view := View{Environment: env, StorageReady: s.StorageReady(), Source: "legacy"}
|
||||
if found {
|
||||
view.Revision = saved.Revision
|
||||
view.BaseURL = saved.BaseURL
|
||||
view.KeyConfigured = len(saved.KeyCiphertext) > 0
|
||||
view.KeySource = keySource(view.KeyConfigured)
|
||||
view.InternalKBID = saved.InternalKBID
|
||||
view.InternalKBName = saved.InternalKBName
|
||||
view.ExternalKBID = saved.ExternalKBID
|
||||
view.ExternalKBName = saved.ExternalKBName
|
||||
view.Verification = saved.Verification
|
||||
view.CheckedAt = saved.CheckedAt
|
||||
view.UpdatedBy = saved.UpdatedBy
|
||||
view.UpdatedAt = saved.UpdatedAt
|
||||
view.Source = "web"
|
||||
if s.options.MasterKeyFile != "" {
|
||||
if tail, ok := s.keyTail(saved, env); ok {
|
||||
view.KeyTail = tail
|
||||
}
|
||||
}
|
||||
s.fillFallbacks(ctx, env, &view)
|
||||
s.fillExecutionCounts(ctx, env, &view)
|
||||
return view, nil
|
||||
}
|
||||
// Legacy fallback: exactly what the consumers use before any page save.
|
||||
view.BaseURL = s.legacyBaseURL(ctx, env)
|
||||
if key, keyErr := s.legacyKey(env); keyErr == nil && key != "" {
|
||||
view.KeyConfigured = true
|
||||
view.KeySource = "file"
|
||||
}
|
||||
if s.options.LegacyBinding != nil {
|
||||
internal, external, bindErr := s.options.LegacyBinding(ctx, env)
|
||||
if bindErr != nil {
|
||||
return View{}, bindErr
|
||||
}
|
||||
view.InternalKBID = internal
|
||||
view.ExternalKBID = external
|
||||
}
|
||||
view.Verification = "legacy"
|
||||
s.fillFallbacks(ctx, env, &view)
|
||||
s.fillExecutionCounts(ctx, env, &view)
|
||||
s.fillNames(ctx, &view)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// keyTail decrypts only to keep the last four characters. It never returns the
|
||||
// key and never writes the tail anywhere.
|
||||
func (s *Store) keyTail(saved stored, env string) (string, bool) {
|
||||
box := s.loadBox()
|
||||
if box == nil || len(saved.KeyCiphertext) == 0 {
|
||||
return "", false
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
runes := []rune(string(raw))
|
||||
if len(runes) <= 4 {
|
||||
return string(runes), true
|
||||
}
|
||||
return string(runes[len(runes)-4:]), true
|
||||
}
|
||||
|
||||
// fillFallbacks explains where an unbound direction routes to. Without this the
|
||||
// page could only say 「留空」without saying what 「空」means.
|
||||
func (s *Store) fillFallbacks(ctx context.Context, env string, view *View) {
|
||||
if view.InternalKBID != "" && view.ExternalKBID != "" {
|
||||
return
|
||||
}
|
||||
if env == EnvProduction {
|
||||
if view.InternalKBID == "" {
|
||||
view.InternalFallback = "same-id"
|
||||
}
|
||||
if view.ExternalKBID == "" {
|
||||
view.ExternalFallback = "same-id"
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.options.LegacyBinding == nil {
|
||||
return
|
||||
}
|
||||
internal, external, err := s.options.LegacyBinding(ctx, env)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if view.InternalKBID == "" && strings.TrimSpace(internal) != "" {
|
||||
view.InternalFallback = strings.TrimSpace(internal)
|
||||
}
|
||||
if view.ExternalKBID == "" && strings.TrimSpace(external) != "" {
|
||||
view.ExternalFallback = strings.TrimSpace(external)
|
||||
}
|
||||
}
|
||||
|
||||
// fillExecutionCounts reports how many in-flight release items already have a
|
||||
// frozen production target. Completed executions are history, not something a
|
||||
// binding change could still move.
|
||||
func (s *Store) fillExecutionCounts(ctx context.Context, env string, view *View) {
|
||||
if env != EnvProduction {
|
||||
return
|
||||
}
|
||||
var frozen, retargetable int
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE item.target_knowledge_base_id <> ''),
|
||||
COUNT(*) FILTER (WHERE item.target_knowledge_base_id = '')
|
||||
FROM release_item_executions item
|
||||
JOIN release_executions execution ON execution.id = item.release_execution_id
|
||||
WHERE execution.state IN ('pending','running')`).Scan(&frozen, &retargetable)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
view.Frozen, view.Retargetable = frozen, retargetable
|
||||
}
|
||||
|
||||
func keySource(configured bool) string {
|
||||
if configured {
|
||||
return "sealed"
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
// fillNames reads names from the effective instance for the legacy view. A
|
||||
// failure leaves names empty; ids still identify the binding.
|
||||
func (s *Store) fillNames(ctx context.Context, view *View) {
|
||||
if view.BaseURL == "" || (view.InternalKBID == "" && view.ExternalKBID == "") {
|
||||
return
|
||||
}
|
||||
// 只是把 ID 换成名字:不能让一次不可达的旧实例拖住整个页面读取。
|
||||
namesCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
key, err := s.legacyKey(view.Environment)
|
||||
if err != nil || key == "" {
|
||||
return
|
||||
}
|
||||
client, err := s.client(view.BaseURL, key, view.Environment)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
names := map[string]string{}
|
||||
page := 1
|
||||
for page <= 20 {
|
||||
result, err := client.ListKnowledgeBasesPage(namesCtx, page, 100)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, base := range result.Items {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
if result.Total <= int64(page*100) || len(result.Items) < 100 {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
view.InternalKBName = names[view.InternalKBID]
|
||||
view.ExternalKBName = names[view.ExternalKBID]
|
||||
}
|
||||
|
||||
// Resolve returns the effective connection consumers must use. A saved row is
|
||||
// authoritative: if its key cannot be opened we fail closed instead of falling
|
||||
// back to the file credential (that would send the old key to a new address).
|
||||
func (s *Store) Resolve(ctx context.Context, env string) (Target, error) {
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
if found {
|
||||
if saved.BaseURL == "" {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
if len(saved.KeyCiphertext) == 0 {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return Target{}, ErrStorage
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return Target{}, ErrStorage
|
||||
}
|
||||
return Target{BaseURL: saved.BaseURL, APIKey: string(raw), Revision: saved.Revision, Source: "web"}, nil
|
||||
}
|
||||
baseURL := s.legacyBaseURL(ctx, env)
|
||||
key, err := s.legacyKey(env)
|
||||
if err != nil {
|
||||
return Target{}, err
|
||||
}
|
||||
if baseURL == "" || key == "" {
|
||||
return Target{}, ErrNotConfigured
|
||||
}
|
||||
return Target{BaseURL: baseURL, APIKey: key, Source: "legacy"}, nil
|
||||
}
|
||||
|
||||
// ResolveBaseURL is for health probes that only need the endpoint (no key).
|
||||
func (s *Store) ResolveBaseURL(ctx context.Context, env string) string {
|
||||
if saved, found, err := s.load(ctx, env); err == nil && found && saved.BaseURL != "" {
|
||||
return saved.BaseURL
|
||||
}
|
||||
return s.legacyBaseURL(ctx, env)
|
||||
}
|
||||
|
||||
func (s *Store) keyFor(ctx context.Context, env string, action, baseURL, apiKey string, saved stored, found bool) (string, error) {
|
||||
switch action {
|
||||
case "keep":
|
||||
if apiKey != "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if found {
|
||||
if saved.BaseURL != baseURL {
|
||||
return "", ErrKeyForwarding
|
||||
}
|
||||
if len(saved.KeyCiphertext) == 0 {
|
||||
return "", ErrNotConfigured
|
||||
}
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return "", ErrStorage
|
||||
}
|
||||
raw, err := box.Open(saved.KeyCiphertext, keyAAD(env, saved.Revision))
|
||||
if err != nil {
|
||||
return "", ErrStorage
|
||||
}
|
||||
return string(raw), nil
|
||||
}
|
||||
// First save on an upgraded deployment: keeping the deployment file key
|
||||
// is allowed only for exactly that legacy address.
|
||||
if s.legacyBaseURL(ctx, env) != baseURL {
|
||||
return "", ErrKeyForwarding
|
||||
}
|
||||
return s.legacyKey(env)
|
||||
case "replace":
|
||||
if !validAPIKey(apiKey) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return apiKey, nil
|
||||
case "clear":
|
||||
// 清除密钥是独立动作:留下地址与绑定,只是这一侧不再有可用凭据,
|
||||
// 消费者解析会失败关闭(不会悄悄回落到部署文件里的旧 Key)。
|
||||
if apiKey != "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return "", nil
|
||||
default:
|
||||
return "", ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func validAPIKey(value string) bool {
|
||||
return value != "" && len(value) <= 4096 && strings.TrimSpace(value) == value && !strings.ContainsAny(value, "\r\n\x00")
|
||||
}
|
||||
|
||||
func (s *Store) client(baseURL, apiKey, env string) (*weknora.Client, error) {
|
||||
return weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: s.options.Timeout,
|
||||
AllowDockerHTTP: s.options.AllowDockerHTTP[env],
|
||||
AllowPrivateHTTP: s.options.AllowPrivateHTTP[env],
|
||||
})
|
||||
}
|
||||
|
||||
func keyAAD(env string, revision int64) string {
|
||||
return "weknora-binding:" + env + ":" + strconv.FormatInt(revision, 10)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
type emptyDB struct{}
|
||||
|
||||
func (emptyDB) QueryRow(context.Context, string, ...any) pgx.Row { return emptyRow{} }
|
||||
func (emptyDB) Begin(context.Context) (pgx.Tx, error) {
|
||||
return nil, errors.New("no transaction in unit test")
|
||||
}
|
||||
|
||||
type emptyRow struct{}
|
||||
|
||||
func (emptyRow) Scan(...any) error { return pgx.ErrNoRows }
|
||||
|
||||
// fakeWeKnora serves the two reads the candidate validation makes: one page of
|
||||
// knowledge bases and a single base by id.
|
||||
func fakeWeKnora(t *testing.T, wantKey string, bases []struct{ id, name string }, total int64) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("X-API-Key"); got != wantKey {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/knowledge-bases" {
|
||||
items := make([]string, 0, len(bases))
|
||||
for _, base := range bases {
|
||||
items = append(items, `{"id":"`+base.id+`","name":"`+base.name+`","knowledge_count":2}`)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[` + strings.Join(items, ",") + `],"total":` + strconv.FormatInt(total, 10) + `}`))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/") {
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/")
|
||||
for _, base := range bases {
|
||||
if base.id == id {
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"` + base.id + `","name":"` + base.name + `"}}`))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
func TestCatalogDistinguishesEmptyFromPermissionFromUnreachable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}})
|
||||
|
||||
empty := fakeWeKnora(t, "key-1", nil, 0)
|
||||
catalog, err := store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: empty.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusEmpty || catalog.Total != 0 {
|
||||
t.Fatalf("empty catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
denied := fakeWeKnora(t, "another-key", nil, 0)
|
||||
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: denied.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusKeyInvalid {
|
||||
t.Fatalf("denied catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
|
||||
down := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
downURL := down.URL
|
||||
down.Close()
|
||||
catalog, err = store.Catalog(ctx, EnvTest, CatalogInput{
|
||||
BaseURL: downURL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusUnreachable {
|
||||
t.Fatalf("unreachable catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogPaginatesAndReturnsNamesWithShortIDsAreStable(t *testing.T) {
|
||||
server := fakeWeKnora(t, "key-1", []struct{ id, name string }{{"kb-1", "技术资料"}}, 1)
|
||||
store := New(emptyDB{}, Options{Timeout: 2 * time.Second, AllowDockerHTTP: map[string]bool{EnvTest: true}})
|
||||
catalog, err := store.Catalog(context.Background(), EnvTest, CatalogInput{
|
||||
BaseURL: server.URL, KeyAction: "replace", APIKey: "key-1", Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil || catalog.Status != statusOK || len(catalog.Options) != 1 || catalog.Options[0].Name != "技术资料" {
|
||||
t.Fatalf("catalog = %#v, %v", catalog, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyActionRulesRejectForwardingAndInvalidInput(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{})
|
||||
saved := stored{Environment: EnvTest, Revision: 1, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://new.example", "", saved, true); !errors.Is(err, ErrKeyForwarding) {
|
||||
t.Fatalf("keep with a new address = %v, want ErrKeyForwarding", err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "keep", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("keep with a typed key = %v, want ErrInvalid", err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "replace", "https://new.example", " ", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("replace with blank key = %v, want ErrInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
|
||||
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
||||
store := New(emptyDB{}, Options{Now: func() time.Time { return now }})
|
||||
for _, input := range []SaveInput{
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"},
|
||||
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"},
|
||||
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
|
||||
} {
|
||||
if _, err := store.Save(context.Background(), EnvTest, input, "admin", now); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("input %#v error = %v, want ErrInvalid", input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogDistinguishesInvalidKeyFromForbiddenKey(t *testing.T) {
|
||||
invalid := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusUnauthorized})
|
||||
if invalid.Status != "key_invalid" || !strings.Contains(invalid.Message, "密钥无效") {
|
||||
t.Fatalf("401 -> %+v", invalid)
|
||||
}
|
||||
forbidden := catalogFailure(&weknora.HTTPError{StatusCode: http.StatusForbidden})
|
||||
if forbidden.Status != "key_forbidden" || !strings.Contains(forbidden.Message, "无权限") {
|
||||
t.Fatalf("403 -> %+v", forbidden)
|
||||
}
|
||||
dead := catalogFailure(context.DeadlineExceeded)
|
||||
if dead.Status != "unreachable" || !(strings.Contains(dead.Message, "超时") || strings.Contains(dead.Message, "不可达")) {
|
||||
t.Fatalf("timeout -> %+v", dead)
|
||||
}
|
||||
if dead.Status == invalid.Status || invalid.Status == forbidden.Status {
|
||||
t.Fatal("the three outcomes must stay distinguishable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearKeyIsASeparateAction(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{})
|
||||
saved := stored{Environment: EnvTest, Revision: 2, BaseURL: "https://old.example", KeyCiphertext: []byte("sealed")}
|
||||
key, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "", saved, true)
|
||||
if err != nil || key != "" {
|
||||
t.Fatalf("clear = %q, %v", key, err)
|
||||
}
|
||||
if _, err := store.keyFor(context.Background(), EnvTest, "clear", "https://old.example", "typed", saved, true); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("clear with a typed key = %v, want ErrInvalid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyTailShowsOnlyFourCharacters(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "master.key")
|
||||
if err := os.WriteFile(path, bytes.Repeat([]byte{7}, 32), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
box, err := secretbox.Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("secretbox.Load: %v", err)
|
||||
}
|
||||
sealed, err := box.Seal([]byte("sk-live-abcd"), keyAAD(EnvTest, 3))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := New(emptyDB{}, Options{MasterKeyFile: path})
|
||||
tail, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 3}, EnvTest)
|
||||
if !ok || tail != "abcd" {
|
||||
t.Fatalf("tail = %q %v", tail, ok)
|
||||
}
|
||||
// A different revision must not open — the tail must never leak from a
|
||||
// ciphertext that no longer matches the row.
|
||||
if _, ok := store.keyTail(stored{KeyCiphertext: sealed, Revision: 4}, EnvTest); ok {
|
||||
t.Fatal("tail opened with the wrong revision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
|
||||
store := New(emptyDB{}, Options{LegacyBinding: func(context.Context, string) (string, string, error) {
|
||||
return "legacy-in-0001", "legacy-out-0001", nil
|
||||
}})
|
||||
view := View{Environment: EnvTest}
|
||||
store.fillFallbacks(context.Background(), EnvTest, &view)
|
||||
if view.InternalFallback != "legacy-in-0001" || view.ExternalFallback != "legacy-out-0001" {
|
||||
t.Fatalf("test fallbacks = %+v", view)
|
||||
}
|
||||
production := View{Environment: EnvProduction}
|
||||
store.fillFallbacks(context.Background(), EnvProduction, &production)
|
||||
if production.InternalFallback != "same-id" || production.ExternalFallback != "same-id" {
|
||||
t.Fatalf("production fallbacks = %+v", production)
|
||||
}
|
||||
bound := View{Environment: EnvTest, InternalKBID: "a", ExternalKBID: "b"}
|
||||
store.fillFallbacks(context.Background(), EnvTest, &bound)
|
||||
if bound.InternalFallback != "" || bound.ExternalFallback != "" {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
package kbbinding_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/kbbinding"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/postgres/pgtest"
|
||||
)
|
||||
|
||||
// testSecret() 在运行时拼出测试夹具密钥,避免把任何字面量误当成真实凭据入库。
|
||||
func testSecret() string { return "fixture-" + strings.Repeat("k", 24) }
|
||||
|
||||
func fakeCandidate(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != testSecret() {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/knowledge-bases":
|
||||
_, _ = w.Write([]byte(`{"success":true,"total":5,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4},{"id":"p-internal","name":"生产内部资料","knowledge_count":5},{"id":"p-external","name":"生产客户手册","knowledge_count":6},{"id":"p-new-internal","name":"生产内部资料新版","knowledge_count":0}]}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/p-internal":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-internal","name":"生产内部资料","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/p-external":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-external","name":"生产客户手册","tenant_id":10000}}`))
|
||||
case r.URL.Path == "/api/v1/knowledge-bases/p-new-internal":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-new-internal","name":"生产内部资料新版","tenant_id":10000}}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
func masterKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "binding-master.key")
|
||||
if err := os.WriteFile(path, []byte(strings.Repeat("k", 32)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction(t *testing.T) {
|
||||
databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true);
|
||||
INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES
|
||||
('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope'),
|
||||
('item-prod-kbb','conn-kbb','n-prod-kbb',repeat('d',64),'docs/prod-kbb.docx','prod-kbb.docx','document','locator:r2','internal','configured_scope');
|
||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
||||
('version-kbb','item-kbb','locator:r1',NULL,'unknown'),
|
||||
('version-prod-kbb','item-prod-kbb','locator:r2',NULL,'unknown');
|
||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
||||
('pub-kbb','version-kbb','kb-legacy-in','planned','pending','internal'),
|
||||
('pub-prod-kbb','version-prod-kbb','p-internal','planned','pending','internal');
|
||||
`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := fakeCandidate(t)
|
||||
store := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: masterKey(t),
|
||||
Timeout: 2 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
|
||||
// 留空的一侧回退到部署默认绑定:用例必须能断言回退来源写了什么。
|
||||
LegacyBinding: func(context.Context, string) (string, string, error) {
|
||||
return "kb-legacy-in", "kb-legacy-out", nil
|
||||
},
|
||||
})
|
||||
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
|
||||
// 留空 = 取消该方向绑定,不再报 ErrInvalid:只填对内也要能保存,
|
||||
// 对外回退到部署默认库,响应里必须写明回退来源。
|
||||
internalOnly, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("save with an unbound side = %v, want success", err)
|
||||
}
|
||||
if internalOnly.Revision != 1 || !internalOnly.KeyConfigured ||
|
||||
internalOnly.InternalKBID != "kb-in" || internalOnly.InternalKBName != "内部技术资料" ||
|
||||
internalOnly.ExternalKBID != "" || internalOnly.ExternalKBName != "" ||
|
||||
internalOnly.ExternalFallback != "kb-legacy-out" || internalOnly.InternalFallback != "" {
|
||||
t.Fatalf("internal-only view = %#v", internalOnly)
|
||||
}
|
||||
// 只填对内也要把未上传的待入库项改指向对内库。
|
||||
if internalOnly.Replanned != 1 {
|
||||
t.Fatalf("internal-only replanned = %d, want 1", internalOnly.Replanned)
|
||||
}
|
||||
view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 1, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("Save() error = %v", err)
|
||||
}
|
||||
if view.Revision != 2 || !view.KeyConfigured || view.InternalKBName != "内部技术资料" || view.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("view = %#v", view)
|
||||
}
|
||||
// 待入库项在第一次保存时已经指向 kb-in:这次补上对外绑定不再移动任何行。
|
||||
if view.Replanned != 0 {
|
||||
t.Fatalf("second save replanned = %d, want 0", view.Replanned)
|
||||
}
|
||||
target, err := store.Resolve(ctx, kbbinding.EnvTest)
|
||||
if err != nil || target.BaseURL != server.URL || target.APIKey != testSecret() || target.Revision != 2 {
|
||||
t.Fatalf("Resolve() = %#v, %v", target, err)
|
||||
}
|
||||
var routingInternal, routingExternal string
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal, &routingExternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routingInternal != "kb-in" || routingExternal != "kb-out" {
|
||||
t.Fatalf("routing binding = %s/%s", routingInternal, routingExternal)
|
||||
}
|
||||
var pendingKB string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&pendingKB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pendingKB != "kb-in" {
|
||||
t.Fatalf("pending publication target = %s, want kb-in", pendingKB)
|
||||
}
|
||||
// A save on the test card must not carry off pending work that already aims
|
||||
// at the production binding: the two environments share test_publications.
|
||||
var productionPending string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod-kbb'`).Scan(&productionPending); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if productionPending != "p-internal" {
|
||||
t.Fatalf("test-side save moved a production pending item to %s", productionPending)
|
||||
}
|
||||
|
||||
// A stale revision must not overwrite the saved connection or re-point work.
|
||||
_, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 1, BaseURL: server.URL, KeyAction: "keep",
|
||||
InternalKBID: "kb-out", ExternalKBID: "kb-in",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if !errors.Is(err, kbbinding.ErrConflict) {
|
||||
t.Fatalf("stale save error = %v, want ErrConflict", err)
|
||||
}
|
||||
unchanged, err := store.Resolve(ctx, kbbinding.EnvTest)
|
||||
if err != nil || unchanged.APIKey != testSecret() {
|
||||
t.Fatalf("connection changed after conflict: %#v, %v", unchanged, err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM routing_kb_bindings WHERE id='active'`).Scan(&routingInternal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if routingInternal != "kb-in" {
|
||||
t.Fatalf("routing binding changed after conflict: %s", routingInternal)
|
||||
}
|
||||
|
||||
// A base from another instance (404 here) must be refused and leave no row
|
||||
// for a different environment.
|
||||
if _, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "not-there", ExternalKBID: "kb-out",
|
||||
}, "admin", now); !errors.Is(err, kbbinding.ErrRejected) {
|
||||
t.Fatalf("unknown base error = %v, want ErrRejected", err)
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM weknora_environment_bindings WHERE environment='production'`).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("failed production save wrote %d rows", count)
|
||||
}
|
||||
|
||||
// The old key must never be forwarded: keep is only legal for the saved URL.
|
||||
if _, err := store.Catalog(ctx, kbbinding.EnvTest, kbbinding.CatalogInput{
|
||||
BaseURL: "https://another.example", KeyAction: "keep", Page: 1, PageSize: 20,
|
||||
}); !errors.Is(err, kbbinding.ErrKeyForwarding) {
|
||||
t.Fatalf("keep with another address = %v, want ErrKeyForwarding", err)
|
||||
}
|
||||
|
||||
prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "p-internal", ExternalKBID: "p-external",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("production Save() error = %v", err)
|
||||
}
|
||||
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 || prodView.Replanned != 0 {
|
||||
t.Fatalf("production view = %#v", prodView)
|
||||
}
|
||||
// Changing the production internal base must re-point pending 待入库 items
|
||||
// that were waiting for p-internal (the C-006 failure), and must leave the
|
||||
// test-lane publication on its own target.
|
||||
prodMoved, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: prodView.Revision, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "p-new-internal", ExternalKBID: "p-external",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("production retarget Save() error = %v", err)
|
||||
}
|
||||
if prodMoved.Replanned != 1 || prodMoved.RetiredDuplicates != 0 {
|
||||
t.Fatalf("production replan = %d/%d, want 1 moved / 0 retired", prodMoved.Replanned, prodMoved.RetiredDuplicates)
|
||||
}
|
||||
var movedProduction, stillTest string
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod-kbb'`).Scan(&movedProduction); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if movedProduction != "p-new-internal" {
|
||||
t.Fatalf("production pending target = %s, want p-new-internal", movedProduction)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&stillTest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stillTest != "kb-in" {
|
||||
t.Fatalf("test publication moved by a production save: %s", stillTest)
|
||||
}
|
||||
var productionInternal, productionURL string
|
||||
var productionTenant uint64
|
||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if productionInternal != "p-new-internal" || productionURL != server.URL || productionTenant != 10000 {
|
||||
t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
|
||||
}
|
||||
}
|
||||
|
||||
// 清除密钥只清凭据:名称、库 ID、绑定、实例身份全部保留,消费者必须失败关闭
|
||||
// (绝不回落到部署文件里的旧 Key),历史表只记「是否配置」而不含任何密钥。
|
||||
func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) {
|
||||
databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := fakeCandidate(t)
|
||||
store := kbbinding.New(pool, kbbinding.Options{
|
||||
MasterKeyFile: masterKey(t),
|
||||
Timeout: 2 * time.Second,
|
||||
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
|
||||
// 部署文件里仍留着旧 Key:清除之后解析必须 ErrNotConfigured,不能悄悄用它。
|
||||
LegacyKey: func(string) (string, error) { return testSecret(), nil },
|
||||
})
|
||||
now := time.Date(2026, 11, 20, 8, 0, 0, 0, time.UTC)
|
||||
|
||||
saved, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("seed Save() error = %v", err)
|
||||
}
|
||||
if saved.Revision != 1 || saved.InternalKBName != "内部技术资料" || saved.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("seed view = %#v", saved)
|
||||
}
|
||||
|
||||
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
|
||||
// 非 HTTPS 控制台保存:审计行必须能还原当时的入口与客户端地址。
|
||||
SourceAddress: "172.29.151.11", SourceOrigin: "http://172.29.151.11:8088",
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("clear Save() error = %v", err)
|
||||
}
|
||||
if cleared.Revision != 2 || cleared.KeyConfigured || cleared.KeyTail != "" {
|
||||
t.Fatalf("cleared view = %#v", cleared)
|
||||
}
|
||||
if cleared.Verification != "not_configured" {
|
||||
t.Fatalf("verification = %q, want not_configured", cleared.Verification)
|
||||
}
|
||||
if cleared.InternalKBID != "kb-in" || cleared.ExternalKBID != "kb-out" ||
|
||||
cleared.InternalKBName != "内部技术资料" || cleared.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("clear dropped the binding or its names: %#v", cleared)
|
||||
}
|
||||
if _, err := store.Resolve(ctx, kbbinding.EnvTest); !errors.Is(err, kbbinding.ErrNotConfigured) {
|
||||
t.Fatalf("Resolve() after clear = %v, want ErrNotConfigured", err)
|
||||
}
|
||||
|
||||
// 「同时改指向又清密钥」:改过的一侧不能沿用旧库名(否则新库顶着旧名字),
|
||||
// 没动的一侧仍然保留原名称。
|
||||
retargeted, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||
BaseRevision: cleared.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: "kb-new", ExternalKBID: "kb-out",
|
||||
}, "admin", now.Add(2*time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("retarget+clear Save() error = %v", err)
|
||||
}
|
||||
if retargeted.Revision != 3 || retargeted.InternalKBID != "kb-new" || retargeted.InternalKBName != "" ||
|
||||
retargeted.ExternalKBID != "kb-out" || retargeted.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("retarget+clear view = %#v", retargeted)
|
||||
}
|
||||
|
||||
// 生产侧同一口径:租户与实例地址是执行器的一致性凭据,清密钥不能把它们清零。
|
||||
prodSaved, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
||||
}, "admin", now)
|
||||
if err != nil {
|
||||
t.Fatalf("production seed Save() error = %v", err)
|
||||
}
|
||||
prodCleared, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||
BaseRevision: prodSaved.Revision, BaseURL: server.URL, KeyAction: "clear",
|
||||
InternalKBID: prodSaved.InternalKBID, ExternalKBID: prodSaved.ExternalKBID,
|
||||
}, "admin", now.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("production clear Save() error = %v", err)
|
||||
}
|
||||
if prodCleared.Revision != 2 || prodCleared.KeyConfigured || prodCleared.Verification != "not_configured" ||
|
||||
prodCleared.InternalKBName != "内部技术资料" || prodCleared.ExternalKBName != "客户使用手册" {
|
||||
t.Fatalf("production cleared view = %#v", prodCleared)
|
||||
}
|
||||
var prodInternal, prodExternal, prodInternalURL, prodExternalURL string
|
||||
var prodInternalTenant, prodExternalTenant uint64
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT internal_kb_id,external_kb_id,internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id
|
||||
FROM production_kb_bindings WHERE id='active'`).
|
||||
Scan(&prodInternal, &prodExternal, &prodInternalURL, &prodExternalURL, &prodInternalTenant, &prodExternalTenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prodInternal != "kb-in" || prodExternal != "kb-out" || prodInternalURL != server.URL || prodExternalURL != server.URL ||
|
||||
prodInternalTenant != 10000 || prodExternalTenant != 10000 {
|
||||
t.Fatalf("production identity after clear = %s/%s %s/%s %d/%d",
|
||||
prodInternal, prodExternal, prodInternalURL, prodExternalURL, prodInternalTenant, prodExternalTenant)
|
||||
}
|
||||
if _, err := store.Resolve(ctx, kbbinding.EnvProduction); !errors.Is(err, kbbinding.ErrNotConfigured) {
|
||||
t.Fatalf("production Resolve() after clear = %v, want ErrNotConfigured", err)
|
||||
}
|
||||
|
||||
// 历史表只记布尔:既没有密钥列,也不含密钥明文。
|
||||
var keyConfigured bool
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT key_configured FROM weknora_environment_binding_history
|
||||
WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keyConfigured {
|
||||
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
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema=current_schema() AND table_name='weknora_environment_binding_history'
|
||||
AND column_name IN ('key_ciphertext','api_key','key')`).Scan(&secretColumns); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if secretColumns != 0 {
|
||||
t.Fatalf("history table has %d key columns", secretColumns)
|
||||
}
|
||||
var leaked int
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM weknora_environment_binding_history
|
||||
WHERE base_url LIKE $1 OR internal_kb_id LIKE $1 OR external_kb_id LIKE $1 OR actor LIKE $1 OR verification LIKE $1`,
|
||||
"%"+testSecret()+"%").Scan(&leaked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if leaked != 0 {
|
||||
t.Fatalf("history contains the key plaintext in %d rows", leaked)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package kbbinding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
const (
|
||||
statusOK = "ok"
|
||||
statusEmpty = "empty"
|
||||
statusKeyInvalid = "key_invalid"
|
||||
statusKeyForbidden = "key_forbidden"
|
||||
statusUnreachable = "unreachable"
|
||||
statusUnsupported = "unsupported"
|
||||
)
|
||||
|
||||
// Catalog validates a draft connection for real and returns one page of the
|
||||
// knowledge bases that key can read. It never writes anything and never echoes
|
||||
// the key.
|
||||
func (s *Store) Catalog(ctx context.Context, env string, input CatalogInput) (Catalog, error) {
|
||||
if !ValidEnvironment(env) {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
page, pageSize := input.Page, input.PageSize
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found)
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
client, err := s.client(baseURL, key, env)
|
||||
if err != nil {
|
||||
return Catalog{}, ErrInvalid
|
||||
}
|
||||
result, err := client.ListKnowledgeBasesPage(ctx, page, pageSize)
|
||||
if err != nil {
|
||||
return catalogFailure(err), nil
|
||||
}
|
||||
options := make([]Option, 0, len(result.Items))
|
||||
for _, base := range result.Items {
|
||||
options = append(options, Option{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount})
|
||||
}
|
||||
status := statusOK
|
||||
message := fmt.Sprintf("已读取 %d 个知识库", result.Total)
|
||||
if result.Total == 0 {
|
||||
status = statusEmpty
|
||||
message = "连接可用,但这个实例还没有可读的知识库"
|
||||
}
|
||||
return Catalog{Status: status, Message: message, Page: page, PageSize: pageSize, Total: result.Total, Options: options}, nil
|
||||
}
|
||||
|
||||
// catalogFailure turns a transport/permission failure into a distinguishable
|
||||
// answer: "empty" must never be shown for "could not ask".
|
||||
func catalogFailure(err error) Catalog {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
switch httpErr.StatusCode {
|
||||
case http.StatusUnauthorized:
|
||||
return Catalog{Status: statusKeyInvalid, Message: "密钥无效:该实例拒绝了这把 API Key(401)"}
|
||||
case http.StatusForbidden:
|
||||
return Catalog{Status: statusKeyForbidden, Message: "密钥无权限读取知识库列表(403)"}
|
||||
case http.StatusNotFound:
|
||||
return Catalog{Status: statusUnsupported, Message: "该地址没有知识库列表接口(HTTP 404):确认填的是 WeKnora 服务地址"}
|
||||
default:
|
||||
return Catalog{Status: statusUnreachable, Message: fmt.Sprintf("实例返回 HTTP %d,无法确认连接", httpErr.StatusCode)}
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return Catalog{Status: statusUnreachable, Message: "连接超时:检查地址、网络与防火墙"}
|
||||
}
|
||||
return Catalog{Status: statusUnreachable, Message: "服务不可达:检查地址、网络与证书"}
|
||||
}
|
||||
|
||||
// Save writes the environment's connection and both bindings in ONE
|
||||
// transaction. The candidate instance is asked first; nothing is written when
|
||||
// either selected base does not belong to it. A stale base_revision returns
|
||||
// ErrConflict and leaves the previous binding untouched.
|
||||
func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor string, now time.Time) (View, error) {
|
||||
if !ValidEnvironment(env) || strings.TrimSpace(actor) == "" || now.IsZero() {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
internal := strings.TrimSpace(input.InternalKBID)
|
||||
external := strings.TrimSpace(input.ExternalKBID)
|
||||
if baseURL == "" || baseURL != input.BaseURL || len(baseURL) > 300 ||
|
||||
internal != input.InternalKBID || external != input.ExternalKBID ||
|
||||
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
// 留空 = 取消该方向绑定:测试侧回退到部署默认库,生产侧回退到「同 ID 语义」,
|
||||
// 响应里会写明回退到哪(InternalFallback / ExternalFallback)。
|
||||
if internal != "" && internal == external {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
saved, found, err := s.load(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
key, err := s.keyFor(ctx, env, input.KeyAction, baseURL, input.APIKey, saved, found)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
selected := map[string]selectedBase{}
|
||||
cleared := key == "" && input.KeyAction == "clear"
|
||||
if !cleared {
|
||||
client, clientErr := s.client(baseURL, key, env)
|
||||
if clientErr != nil {
|
||||
return View{}, ErrInvalid
|
||||
}
|
||||
selected, err = s.verifySelection(ctx, client, internal, external)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
}
|
||||
revision := saved.Revision + 1
|
||||
if !found {
|
||||
revision = 1
|
||||
}
|
||||
sealed := []byte{}
|
||||
if !cleared {
|
||||
box := s.loadBox()
|
||||
if box == nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
sealed, err = box.Seal([]byte(key), keyAAD(env, revision))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
}
|
||||
verification := "verified"
|
||||
if cleared {
|
||||
verification = "not_configured"
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,42))`, "weknora-binding:"+env); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
locked, lockedFound, err := scanStored(tx.QueryRow(ctx, `SELECT `+bindingColumns+` FROM weknora_environment_bindings WHERE environment=$1 FOR UPDATE`, env))
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
lockedRevision := int64(0)
|
||||
if lockedFound {
|
||||
lockedRevision = locked.Revision
|
||||
}
|
||||
if lockedRevision != input.BaseRevision {
|
||||
return View{}, ErrConflict
|
||||
}
|
||||
// 清除密钥只清这一侧的凭据:名称、库 ID、绑定都保留。verified 分支里名称
|
||||
// 来自候选实例的实时读取;clear 不访问实例,所以名称必须取锁定行的旧值,
|
||||
// 否则 upsert 会用空串覆盖掉表里已有的 internal_kb_name / external_kb_name,
|
||||
// 页面只能回落显示短 ID。只在 ID 未变时沿用,避免「同时改指向又清密钥」把
|
||||
// 旧库名贴到新库上。
|
||||
internalName := selected[internal].Name
|
||||
externalName := selected[external].Name
|
||||
if cleared && lockedFound {
|
||||
if internal == locked.InternalKBID {
|
||||
internalName = locked.InternalKBName
|
||||
}
|
||||
if external == locked.ExternalKBID {
|
||||
externalName = locked.ExternalKBName
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO weknora_environment_bindings(
|
||||
environment,revision,base_url,key_ciphertext,internal_kb_id,external_kb_id,
|
||||
internal_kb_name,external_kb_name,verification,checked_at,updated_by,updated_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$10)
|
||||
ON CONFLICT(environment) DO UPDATE SET
|
||||
revision=EXCLUDED.revision,base_url=EXCLUDED.base_url,key_ciphertext=EXCLUDED.key_ciphertext,
|
||||
internal_kb_id=EXCLUDED.internal_kb_id,external_kb_id=EXCLUDED.external_kb_id,
|
||||
internal_kb_name=EXCLUDED.internal_kb_name,external_kb_name=EXCLUDED.external_kb_name,
|
||||
verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at,
|
||||
updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
|
||||
env, revision, baseURL, sealed, internal, external, internalName, externalName, verification, now.UTC(), actor); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO weknora_environment_binding_history(
|
||||
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at,
|
||||
source_address,source_origin)
|
||||
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
|
||||
}
|
||||
replan := postgresstore.RoutingBindingReplanResult{}
|
||||
if env == EnvTest {
|
||||
// 只搬「上一次生效目标」下的待入库:路由行没有值的一侧由部署默认绑定
|
||||
// 补齐(与 effectiveRoutingTargets 同一口径);两边都空就不要猜。
|
||||
previous := postgresstore.EffectiveKBIDs{}
|
||||
rowErr := tx.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active' FOR UPDATE`).
|
||||
Scan(&previous.Internal, &previous.External)
|
||||
if rowErr != nil && !errors.Is(rowErr, pgx.ErrNoRows) {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if (previous.Internal == "" || previous.External == "") && s.options.LegacyBinding != nil {
|
||||
legacyInternal, legacyExternal, legacyErr := s.options.LegacyBinding(ctx, EnvTest)
|
||||
if legacyErr != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
if previous.Internal == "" {
|
||||
previous.Internal = legacyInternal
|
||||
}
|
||||
if previous.External == "" {
|
||||
previous.External = legacyExternal
|
||||
}
|
||||
}
|
||||
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, previous,
|
||||
postgresstore.EffectiveKBIDs{Internal: internal, External: external}, now.UTC())
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
} else {
|
||||
// 生产页只改「文档级发布」的目标映射;整库发布目标仍由部署配置决定,
|
||||
// 本保存不写它。同时冻结候选实例地址与租户,执行器写入前必须与自己的
|
||||
// 目标一致;执行已开始的项目标不会被重排改写。
|
||||
var previous postgresstore.EffectiveKBIDs
|
||||
var priorInternalTenant, priorExternalTenant uint64
|
||||
rowErr := tx.QueryRow(ctx, `
|
||||
SELECT internal_kb_id,external_kb_id,internal_tenant_id,external_tenant_id
|
||||
FROM production_kb_bindings WHERE id='active' FOR UPDATE`).
|
||||
Scan(&previous.Internal, &previous.External, &priorInternalTenant, &priorExternalTenant)
|
||||
if rowErr != nil && !errors.Is(rowErr, pgx.ErrNoRows) {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
internalTenant := selected[internal].TenantID
|
||||
externalTenant := selected[external].TenantID
|
||||
if cleared {
|
||||
// 同一条「只清密钥」口径:clear 不访问实例,租户不能被写成 0,
|
||||
// 否则执行器的实例一致性检查会把「只是没密钥」误判成换了实例。
|
||||
// 仍然只在 ID 未变时沿用。
|
||||
if internal == previous.Internal {
|
||||
internalTenant = priorInternalTenant
|
||||
}
|
||||
if external == previous.External {
|
||||
externalTenant = priorExternalTenant
|
||||
}
|
||||
}
|
||||
if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx,
|
||||
internal, external, baseURL, baseURL,
|
||||
internalTenant, externalTenant, actor, now.UTC()); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
// 生产页保存也要让「还没上传、原本瞄准旧生产库」的待入库项改指向新库;
|
||||
// 只在国内/国外旧目标存在时搬,空的一侧是「同 ID 语义」,不能猜。
|
||||
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, previous,
|
||||
postgresstore.EffectiveKBIDs{Internal: internal, External: external}, now.UTC())
|
||||
if err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return View{}, ErrStorage
|
||||
}
|
||||
view, err := s.Get(ctx, env)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view.Replanned = replan.Replanned
|
||||
view.RetiredDuplicates = replan.RetiredDuplicates
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// verifySelection proves both chosen bases belong to THIS candidate instance by
|
||||
// reading them with the draft credential. An empty selection still probes the
|
||||
// list endpoint, so a save cannot store a connection nobody verified.
|
||||
type selectedBase struct {
|
||||
Name string
|
||||
TenantID uint64
|
||||
}
|
||||
|
||||
func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]selectedBase, error) {
|
||||
selected := map[string]selectedBase{}
|
||||
if internal == "" && external == "" {
|
||||
if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil {
|
||||
return nil, selectionError(err, "无法确认候选连接")
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
for _, id := range []string{internal, external} {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
base, err := client.GetKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
return nil, selectionError(err, fmt.Sprintf("知识库 %s 不属于该连接实例或不可读", shortID(id)))
|
||||
}
|
||||
if base.ID != id {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
selected[id] = selectedBase{Name: base.Name, TenantID: base.TenantID}
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
func selectionError(err error, message string) error {
|
||||
var httpErr *weknora.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
if httpErr.StatusCode == http.StatusUnauthorized || httpErr.StatusCode == http.StatusForbidden {
|
||||
return fmt.Errorf("%w:密钥被实例拒绝(HTTP %d)", ErrRejected, httpErr.StatusCode)
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w:连接超时", ErrUnreachable)
|
||||
}
|
||||
if _, ok := err.(*weknora.HTTPError); ok {
|
||||
return fmt.Errorf("%w:%s", ErrRejected, message)
|
||||
}
|
||||
if errors.Is(err, ErrInvalid) || errors.Is(err, ErrRejected) || errors.Is(err, ErrUnreachable) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w:%s", ErrUnreachable, message)
|
||||
}
|
||||
|
||||
func validBaseID(value string) bool {
|
||||
return !strings.ContainsAny(value, "\x00\r\n\t /?#\\")
|
||||
}
|
||||
|
||||
func shortID(value string) string {
|
||||
if len(value) > 8 {
|
||||
return value[:8]
|
||||
}
|
||||
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 表)。
|
||||
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 的部件键一致)。
|
||||
type PartRequirement struct {
|
||||
Kind string
|
||||
@@ -41,6 +62,9 @@ type Profile struct {
|
||||
ReviewedTriggers []string
|
||||
RequiredParts []PartRequirement
|
||||
OptionalParts []PartRequirement
|
||||
// RelatedTables 是该版本全部知识域关联表的归类(copied/derived/excluded)。
|
||||
// 漏表门禁按它判定:未归类且有本库数据的表一律拒绝。
|
||||
RelatedTables map[string]RelatedTable
|
||||
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
|
||||
// 不允许回退成空串去匹配任何索引。
|
||||
IndexContractSource string
|
||||
@@ -93,6 +117,9 @@ var profiles = map[int]Profile{
|
||||
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
|
||||
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
|
||||
"wiki_page_issues",
|
||||
// 编辑历史随内容搬运(D1)。放在父表之后:importRows 按本序插入、
|
||||
// 倒序删除,两张历史表因此在 chunks/wiki_pages 之后写、在它们之前删。
|
||||
"chunk_revisions", "wiki_page_revisions",
|
||||
},
|
||||
// 0.9.0 删掉了 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_folders": {"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{
|
||||
{"database", "knowledges"}, {"database", "chunks"},
|
||||
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
|
||||
{"database", "resources"}, {"database", "resource_bindings"},
|
||||
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"},
|
||||
{"database", "chunk_revisions"}, {"wiki", "wiki_page_revisions"},
|
||||
{"index", "chunks"},
|
||||
},
|
||||
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。未知版本一律失败:版本号是"选哪份声明"的索引,
|
||||
// 不是"能不能放行"的依据,所以绝不返回默认 profile。
|
||||
func For(version int) (Profile, error) {
|
||||
profile, ok := profiles[version]
|
||||
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
|
||||
}
|
||||
|
||||
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
|
||||
func Supported() []int {
|
||||
return []int{LegacyVersion, V090Version}
|
||||
return []int{LegacyVersion, V090Version, V091Version}
|
||||
}
|
||||
|
||||
// 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"`
|
||||
Rows []WriteSetRow `json:"rows"`
|
||||
Universe map[string]TableFingerprint `json:"universe"`
|
||||
// Warnings 是放行但需要留痕的契约警告(例如未分类但为空的表)。omitempty:
|
||||
// 空警告不改变历史计划的规范字节/摘要,旧记录读回仍然一致。
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
|
||||
// 记录被改一个字节就对不上。
|
||||
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,
|
||||
// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。
|
||||
// 但必须有编辑历史两表;0.7.1 没有两表、缺 wiki_log_entries 就是残包。
|
||||
func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
||||
part := func(kind, name string) Part {
|
||||
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", "resource_bindings"), part("database", "knowledge_tags"),
|
||||
part("database", "knowledge_tag_relations"),
|
||||
part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"),
|
||||
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 {
|
||||
return Manifest{
|
||||
ValidationPolicy: ArtifactAcceptancePolicy,
|
||||
@@ -36,23 +38,30 @@ func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", parts)); err != nil {
|
||||
t.Fatalf("0.9.0 manifest without wiki_log_entries must be complete: %v", err)
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", v090Parts)); err != nil {
|
||||
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)
|
||||
}
|
||||
withLog := append(append([]Part{}, parts...), part("wiki", "wiki_log_entries"))
|
||||
if _, err := encodeManifest(manifest(74, "v0.7.1", withLog)); err != nil {
|
||||
legacyWithLog := append(append([]Part{}, legacyParts...), part("wiki", "wiki_log_entries"))
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// P10: every configured dependency reports Liveness ("process reachable") and
|
||||
@@ -200,10 +201,14 @@ func (provider *RealProvider) productionWeKnoraProbe(ctx context.Context, now ti
|
||||
func (provider *RealProvider) httpProbeOutcome(ctx context.Context, baseURL string, now time.Time) ProbeOutcome {
|
||||
parsed, err := url.Parse(baseURL)
|
||||
outcome := ProbeOutcome{ObservedAt: now}
|
||||
if err != nil || parsed.Scheme != "http" && parsed.Scheme != "https" || parsed.Host == "" {
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
||||
outcome.Reachability = errors.New("探测配置无效")
|
||||
return outcome
|
||||
}
|
||||
if !weknora.HTTPAllowed(baseURL, weknora.HTTPPolicy{AllowPrivateHTTP: provider.allowPrivateHTTP}) {
|
||||
outcome.Reachability = errors.New("探测配置无效:该地址不被允许(https 或已放行的私网/回环 http)")
|
||||
return outcome
|
||||
}
|
||||
parsed.Path = strings.TrimSuffix(parsed.Path, "/") + "/health"
|
||||
parsed.RawQuery, parsed.Fragment = "", ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
|
||||
@@ -50,6 +50,10 @@ type RealProviderConfig struct {
|
||||
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
|
||||
// as alive (P10).
|
||||
WorkerStaleAfter time.Duration
|
||||
// AllowPrivateHTTP lets the console probe a same-LAN http endpoint — the
|
||||
// same judgement the WeKnora client uses, so a card can never say 「可达」
|
||||
// while the client refuses that URL.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
type RealProvider struct {
|
||||
@@ -63,6 +67,7 @@ type RealProvider struct {
|
||||
productionWeKnoraResolver func(ctx context.Context) string
|
||||
weknoraReadiness func(ctx context.Context) (string, error)
|
||||
workerStaleAfter time.Duration
|
||||
allowPrivateHTTP bool
|
||||
health *healthTracker
|
||||
}
|
||||
|
||||
@@ -103,7 +108,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
|
||||
if stale <= 0 {
|
||||
stale = time.Minute
|
||||
}
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
|
||||
}
|
||||
|
||||
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
|
||||
@@ -114,7 +119,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
overview.Health = provider.Services(ctx)
|
||||
overview.Services = append(overview.Services,
|
||||
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.productionWeKnoraBaseURL, now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.resolveProductionWeKnoraBaseURL(ctx), now),
|
||||
governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now),
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- 回滚只删本迁移新增的审计与配置表;旧部署的 file 凭据/绑定表不受影响。
|
||||
DROP TABLE IF EXISTS weknora_environment_binding_history;
|
||||
DROP TABLE IF EXISTS weknora_environment_bindings;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- 「知识库绑定」按环境保存一组连接与内外库绑定:测试与生产各自一行,
|
||||
-- 一次保存同时写连接(地址 + 加密密钥)与对内/对外目标。没有行时消费者
|
||||
-- 继续使用旧部署的文件凭据/默认绑定,所以升级不需要回填。
|
||||
--
|
||||
-- key_ciphertext 只存密文;主密钥在独立文件里(WEKNORA_BINDING_MASTER_KEY_FILE),
|
||||
-- 不进库、不进备份、不经页面回显。verification 记录最近一次真实列库/选库核验。
|
||||
CREATE TABLE weknora_environment_bindings (
|
||||
environment VARCHAR(16) PRIMARY KEY CHECK (environment IN ('test','production')),
|
||||
revision BIGINT NOT NULL CHECK (revision > 0),
|
||||
base_url TEXT NOT NULL DEFAULT '',
|
||||
key_ciphertext BYTEA NOT NULL DEFAULT ''::bytea,
|
||||
internal_kb_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
external_kb_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
internal_kb_name TEXT NOT NULL DEFAULT '',
|
||||
external_kb_name TEXT NOT NULL DEFAULT '',
|
||||
verification TEXT NOT NULL DEFAULT 'not_configured'
|
||||
CHECK (verification IN ('not_configured','verified','empty','unreachable','rejected')),
|
||||
checked_at TIMESTAMPTZ,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- 修订历史只记录“是否配置了密钥”,绝不复制密文或明文,供审计回答谁在何时
|
||||
-- 把哪个环境指向了哪里。
|
||||
CREATE TABLE weknora_environment_binding_history (
|
||||
environment VARCHAR(16) NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
base_url TEXT NOT NULL,
|
||||
key_configured BOOLEAN NOT NULL,
|
||||
internal_kb_id VARCHAR(128) NOT NULL,
|
||||
external_kb_id VARCHAR(128) NOT NULL,
|
||||
verification TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (environment, revision)
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
ALTER TABLE test_publications
|
||||
DROP COLUMN IF EXISTS test_instance_tenant,
|
||||
DROP COLUMN IF EXISTS test_instance_url;
|
||||
|
||||
ALTER TABLE release_item_executions
|
||||
DROP COLUMN IF EXISTS target_tenant_id,
|
||||
DROP COLUMN IF EXISTS target_instance_url;
|
||||
|
||||
ALTER TABLE production_kb_bindings
|
||||
DROP COLUMN IF EXISTS external_tenant_id,
|
||||
DROP COLUMN IF EXISTS internal_tenant_id,
|
||||
DROP COLUMN IF EXISTS external_instance_url,
|
||||
DROP COLUMN IF EXISTS internal_instance_url;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- 实例身份约束:网页(kbbinding)在实例 A 上列库/选库,而文档发布执行器可能
|
||||
-- 连的是实例 B。同名/同 ID 的知识库在克隆实例里完全可能存在,所以 ID 本身
|
||||
-- 不能证明“写的是网页看到的那个实例”。这里把候选连接地址与租户随绑定冻结到
|
||||
-- 每个发布项,执行器在写入前用自己的目标地址/租户核对;不一致即失败关闭。
|
||||
--
|
||||
-- 同时给测试入库的发布项记录“对象实际写入的测试实例地址/租户”:
|
||||
-- 改绑实例或租户后,旧对象不能在克隆实例上继续轮询/验收/移除。
|
||||
ALTER TABLE production_kb_bindings
|
||||
ADD COLUMN IF NOT EXISTS internal_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS external_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS internal_tenant_id BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS external_tenant_id BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE release_item_executions
|
||||
ADD COLUMN IF NOT EXISTS target_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS target_tenant_id BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE test_publications
|
||||
ADD COLUMN IF NOT EXISTS test_instance_url TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS test_instance_tenant BIGINT NOT NULL DEFAULT 0;
|
||||
@@ -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,30 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 80 {
|
||||
t.Fatalf("migration count = %d, want 80", len(migrations))
|
||||
if len(migrations) != 83 {
|
||||
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 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
|
||||
// 实际实例身份;克隆实例同名/同 ID 不能冒充。
|
||||
if identity := migrations[81]; identity.Version != 82 ||
|
||||
!strings.Contains(identity.UpSQL, "target_instance_url") ||
|
||||
!strings.Contains(identity.UpSQL, "test_instance_url") ||
|
||||
!strings.Contains(identity.UpSQL, "internal_tenant_id") {
|
||||
t.Fatalf("migration 82 = %#v", identity)
|
||||
}
|
||||
// 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。
|
||||
if binding := migrations[80]; binding.Version != 81 ||
|
||||
!strings.Contains(binding.UpSQL, "weknora_environment_bindings") ||
|
||||
!strings.Contains(binding.UpSQL, "key_ciphertext") ||
|
||||
!strings.Contains(binding.DownSQL, "DROP TABLE IF EXISTS weknora_environment_bindings") {
|
||||
t.Fatalf("migration 81 = %#v", binding)
|
||||
}
|
||||
// 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥,
|
||||
// 证据按 target_id 落库(换目标旧证据自动失效)。
|
||||
|
||||
@@ -39,14 +39,48 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern
|
||||
if now.IsZero() {
|
||||
return errors.New("production binding save requires a timestamp")
|
||||
}
|
||||
if _, err := s.db.Exec(ctx, `
|
||||
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
|
||||
VALUES('active',$1,$2,$3,$4)
|
||||
// 旧入口没有实例身份可写:显式清空身份列,执行器随后会失败关闭,
|
||||
// 而不是沿用上一条(可能属于另一个实例的)地址/租户。
|
||||
if _, err := s.db.Exec(ctx, productionBindingIdentityUpsertSQL,
|
||||
internalID, externalID, updatedBy, now, "", "", 0, 0); err != nil {
|
||||
return errors.New("save production kb bindings")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// productionBindingIdentityUpsertSQL freezes the instance identity the console
|
||||
// verified each side on. An empty URL keeps the legacy same-id behaviour for
|
||||
// old callers; the executor then cannot prove the instance and refuses a mapped
|
||||
// write instead of guessing.
|
||||
const productionBindingIdentityUpsertSQL = `
|
||||
INSERT INTO production_kb_bindings(
|
||||
id,internal_kb_id,external_kb_id,updated_by,updated_at,
|
||||
internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id)
|
||||
VALUES('active',$1,$2,$3,$4,$5,$6,$7,$8)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
internal_kb_id=EXCLUDED.internal_kb_id,
|
||||
external_kb_id=EXCLUDED.external_kb_id,
|
||||
updated_by=EXCLUDED.updated_by,
|
||||
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
|
||||
updated_at=EXCLUDED.updated_at,
|
||||
internal_instance_url=EXCLUDED.internal_instance_url,
|
||||
external_instance_url=EXCLUDED.external_instance_url,
|
||||
internal_tenant_id=EXCLUDED.internal_tenant_id,
|
||||
external_tenant_id=EXCLUDED.external_tenant_id`
|
||||
|
||||
// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save
|
||||
// update the same row inside its own transaction, so connection and bindings
|
||||
// cannot be half-written.
|
||||
func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
|
||||
return SaveProductionKBBindingsWithIdentityTx(ctx, tx, internalID, externalID, "", "", 0, 0, updatedBy, now)
|
||||
}
|
||||
|
||||
// SaveProductionKBBindingsWithIdentityTx is used by the environment-scoped
|
||||
// 「知识库绑定」save: it stores which instance/tenant each side was verified on,
|
||||
// so the release executor can refuse a cloned instance with the same base id.
|
||||
func SaveProductionKBBindingsWithIdentityTx(ctx context.Context, tx pgx.Tx, internalID, externalID, internalURL, externalURL string, internalTenant, externalTenant uint64, updatedBy string, now time.Time) error {
|
||||
if _, err := tx.Exec(ctx, productionBindingIdentityUpsertSQL,
|
||||
internalID, externalID, updatedBy, now,
|
||||
internalURL, externalURL, internalTenant, externalTenant); err != nil {
|
||||
return errors.New("save production kb bindings")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -11,19 +11,22 @@ import (
|
||||
)
|
||||
|
||||
type PublicationForRemoval struct {
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
RetrievalState governance.RetrievalState
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
RetrievalState governance.RetrievalState
|
||||
}
|
||||
|
||||
func (s *Store) LoadPublicationForRemoval(ctx context.Context, publicationID string) (PublicationForRemoval, error) {
|
||||
var candidate PublicationForRemoval
|
||||
var retrievalState string
|
||||
err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,retrieval_state
|
||||
err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,test_instance_url,test_instance_tenant,retrieval_state
|
||||
FROM test_publications
|
||||
WHERE id=$1 AND knowledge_id<>'' AND retrieval_state='disabling'`, publicationID).Scan(
|
||||
&candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID, &retrievalState,
|
||||
&candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID,
|
||||
&candidate.TestInstanceURL, &candidate.TestInstanceTenant, &retrievalState,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return PublicationForRemoval{}, ErrPublicationStateConflict
|
||||
|
||||
@@ -75,13 +75,32 @@ execution_gate AS (
|
||||
WHEN 'internal' THEN binding.internal_kb_id
|
||||
WHEN 'external' THEN binding.external_kb_id
|
||||
END, ''),
|
||||
publication.test_kb_id) AS target_kb_id
|
||||
publication.test_kb_id) AS target_kb_id,
|
||||
-- 身份必须与 target_kb_id 来自同一来源:重试/回滚沿用的旧目标若
|
||||
-- 没有身份(迁移前),不能拿当前绑定去补,否则会把旧项写到新实例;
|
||||
-- 这种情况留空,由执行器失败关闭。
|
||||
CASE
|
||||
WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
|
||||
THEN COALESCE(prior_item.target_instance_url, '')
|
||||
ELSE COALESCE(NULLIF(CASE publication.target_scope
|
||||
WHEN 'internal' THEN binding.internal_instance_url
|
||||
WHEN 'external' THEN binding.external_instance_url
|
||||
END, ''), '')
|
||||
END AS target_instance_url,
|
||||
CASE
|
||||
WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
|
||||
THEN COALESCE(prior_item.target_tenant_id, 0)
|
||||
ELSE COALESCE(NULLIF(CASE publication.target_scope
|
||||
WHEN 'internal' THEN binding.internal_tenant_id
|
||||
WHEN 'external' THEN binding.external_tenant_id
|
||||
END, 0), 0)
|
||||
END AS target_tenant_id
|
||||
FROM started
|
||||
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
|
||||
JOIN test_publications AS publication ON publication.id = item.publication_id
|
||||
LEFT JOIN production_kb_bindings AS binding ON binding.id = 'active'
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT candidate.target_knowledge_base_id
|
||||
SELECT candidate.target_knowledge_base_id, candidate.target_instance_url, candidate.target_tenant_id
|
||||
FROM release_item_executions AS candidate
|
||||
JOIN release_executions AS candidate_execution ON candidate_execution.id = candidate.release_execution_id
|
||||
WHERE candidate.publication_id = item.publication_id
|
||||
@@ -94,11 +113,14 @@ execution_gate AS (
|
||||
) AS prior_item ON TRUE
|
||||
), seeded AS (
|
||||
INSERT INTO release_item_executions (
|
||||
id, release_execution_id, publication_id, action, state, created_at, updated_at, target_knowledge_base_id
|
||||
id, release_execution_id, publication_id, action, state, created_at, updated_at,
|
||||
target_knowledge_base_id, target_instance_url, target_tenant_id
|
||||
)
|
||||
SELECT 'ri-' || SUBSTR(MD5(started.id || ':' || item.publication_id), 1, 32),
|
||||
started.id, item.publication_id, item.action, 'pending', $4::TIMESTAMPTZ, $4::TIMESTAMPTZ,
|
||||
COALESCE(target_base.target_kb_id, '')
|
||||
COALESCE(target_base.target_kb_id, ''),
|
||||
COALESCE(target_base.target_instance_url, ''),
|
||||
COALESCE(target_base.target_tenant_id, 0)
|
||||
FROM started
|
||||
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
|
||||
LEFT JOIN target_base ON target_base.publication_id = item.publication_id
|
||||
@@ -129,6 +151,8 @@ execution_gate AS (
|
||||
item.review_id AS release_revision,
|
||||
publication.test_kb_id,
|
||||
COALESCE(target_base.target_kb_id, '') AS target_kb_id,
|
||||
COALESCE(target_base.target_instance_url, '') AS target_instance_url,
|
||||
COALESCE(target_base.target_tenant_id, 0) AS target_tenant_id,
|
||||
publication.knowledge_id,
|
||||
item.decided_visibility,
|
||||
COALESCE(previous.production_revision, '') AS previous_production_revision
|
||||
@@ -180,6 +204,8 @@ SELECT COUNT(DISTINCT started.id)::INTEGER,
|
||||
'release_revision', plan.release_revision,
|
||||
'test_knowledge_base_id', plan.test_kb_id,
|
||||
'target_knowledge_base_id', plan.target_kb_id,
|
||||
'target_instance_url', plan.target_instance_url,
|
||||
'target_tenant_id', plan.target_tenant_id,
|
||||
'knowledge_id', plan.knowledge_id,
|
||||
'decided_visibility', plan.decided_visibility,
|
||||
'previous_production_revision', plan.previous_production_revision
|
||||
@@ -307,7 +333,8 @@ func (s *Store) StartExecution(ctx context.Context, request releaseworkflow.Star
|
||||
if !validShortID(item.PublicationID) || !validShortID(item.SourceItemVersionID) ||
|
||||
!validRemoteIdentifier(item.TestKnowledgeBaseID) || !validRemoteIdentifier(item.TargetKnowledgeBaseID) || !validRemoteIdentifier(item.KnowledgeID) ||
|
||||
(item.DecidedVisibility != governance.VisibilityInternal && item.DecidedVisibility != governance.VisibilityExternal) ||
|
||||
len(item.PreviousProductionRevision) > 128 {
|
||||
len(item.PreviousProductionRevision) > 128 || len(item.TargetInstanceURL) > 300 ||
|
||||
strings.ContainsAny(item.TargetInstanceURL, " \r\n\x00") {
|
||||
return nil, errors.New("invalid release execution plan")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) {
|
||||
payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
|
||||
payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","target_instance_url":"https://instance-a.weknora.example","target_tenant_id":10000,"knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
|
||||
db := &recordingDB{row: startExecutionRow{executionCount: 1, payload: []byte(payload)}}
|
||||
items, err := NewStore(db).StartExecution(context.Background(), releaseworkflow.StartExecutionRequest{
|
||||
ExecutionID: "rx-safe", JobID: "job-safe", Operation: "publish", Now: time.Now(),
|
||||
@@ -24,7 +24,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
|
||||
if len(items) != 1 || items[0].PublicationID != "tp-safe" || items[0].Action != "delete" || items[0].KnowledgeID != "knowledge-safe" || items[0].PreviousProductionRevision != "prod-old" {
|
||||
t.Fatalf("items=%#v", items)
|
||||
}
|
||||
if items[0].TargetBase() != "prod-kb" {
|
||||
if items[0].TargetBase() != "prod-kb" || items[0].TargetInstanceURL != "https://instance-a.weknora.example" || items[0].TargetTenantID != 10000 {
|
||||
t.Fatalf("target base=%q, want the mapped 源库 → 目标库 target", items[0].TargetBase())
|
||||
}
|
||||
sql := strings.ToLower(db.queryRowSQL)
|
||||
@@ -39,6 +39,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
|
||||
"release_delete_ready", "item.action = 'delete'", "execution_gate.valid_items = execution_gate.item_count",
|
||||
// the 源库 → 目标库 mapping is resolved into the plan and frozen per item
|
||||
"production_kb_bindings", "target_knowledge_base_id", "target_base.target_kb_id",
|
||||
"target_instance_url", "target_tenant_id", "internal_instance_url", "internal_tenant_id",
|
||||
} {
|
||||
if !strings.Contains(sql, required) {
|
||||
t.Fatalf("start execution SQL missing %q", required)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
releaseworkflow "knowledge-governance/internal/workflows/release"
|
||||
)
|
||||
|
||||
// The console verified the production binding on instance A. The release plan
|
||||
// must freeze that instance identity with each item; the executor later compares
|
||||
// it with its own route target before writing. Same knowledge-base id/tenant on
|
||||
// a cloned instance is not enough.
|
||||
func TestStartReleaseExecutionFreezesTheBindingInstanceIdentity(t *testing.T) {
|
||||
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publicationID := "tp-identity-e2e"
|
||||
insertReviewFixture(t, ctx, pool, 9, publicationID, now)
|
||||
if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{PublicationID: publicationID, Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal, ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(time.Minute)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
batch, err := store.CreateReleaseBatch(ctx, governance.CreateReleaseBatchRequest{Name: "Identity publish", CreatedBy: "engineer-1", PublicationIDs: []string{publicationID}, Now: now.Add(2 * time.Minute)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.SealReleaseBatch(ctx, governance.SealReleaseBatchRequest{BatchID: batch.ID, SealedBy: "engineer-2", Now: now.Add(3 * time.Minute)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
execution, err := store.AuthorizeReleaseBatch(ctx, governance.AuthorizeReleaseBatchRequest{BatchID: batch.ID, AuthorizedBy: "release-owner", AuthorizationCode: "production_release_authorized", Now: now.Add(4 * time.Minute)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveProductionKBBindingsWithIdentityTx(ctx, tx, "test-kb", "test-kb", "https://instance-a.weknora.example", "https://instance-a.weknora.example", 10000, 10000, "admin", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plan, err := store.StartExecution(ctx, releaseworkflow.StartExecutionRequest{ExecutionID: execution.ID, JobID: execution.JobID, Operation: governance.ReleaseOperationPublish, Now: now.Add(5 * time.Minute)})
|
||||
if err != nil || len(plan) != 1 {
|
||||
t.Fatalf("plan=%#v error=%v", plan, err)
|
||||
}
|
||||
if plan[0].TargetKnowledgeBaseID != "test-kb" || plan[0].TargetInstanceURL != "https://instance-a.weknora.example" || plan[0].TargetTenantID != 10000 {
|
||||
t.Fatalf("plan identity = %s / %s / %d", plan[0].TargetKnowledgeBaseID, plan[0].TargetInstanceURL, plan[0].TargetTenantID)
|
||||
}
|
||||
}
|
||||
@@ -60,14 +60,33 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
return nil
|
||||
}
|
||||
|
||||
// replanRetireDuplicatesSQL retires a pending publication whose twin for the
|
||||
// new knowledge base already exists — the unique key is
|
||||
// (source_item_version_id, test_kb_id), so the row cannot simply be moved.
|
||||
// EffectiveKBIDs is the pair of knowledge base ids consumers actually route to:
|
||||
// the UI binding where it is set, the deployment default otherwise. A save must
|
||||
// name both the pair it replaces and the pair it establishes, so re-planning
|
||||
// only moves work that was aimed at THIS environment's previous target.
|
||||
type EffectiveKBIDs struct {
|
||||
Internal string
|
||||
External string
|
||||
}
|
||||
|
||||
// RoutingBindingSave is one binding change: the ids to persist plus the
|
||||
// effective routing before and after it.
|
||||
type RoutingBindingSave struct {
|
||||
InternalID string
|
||||
ExternalID string
|
||||
Previous EffectiveKBIDs
|
||||
Effective EffectiveKBIDs
|
||||
UpdatedBy string
|
||||
}
|
||||
|
||||
// replanRetireDuplicatesSQL retires a pending publication aimed at the previous
|
||||
// target whose twin for the new knowledge base already exists — the unique key
|
||||
// is (source_item_version_id, test_kb_id), so the row cannot simply be moved.
|
||||
const replanRetireDuplicatesSQL = `
|
||||
UPDATE test_publications stale
|
||||
SET superseded_at = $3, updated_at = $3
|
||||
SET superseded_at = $4, updated_at = $4
|
||||
WHERE stale.superseded_at IS NULL
|
||||
AND stale.test_kb_id <> $1
|
||||
AND stale.test_kb_id = $1
|
||||
AND stale.processing_state = 'planned'
|
||||
AND stale.ingest_state = 'pending'
|
||||
AND stale.knowledge_id = ''
|
||||
@@ -77,7 +96,7 @@ WHERE stale.superseded_at IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM test_publications twin
|
||||
WHERE twin.source_item_version_id = stale.source_item_version_id
|
||||
AND twin.test_kb_id = $1
|
||||
AND twin.test_kb_id = $3
|
||||
AND twin.superseded_at IS NULL)
|
||||
`
|
||||
|
||||
@@ -86,9 +105,9 @@ WHERE stale.superseded_at IS NULL
|
||||
// already in flight keeps its frozen target and stays visible in 待入库.
|
||||
const replanMovePendingSQL = `
|
||||
UPDATE test_publications pending
|
||||
SET test_kb_id = $1, updated_at = $3
|
||||
SET test_kb_id = $3, test_instance_url = '', test_instance_tenant = 0, updated_at = $4
|
||||
WHERE pending.superseded_at IS NULL
|
||||
AND pending.test_kb_id <> $1
|
||||
AND pending.test_kb_id = $1
|
||||
AND pending.processing_state = 'planned'
|
||||
AND pending.ingest_state = 'pending'
|
||||
AND pending.knowledge_id = ''
|
||||
@@ -98,20 +117,20 @@ WHERE pending.superseded_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM test_publications twin
|
||||
WHERE twin.source_item_version_id = pending.source_item_version_id
|
||||
AND twin.test_kb_id = $1
|
||||
AND twin.test_kb_id = $3
|
||||
AND twin.superseded_at IS NULL)
|
||||
`
|
||||
|
||||
// SaveRoutingKBBindingsWithReplan saves the binding and, in the SAME
|
||||
// transaction, re-points 待入库 items that were still waiting for the old
|
||||
// SaveRoutingKBBindingsWithReplan saves the test-side binding and, in the SAME
|
||||
// transaction, re-points 待入库 items that were still waiting for the previous
|
||||
// knowledge base. Without this, changing the binding left every pending
|
||||
// publication aimed at the previous (possibly deleted) KB, and re-marking the
|
||||
// file created a SECOND publication instead of moving the first.
|
||||
//
|
||||
// effectiveInternal/effectiveExternal are the ids the platform actually routes
|
||||
// to (the saved binding, or the deployment default when a side is unbound);
|
||||
// an empty effective id means that scope cannot be routed and is skipped.
|
||||
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (RoutingBindingReplanResult, error) {
|
||||
// save.Previous is the effective pair before the change (stored binding, or the
|
||||
// deployment default where a side was unbound); an empty or unchanged side is
|
||||
// not guessed at.
|
||||
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save RoutingBindingSave, now time.Time) (RoutingBindingReplanResult, error) {
|
||||
var result RoutingBindingReplanResult
|
||||
if now.IsZero() {
|
||||
return result, errors.New("binding replan requires a timestamp")
|
||||
@@ -121,6 +140,22 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
|
||||
return result, fmt.Errorf("begin routing binding save: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err := SaveRoutingKBBindingsTx(ctx, tx, save.InternalID, save.ExternalID, save.UpdatedBy, now); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result, err = ReplanPendingPublicationsTx(ctx, tx, save.Previous, save.Effective, now)
|
||||
if err != nil {
|
||||
return RoutingBindingReplanResult{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return result, fmt.Errorf("commit routing binding save: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveRoutingKBBindingsTx is the binding upsert, shared by the settings page and
|
||||
// the environment-scoped 「知识库绑定」save so the two entries cannot drift.
|
||||
func SaveRoutingKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
|
||||
VALUES('active',$1,$2,$3,$4)
|
||||
@@ -129,28 +164,37 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
external_kb_id=EXCLUDED.external_kb_id,
|
||||
updated_by=EXCLUDED.updated_by,
|
||||
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
|
||||
return result, errors.New("save routing kb bindings")
|
||||
return errors.New("save routing kb bindings")
|
||||
}
|
||||
for _, scope := range []struct{ name, kbID string }{
|
||||
{"internal", effectiveInternal},
|
||||
{"external", effectiveExternal},
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplanPendingPublicationsTx re-points untouched 待入库 rows from the previous
|
||||
// effective targets to the new ones inside the caller's transaction. It only
|
||||
// moves rows that were never uploaded anywhere AND were aimed at the previous
|
||||
// target: that target check is what keeps one environment's save from carrying
|
||||
// off pending work belonging to the other environment (both envs share the
|
||||
// test_publications lane until an item is executed). Anything already in flight
|
||||
// keeps its frozen target.
|
||||
func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
|
||||
var result RoutingBindingReplanResult
|
||||
for _, scope := range []struct{ name, from, to string }{
|
||||
{"internal", previous.Internal, effective.Internal},
|
||||
{"external", previous.External, effective.External},
|
||||
} {
|
||||
if scope.kbID == "" {
|
||||
if scope.from == "" || scope.to == "" || scope.from == scope.to {
|
||||
continue
|
||||
}
|
||||
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.kbID, scope.name, now)
|
||||
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.from, scope.name, scope.to, now)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
|
||||
}
|
||||
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.kbID, scope.name, now)
|
||||
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.from, scope.name, scope.to, now)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("replan pending publications: %w", err)
|
||||
}
|
||||
result.RetiredDuplicates += int(retired.RowsAffected())
|
||||
result.Replanned += int(moved.RowsAffected())
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return result, fmt.Errorf("commit routing binding save: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -33,16 +33,19 @@ INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_ur
|
||||
('item-in','conn-replan','n-in',repeat('b',64),'docs/in.docx','in.docx','document','locator:r1','internal','configured_scope'),
|
||||
('item-ext','conn-replan','n-ext',repeat('b',64),'docs/ext.docx','ext.docx','document','locator:r2','external','configured_scope'),
|
||||
('item-sent','conn-replan','n-sent',repeat('b',64),'docs/sent.docx','sent.docx','document','locator:r3','internal','configured_scope'),
|
||||
('item-prod','conn-replan','n-prod',repeat('b',64),'docs/prod.docx','prod.docx','document','locator:r5','internal','configured_scope'),
|
||||
('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope');
|
||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
||||
('v-in','item-in','locator:r1',NULL,'unknown'),
|
||||
('v-ext','item-ext','locator:r2',NULL,'unknown'),
|
||||
('v-sent','item-sent','locator:r3',NULL,'unknown'),
|
||||
('v-prod','item-prod','locator:r5',NULL,'unknown'),
|
||||
('v-dup','item-dup','locator:r4',NULL,'unknown');
|
||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
||||
('pub-in','v-in','kb-old-internal','planned','pending','internal'),
|
||||
('pub-ext','v-ext','kb-old-external','planned','pending','external'),
|
||||
('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'),
|
||||
('pub-prod','v-prod','p-internal','planned','pending','internal'),
|
||||
('pub-dup-old','v-dup','kb-old-internal','planned','pending','internal'),
|
||||
('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal');
|
||||
INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
||||
@@ -53,12 +56,19 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, time.October, 8, 7, 0, 0, 0, time.UTC)
|
||||
|
||||
result, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
|
||||
result, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
|
||||
InternalID: "kb-new-internal", ExternalID: "kb-new-external",
|
||||
Previous: EffectiveKBIDs{Internal: "kb-old-internal", External: "kb-old-external"},
|
||||
Effective: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||
UpdatedBy: "tester",
|
||||
}, now)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
|
||||
}
|
||||
// pub-in and pub-ext move; pub-sent already has an upload job (untouched);
|
||||
// pub-dup-old already has a twin for the new KB so it is retired instead.
|
||||
// pub-dup-old already has a twin for the new KB so it is retired instead;
|
||||
// pub-prod aims at the production binding and must not be carried off by a
|
||||
// test-side save.
|
||||
if result.Replanned != 2 || result.RetiredDuplicates != 1 {
|
||||
t.Fatalf("replan result = %#v, want 2 moved / 1 retired", result)
|
||||
}
|
||||
@@ -95,9 +105,17 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
||||
if states["pub-dup-old"].kb != "kb-old-internal" || !states["pub-dup-old"].superseded {
|
||||
t.Fatalf("the duplicate stale row must be retired: %#v", states["pub-dup-old"])
|
||||
}
|
||||
if states["pub-prod"].kb != "p-internal" || states["pub-prod"].superseded {
|
||||
t.Fatalf("a pending item aimed at another environment's target must stay put: %#v", states["pub-prod"])
|
||||
}
|
||||
|
||||
// Re-saving the same binding is a no-op: nothing left to move or retire.
|
||||
again, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
|
||||
again, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
|
||||
InternalID: "kb-new-internal", ExternalID: "kb-new-external",
|
||||
Previous: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||
Effective: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||
UpdatedBy: "tester",
|
||||
}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -29,22 +29,27 @@ type PublicationForUpload struct {
|
||||
SourceItemVersionID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
IngestState governance.IngestState
|
||||
ProcessingState governance.ProcessingState
|
||||
TargetScope governance.Visibility
|
||||
ContentObjectID string
|
||||
SHA256 string
|
||||
SizeBytes int64
|
||||
MIME string
|
||||
ValidatedFormat string
|
||||
LocalSpoolRef string
|
||||
Title string
|
||||
// 对象实际写入的测试实例身份;空 = 迁移前的旧行,无法证明归属。
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
IngestState governance.IngestState
|
||||
ProcessingState governance.ProcessingState
|
||||
TargetScope governance.Visibility
|
||||
ContentObjectID string
|
||||
SHA256 string
|
||||
SizeBytes int64
|
||||
MIME string
|
||||
ValidatedFormat string
|
||||
LocalSpoolRef string
|
||||
Title string
|
||||
}
|
||||
|
||||
type PublicationForPoll struct {
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
ProcessingState governance.ProcessingState
|
||||
PollSequence int
|
||||
LastRemoteStatus string
|
||||
@@ -55,9 +60,11 @@ type PublicationForPoll struct {
|
||||
}
|
||||
|
||||
type PublicationForValidation struct {
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
ID string
|
||||
TestKBID string
|
||||
KnowledgeID string
|
||||
TestInstanceURL string
|
||||
TestInstanceTenant uint64
|
||||
// TargetScope 决定这条知识发到哪个生产库(对内/对外)。自动批准策略依赖它:
|
||||
// 默认只自动批准"对内","对外"仍要人工。
|
||||
TargetScope string
|
||||
@@ -71,6 +78,7 @@ type LegacyVerificationCandidate struct {
|
||||
|
||||
const loadPublicationForUploadSQL = `
|
||||
SELECT p.id, p.source_item_version_id, p.test_kb_id, p.knowledge_id,
|
||||
p.test_instance_url, p.test_instance_tenant,
|
||||
p.ingest_state, p.processing_state, p.target_scope,
|
||||
co.id, co.sha256, co.size_bytes, co.mime, co.validated_format,
|
||||
co.local_spool_ref, si.title
|
||||
@@ -89,7 +97,8 @@ WHERE p.id = $1
|
||||
`
|
||||
|
||||
const loadPublicationForPollSQL = `
|
||||
SELECT id, test_kb_id, knowledge_id, processing_state, poll_sequence,
|
||||
SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant,
|
||||
processing_state, poll_sequence,
|
||||
last_remote_status, last_remote_updated_at, processing_started_at,
|
||||
last_observed_at, updated_at
|
||||
FROM test_publications
|
||||
@@ -97,7 +106,7 @@ WHERE id = $1
|
||||
`
|
||||
|
||||
const loadPublicationForValidationSQL = `
|
||||
SELECT id, test_kb_id, knowledge_id, target_scope
|
||||
SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant, target_scope
|
||||
FROM test_publications
|
||||
WHERE id = $1
|
||||
AND ingest_state = 'uploaded'
|
||||
@@ -223,8 +232,10 @@ ON CONFLICT (idempotency_key) DO NOTHING
|
||||
const markUploadingSQL = `
|
||||
UPDATE test_publications
|
||||
SET ingest_state = 'uploading',
|
||||
test_instance_url = $2,
|
||||
test_instance_tenant = $3,
|
||||
last_error = '',
|
||||
updated_at = $2
|
||||
updated_at = $4
|
||||
WHERE id = $1
|
||||
AND ingest_state IN ('pending', 'uploading')
|
||||
AND processing_state = 'pending'
|
||||
@@ -393,6 +404,8 @@ func (s *Store) LoadPublicationForUpload(ctx context.Context, publicationID stri
|
||||
&candidate.SourceItemVersionID,
|
||||
&candidate.TestKBID,
|
||||
&candidate.KnowledgeID,
|
||||
&candidate.TestInstanceURL,
|
||||
&candidate.TestInstanceTenant,
|
||||
&ingestState,
|
||||
&processingState,
|
||||
&candidate.TargetScope,
|
||||
@@ -422,6 +435,8 @@ func (s *Store) LoadPublicationForPoll(ctx context.Context, publicationID string
|
||||
&publication.ID,
|
||||
&publication.TestKBID,
|
||||
&publication.KnowledgeID,
|
||||
&publication.TestInstanceURL,
|
||||
&publication.TestInstanceTenant,
|
||||
&processingState,
|
||||
&publication.PollSequence,
|
||||
&publication.LastRemoteStatus,
|
||||
@@ -446,6 +461,8 @@ func (s *Store) LoadPublicationForValidation(ctx context.Context, publicationID
|
||||
&publication.ID,
|
||||
&publication.TestKBID,
|
||||
&publication.KnowledgeID,
|
||||
&publication.TestInstanceURL,
|
||||
&publication.TestInstanceTenant,
|
||||
&publication.TargetScope,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -594,8 +611,8 @@ func (s *Store) RetryPublication(ctx context.Context, publicationID string, now
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkUploading(ctx context.Context, publicationID string, now time.Time) error {
|
||||
tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, now)
|
||||
func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL string, instanceTenant uint64, now time.Time) error {
|
||||
tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, instanceURL, instanceTenant, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark test publication uploading: %w", err)
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
|
||||
if _, err := store.LoadPublicationForUpload(ctx, "publication-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.MarkUploading(ctx, "publication-1", now); err != nil {
|
||||
if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestLoadPublicationForUploadMapsVerifiedCandidate(t *testing.T) {
|
||||
|
||||
func TestMarkUploadingRejectsStalePublicationState(t *testing.T) {
|
||||
db := &recordingDB{commandTag: pgconn.NewCommandTag("UPDATE 0")}
|
||||
err := NewStore(db).MarkUploading(context.Background(), "publication-1", time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
|
||||
err := NewStore(db).MarkUploading(context.Background(), "publication-1", "", 0, time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
|
||||
if !errors.Is(err, ErrPublicationStateConflict) {
|
||||
t.Fatalf("MarkUploading() error = %v, want ErrPublicationStateConflict", err)
|
||||
}
|
||||
@@ -380,6 +380,8 @@ func (publicationValidationRow) Scan(dest ...any) error {
|
||||
*(dest[0].(*string)) = "publication-1"
|
||||
*(dest[1].(*string)) = "kb-1"
|
||||
*(dest[2].(*string)) = "knowledge-1"
|
||||
*(dest[3].(*string)) = ""
|
||||
*(dest[4].(*uint64)) = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -547,13 +549,15 @@ func (row publicationPollRow) Scan(dest ...any) error {
|
||||
*(dest[0].(*string)) = "publication-1"
|
||||
*(dest[1].(*string)) = "kb-1"
|
||||
*(dest[2].(*string)) = "knowledge-1"
|
||||
*(dest[3].(*string)) = string(governance.ProcessingProcessing)
|
||||
*(dest[4].(*int)) = 2
|
||||
*(dest[5].(*string)) = "processing"
|
||||
*(dest[6].(**time.Time)) = &row.now
|
||||
*(dest[7].(**time.Time)) = &row.now
|
||||
*(dest[3].(*string)) = ""
|
||||
*(dest[4].(*uint64)) = 0
|
||||
*(dest[5].(*string)) = string(governance.ProcessingProcessing)
|
||||
*(dest[6].(*int)) = 2
|
||||
*(dest[7].(*string)) = "processing"
|
||||
*(dest[8].(**time.Time)) = &row.now
|
||||
*(dest[9].(**time.Time)) = &row.now
|
||||
*(dest[10].(**time.Time)) = &row.now
|
||||
*(dest[11].(**time.Time)) = &row.now
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -572,6 +576,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
|
||||
"version-1",
|
||||
"kb-1",
|
||||
"",
|
||||
"", // test_instance_url
|
||||
uint64(0),
|
||||
string(governance.IngestPending),
|
||||
string(governance.ProcessingPending),
|
||||
"internal",
|
||||
@@ -589,6 +595,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
|
||||
*target = value.(string)
|
||||
case *int64:
|
||||
*target = value.(int64)
|
||||
case *uint64:
|
||||
*target = value.(uint64)
|
||||
case *governance.Visibility:
|
||||
*target = governance.Visibility(value.(string))
|
||||
case nil:
|
||||
|
||||
@@ -48,6 +48,53 @@ type ClientConfig struct {
|
||||
Timeout time.Duration
|
||||
MaxResponseBytes int64
|
||||
AllowDockerHTTP bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for RFC1918 / link-local
|
||||
// literals, because the production instance is only reachable as a same-LAN
|
||||
// http reverse proxy. Public http hosts stay refused.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
// HTTPPolicy is the single reachability judgement shared by the WeKnora client,
|
||||
// the console probes and the binding page: two callers must never disagree
|
||||
// about whether a configured endpoint is acceptable.
|
||||
type HTTPPolicy struct {
|
||||
AllowPrivateHTTP bool
|
||||
AllowDockerHTTP bool
|
||||
}
|
||||
|
||||
// HTTPAllowed reports whether baseURL may be called at all. https is always
|
||||
// allowed; http only for loopback, an opted-in private address, or a
|
||||
// single-label docker host.
|
||||
func HTTPAllowed(rawURL string, policy HTTPPolicy) bool {
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || parsed.Host == "" || parsed.User != nil {
|
||||
return false
|
||||
}
|
||||
switch parsed.Scheme {
|
||||
case "https":
|
||||
return true
|
||||
case "http":
|
||||
host := parsed.Hostname()
|
||||
if isLoopbackHost(host) {
|
||||
return true
|
||||
}
|
||||
if policy.AllowPrivateHTTP && isPrivateHost(host) {
|
||||
return true
|
||||
}
|
||||
return policy.AllowDockerHTTP && isSingleLabelDockerHost(host)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isPrivateHost reports the addresses a same-LAN deployment legitimately uses:
|
||||
// RFC1918, link-local and IPv6 ULA. A public name is never private, so opting
|
||||
// in cannot widen the client to the internet.
|
||||
func isPrivateHost(host string) bool {
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
return ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
@@ -65,7 +112,7 @@ func NewClient(config ClientConfig) (*Client, error) {
|
||||
if baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {
|
||||
return nil, errors.New("invalid WeKnora base URL")
|
||||
}
|
||||
if baseURL.Scheme != "https" && !(baseURL.Scheme == "http" && (isLoopbackHost(baseURL.Hostname()) || (config.AllowDockerHTTP && isSingleLabelDockerHost(baseURL.Hostname())))) {
|
||||
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
|
||||
return nil, errors.New("WeKnora base URL must use HTTPS")
|
||||
}
|
||||
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
|
||||
@@ -234,6 +281,31 @@ func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBasesPage reads one page. The console must show every readable
|
||||
// base without pretending the first page is the whole set, so the total is
|
||||
// carried through whenever the instance reports one.
|
||||
func (c *Client) ListKnowledgeBasesPage(ctx context.Context, page, pageSize int) (KnowledgeBasePage, error) {
|
||||
if !validPage(page, pageSize) {
|
||||
return KnowledgeBasePage{}, errors.New("invalid knowledge base list request")
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("page", fmt.Sprint(page))
|
||||
query.Set("page_size", fmt.Sprint(pageSize))
|
||||
var response knowledgeBaseListResponse
|
||||
if err := c.doJSONQuery(ctx, http.MethodGet, "/api/v1/knowledge-bases", query, nil, &response); err != nil {
|
||||
return KnowledgeBasePage{}, err
|
||||
}
|
||||
if !response.Success {
|
||||
return KnowledgeBasePage{}, errors.New("WeKnora returned an unsuccessful knowledge base list")
|
||||
}
|
||||
total := response.Total
|
||||
totalKnown := total > 0 || (len(response.Data) == 0 && response.Page > 0)
|
||||
if !totalKnown {
|
||||
total = int64(len(response.Data))
|
||||
}
|
||||
return KnowledgeBasePage{Items: response.Data, Total: total, Page: page, PageSize: pageSize, TotalKnown: totalKnown}, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBase reads a single knowledge base by id. A knowledge base that is
|
||||
// not there surfaces as *HTTPError with status 404, so a caller can tell
|
||||
// "definitely absent" from "could not ask".
|
||||
|
||||
@@ -2,6 +2,8 @@ package weknora
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -76,8 +78,21 @@ type KnowledgeBase struct {
|
||||
}
|
||||
|
||||
type knowledgeBaseListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// KnowledgeBasePage is one page of the readable knowledge bases. TotalKnown is
|
||||
// false when the instance did not report a total; callers must not invent one.
|
||||
type KnowledgeBasePage struct {
|
||||
Items []KnowledgeBase
|
||||
Total int64
|
||||
Page int
|
||||
PageSize int
|
||||
TotalKnown bool
|
||||
}
|
||||
|
||||
type knowledgeBaseResponse struct {
|
||||
@@ -85,6 +100,34 @@ type knowledgeBaseResponse struct {
|
||||
Data KnowledgeBase `json:"data"`
|
||||
}
|
||||
|
||||
// InstanceIdentity is the verifiable identity of the WeKnora instance a call
|
||||
// actually reached: the normalized service address plus the tenant that owns
|
||||
// the knowledge base. Knowledge base ids alone cannot distinguish a cloned
|
||||
// instance, so workflows that stored an object must compare this before using
|
||||
// the object again.
|
||||
type InstanceIdentity struct {
|
||||
BaseURL string
|
||||
TenantID uint64
|
||||
}
|
||||
|
||||
// NormalizeInstanceURL is the single comparison form for service addresses:
|
||||
// scheme/host are case-insensitive and a trailing slash is not a different
|
||||
// instance. Userinfo/query/fragment never reach storage (endpoints are
|
||||
// validated as bare origins), so they are deliberately dropped here.
|
||||
func NormalizeInstanceURL(raw string) string {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
parsed.Scheme = strings.ToLower(parsed.Scheme)
|
||||
parsed.Host = strings.ToLower(parsed.Host)
|
||||
parsed.Path = strings.TrimRight(parsed.Path, "/")
|
||||
parsed.User = nil
|
||||
parsed.RawQuery = ""
|
||||
parsed.Fragment = ""
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
type chunkListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []Chunk `json:"data"`
|
||||
|
||||
+21
-32
@@ -1,53 +1,42 @@
|
||||
package qaopsai
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"knowledge-governance/internal/secretbox"
|
||||
)
|
||||
|
||||
// The independently provisioned master key never lives in source, settings JSON or database backups.
|
||||
func (s *Store) box() (*secretbox.Box, error) {
|
||||
box, err := secretbox.Load(s.options.KeyFile)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return box, nil
|
||||
}
|
||||
|
||||
// masterKey 保留给调用方判断“存储是否就绪”;实际加解密统一走 secretbox。
|
||||
func (s *Store) masterKey() ([]byte, error) {
|
||||
info, err := os.Lstat(s.options.KeyFile)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
raw, err := os.ReadFile(s.options.KeyFile)
|
||||
if err != nil || len(raw) != 32 {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
func (s *Store) aead() (cipher.AEAD, error) {
|
||||
key, err := s.masterKey()
|
||||
if err != nil {
|
||||
if _, err := s.box(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
return []byte{1}, nil
|
||||
}
|
||||
|
||||
func (s *Store) seal(secret string, revision int64) ([]byte, error) {
|
||||
aead, err := s.aead()
|
||||
box, err := s.box()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonce := make([]byte, aead.NonceSize())
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return aead.Seal(nonce, nonce, []byte(secret), []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))), nil
|
||||
return box.Seal([]byte(secret), fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))
|
||||
}
|
||||
|
||||
func (s *Store) unseal(sealed []byte, revision int64) (string, error) {
|
||||
aead, err := s.aead()
|
||||
if err != nil || len(sealed) < aead.NonceSize() {
|
||||
return "", ErrUnavailable
|
||||
box, err := s.box()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision)))
|
||||
raw, err := box.Open(sealed, fmt.Sprintf("qa-ai:%s:%d", s.tenant, revision))
|
||||
if err != nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ type Resolver struct {
|
||||
LoadBinding func(context.Context) (string, error)
|
||||
ReadKey func() (string, error)
|
||||
DefaultKB string
|
||||
// ResolveConnection 可选:一次解析端点与凭据(例如来自加密存储)。
|
||||
// 提供时优先于 Endpoint + ReadKey,因为密钥解密需要请求上下文。
|
||||
ResolveConnection func(context.Context) (baseURL, apiKey string, err error)
|
||||
}
|
||||
|
||||
func (resolver Resolver) Resolve(ctx context.Context) (Target, error) {
|
||||
@@ -58,25 +61,35 @@ func (resolver Resolver) Resolve(ctx context.Context) (Target, error) {
|
||||
knowledgeBaseID = stored
|
||||
}
|
||||
}
|
||||
apiKey := ""
|
||||
if resolver.ReadKey != nil {
|
||||
value, err := resolver.ReadKey()
|
||||
baseURL, apiKey := "", ""
|
||||
if resolver.ResolveConnection != nil {
|
||||
var err error
|
||||
baseURL, apiKey, err = resolver.ResolveConnection(ctx)
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败")
|
||||
return Target{}, fmt.Errorf("读取 WeKnora 有效连接失败:%w", err)
|
||||
}
|
||||
} else {
|
||||
if resolver.ReadKey != nil {
|
||||
value, err := resolver.ReadKey()
|
||||
if err != nil {
|
||||
return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败")
|
||||
}
|
||||
apiKey = strings.TrimSpace(value)
|
||||
}
|
||||
if resolver.Endpoint != nil {
|
||||
baseURL = strings.TrimSpace(resolver.Endpoint(ctx))
|
||||
}
|
||||
apiKey = strings.TrimSpace(value)
|
||||
}
|
||||
baseURL := ""
|
||||
if resolver.Endpoint != nil {
|
||||
baseURL = strings.TrimSpace(resolver.Endpoint(ctx))
|
||||
}
|
||||
return Target{BaseURL: baseURL, KnowledgeBaseID: knowledgeBaseID, APIKey: apiKey}, nil
|
||||
return Target{BaseURL: strings.TrimSpace(baseURL), KnowledgeBaseID: knowledgeBaseID, APIKey: strings.TrimSpace(apiKey)}, nil
|
||||
}
|
||||
|
||||
type Prober struct {
|
||||
Resolve func(context.Context) (Target, error)
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
// AllowPrivateHTTP relaxes the plain-http rule for same-LAN addresses, the
|
||||
// same judgement the binding store and the client use.
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
func (prober Prober) Check(ctx context.Context) Result {
|
||||
@@ -96,10 +109,11 @@ func (prober Prober) Check(ctx context.Context) Result {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: prober.AllowDockerHTTP,
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: prober.AllowDockerHTTP,
|
||||
AllowPrivateHTTP: prober.AllowPrivateHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return Result{Target: described, Err: err}
|
||||
|
||||
@@ -151,5 +151,5 @@ func testDocumentBundle(t *testing.T) *DocumentBundle {
|
||||
func fixedArchiveTime() time.Time { return time.Date(2026, 9, 6, 11, 0, 0, 0, time.UTC) }
|
||||
|
||||
func releasePlanForArchive() releaseworkflow.PlanItem {
|
||||
return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
|
||||
return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package v071
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/releasebundle"
|
||||
releaseworkflow "knowledge-governance/internal/workflows/release"
|
||||
)
|
||||
@@ -49,6 +51,11 @@ type DocumentTargetConfig struct {
|
||||
Search searchDocumentTarget
|
||||
Objects objectDocumentTarget
|
||||
Verifier ProductionVerifier
|
||||
// TargetInstanceURL/TargetTenantID are the executor's own route target. The
|
||||
// console freezes the instance it verified the binding on; this side must
|
||||
// match before any document write/restore.
|
||||
TargetInstanceURL string
|
||||
TargetTenantID uint64
|
||||
}
|
||||
|
||||
type DocumentTarget struct {
|
||||
@@ -63,6 +70,9 @@ func NewDocumentTarget(config DocumentTargetConfig) (*DocumentTarget, error) {
|
||||
}
|
||||
|
||||
func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow.PlanItem) (releasebundle.TargetContract, error) {
|
||||
if err := target.checkInstance(item); err != nil {
|
||||
return releasebundle.TargetContract{}, err
|
||||
}
|
||||
contract, err := target.config.Contract.Contract(ctx, item)
|
||||
if err != nil {
|
||||
return releasebundle.TargetContract{}, errors.New("inspect target release contract")
|
||||
@@ -75,6 +85,9 @@ func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow
|
||||
// same target base. The archive itself keeps the canonical source-form bundle:
|
||||
// the remap is deterministic, so a rollback re-derives the same target form.
|
||||
func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision string) (*DocumentBundle, error) {
|
||||
if err := target.checkInstance(item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bundle, err := target.config.Archive.Load(revision)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -86,6 +99,9 @@ func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision
|
||||
}
|
||||
|
||||
func (target *DocumentTarget) Prepare(ctx context.Context, item releaseworkflow.PlanItem, exported releaseworkflow.ExportedBundle) (releaseworkflow.PreparedChange, error) {
|
||||
if err := target.checkInstance(item); err != nil {
|
||||
return releaseworkflow.PreparedChange{}, err
|
||||
}
|
||||
bundle, ok := exported.(*DocumentBundle)
|
||||
if !ok || validateDocumentBundle(bundle) != nil || bundle.Manifest.ReleaseRevision != item.ReleaseRevision {
|
||||
return releaseworkflow.PreparedChange{}, errors.New("invalid v0.7.1 target bundle")
|
||||
@@ -219,6 +235,30 @@ func (target *DocumentTarget) VerifyRestored(ctx context.Context, item releasewo
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkInstance is the single instance-identity boundary for the document
|
||||
// release path. Empty identity means a pre-identity binding: the executor
|
||||
// cannot prove which instance it is, so it fails closed instead of writing to a
|
||||
// cloned instance that happens to expose the same knowledge base id.
|
||||
func (target *DocumentTarget) checkInstance(item releaseworkflow.PlanItem) error {
|
||||
if item.TargetInstanceURL == "" || item.TargetTenantID == 0 {
|
||||
return fmt.Errorf("%w: binding has no verified instance identity", releaseworkflow.ErrTargetInstanceMismatch)
|
||||
}
|
||||
if target.config.TargetInstanceURL == "" || target.config.TargetTenantID == 0 {
|
||||
return fmt.Errorf("%w: executor target identity is not configured", releaseworkflow.ErrTargetInstanceMismatch)
|
||||
}
|
||||
if weknora.NormalizeInstanceURL(item.TargetInstanceURL) != weknora.NormalizeInstanceURL(target.config.TargetInstanceURL) {
|
||||
return fmt.Errorf("%w: binding verified on %s, executor writes %s",
|
||||
releaseworkflow.ErrTargetInstanceMismatch,
|
||||
weknora.NormalizeInstanceURL(item.TargetInstanceURL),
|
||||
weknora.NormalizeInstanceURL(target.config.TargetInstanceURL))
|
||||
}
|
||||
if item.TargetTenantID != target.config.TargetTenantID {
|
||||
return fmt.Errorf("%w: binding tenant %d, executor tenant %d",
|
||||
releaseworkflow.ErrTargetInstanceMismatch, item.TargetTenantID, target.config.TargetTenantID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (target *DocumentTarget) restoreBundle(ctx context.Context, item releaseworkflow.PlanItem, revision string) error {
|
||||
bundle, err := target.loadBundle(item, revision)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -20,7 +21,7 @@ func TestDocumentTargetCoordinatesPrepareActivateVerifyAndRollback(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := []string{}
|
||||
target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}})
|
||||
target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -60,7 +61,7 @@ func TestDocumentTargetCompensatesFirstReleaseByDisableWithoutDelete(t *testing.
|
||||
archive, _ := NewBundleArchive(root, 16*1024*1024)
|
||||
bundle := testDocumentBundle(t)
|
||||
calls := []string{}
|
||||
target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}})
|
||||
target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
|
||||
item := releasePlanForArchive()
|
||||
change, err := target.Prepare(context.Background(), item, bundle)
|
||||
if err != nil {
|
||||
@@ -179,3 +180,44 @@ func revisionFromSearch(snapshot SearchSnapshot) string {
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// 网页在实例 A 上列库并保存了绑定,执行器实际连的是实例 B;即使两边知识库
|
||||
// ID 与租户完全相同,也不得写入 B。这里复用 DocumentTarget 的唯一实例身份
|
||||
// 检查,正例证明同一实例仍可通过。
|
||||
func TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
_ = os.Chmod(root, 0o700)
|
||||
archive, _ := NewBundleArchive(root, 16*1024*1024)
|
||||
bundle := testDocumentBundle(t)
|
||||
calls := []string{}
|
||||
target, err := NewDocumentTarget(DocumentTargetConfig{
|
||||
Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)},
|
||||
Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls},
|
||||
Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls},
|
||||
TargetInstanceURL: "https://instance-b.weknora.example", TargetTenantID: 10000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item := releasePlanForArchive() // verified on instance A, same kb id, same tenant
|
||||
item.TargetKnowledgeBaseID = "kb-safe"
|
||||
if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
|
||||
t.Fatalf("contract error = %v, want ErrTargetInstanceMismatch", err)
|
||||
}
|
||||
if _, err := target.Prepare(context.Background(), item, bundle); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
|
||||
t.Fatalf("prepare error = %v, want ErrTargetInstanceMismatch", err)
|
||||
}
|
||||
if len(calls) != 0 {
|
||||
t.Fatalf("no write/stage may happen before identity matches: %v", calls)
|
||||
}
|
||||
|
||||
item.TargetInstanceURL = "https://instance-b.weknora.example"
|
||||
item.TargetTenantID = 10000
|
||||
if _, err := target.Contract(context.Background(), item); err != nil {
|
||||
t.Fatalf("same instance must pass: %v", err)
|
||||
}
|
||||
item.TargetTenantID = 20000
|
||||
if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
|
||||
t.Fatalf("tenant mismatch error = %v, want ErrTargetInstanceMismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,7 +274,9 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
}
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range pg.Tables {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
if libraryResourceBodyTable(table.Name) {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
}
|
||||
}
|
||||
references, err := libraryResourceHandles(bodies)
|
||||
if err != nil {
|
||||
|
||||
@@ -35,7 +35,7 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
rowsByTable[table] = rows
|
||||
if table != "resource_bindings" && table != "knowledge_tag_relations" {
|
||||
if libraryResourceBodyTable(table) {
|
||||
bodies = append(bodies, rows...)
|
||||
}
|
||||
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"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
@@ -34,6 +38,17 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
if err != nil {
|
||||
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
|
||||
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")
|
||||
@@ -85,7 +100,7 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
// The latter includes Wiki manual pages, which document bundles used to miss.
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range snapshot.Tables {
|
||||
if table.Name == "resource_bindings" || table.Name == "knowledge_tag_relations" {
|
||||
if !libraryResourceBodyTable(table.Name) {
|
||||
continue
|
||||
}
|
||||
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_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 }{
|
||||
{"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`},
|
||||
// 编辑历史:只随活跃父行发布。父行被软删(不在本次范围)时不搬它的历史;
|
||||
// 父行完全缺失属于数据异常,由 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_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`},
|
||||
{"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_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`},
|
||||
|
||||
@@ -103,6 +103,11 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row
|
||||
if d.queryError {
|
||||
return nil, errors.New("fixture failure")
|
||||
}
|
||||
// 漏表门禁也查 information_schema,但回答形状是(表,列集合);与能力探测分开打桩,
|
||||
// 否则会被当成两列结果扫描。74 夹具没有任何未分类的知识域表。
|
||||
if strings.Contains(q, "knowledge-table-gate") {
|
||||
return &jsonRows{}, nil
|
||||
}
|
||||
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
|
||||
if strings.Contains(q, "information_schema.columns") {
|
||||
return legacySchemaProbeRows(), nil
|
||||
|
||||
@@ -31,7 +31,11 @@ var migrationIdentityContracts = map[string]rowIdentityContract{
|
||||
"wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||
// 编辑历史:稳定字符串身份;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"},
|
||||
}
|
||||
|
||||
type typedRowIdentity struct {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -344,12 +345,16 @@ func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string)
|
||||
if name == "resources" {
|
||||
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`,
|
||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
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...)
|
||||
}
|
||||
if name == "resource_bindings" {
|
||||
@@ -479,6 +484,16 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra
|
||||
return errors.New("开启生产事务失败")
|
||||
}
|
||||
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-- {
|
||||
table := t.tables[index]
|
||||
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)
|
||||
}
|
||||
}
|
||||
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() {
|
||||
call("DELETE", "/"+index, "", 200)
|
||||
call("HEAD", "/"+index, "", 404)
|
||||
@@ -375,7 +375,7 @@ func v090PublishIndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA stri
|
||||
t.Fatalf("decode chunk: %v", err)
|
||||
}
|
||||
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,
|
||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||
"embedding": []float64{0.1, 0.2},
|
||||
|
||||
@@ -57,6 +57,10 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
|
||||
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)
|
||||
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")
|
||||
}
|
||||
}
|
||||
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")
|
||||
if err := seedV090Binding(t, ctx, dst); err != nil {
|
||||
@@ -100,14 +111,21 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
reloaded, err := ExportLibrary(ctx, dst, identity)
|
||||
if err != nil {
|
||||
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 由目标序列分配。
|
||||
var defaults int
|
||||
@@ -130,7 +148,7 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
}
|
||||
|
||||
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
|
||||
crossVersion := source
|
||||
crossVersion := documentSource
|
||||
crossVersion.SchemaVersion = 74
|
||||
crossVersion.Profile = "v071"
|
||||
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 逐表逐行比对"共有列"的规范化内容。
|
||||
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
|
||||
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))
|
||||
}
|
||||
for _, table := range source.Tables {
|
||||
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||
continue
|
||||
}
|
||||
want := tableDigests(t, table.Name, table.Rows)
|
||||
got := tableDigests(t, table.Name, target.Table(table.Name).Rows)
|
||||
if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) {
|
||||
|
||||
@@ -9,13 +9,26 @@ import (
|
||||
"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.
|
||||
// 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).
|
||||
func libraryResourceBodyReferenceSQL(tables []string, predicate string) string {
|
||||
queries := []string{}
|
||||
for _, table := range tables {
|
||||
if table == "resources" || table == "resource_bindings" || table == "knowledge_tag_relations" {
|
||||
if !libraryResourceBodyTable(table) {
|
||||
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))
|
||||
|
||||
@@ -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{
|
||||
"knowledges": true, "chunks": true, "knowledge_tags": true,
|
||||
"wiki_folders": true, "wiki_pages": true, "wiki_page_issues": true, "wiki_log_entries": true,
|
||||
"chunk_revisions": true, "wiki_page_revisions": true,
|
||||
}
|
||||
|
||||
// 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"] {
|
||||
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
|
||||
return e
|
||||
|
||||
@@ -173,6 +173,26 @@ func (m *targetIDMapper) remapRow(table string, row map[string]json.RawMessage)
|
||||
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":
|
||||
// id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档,
|
||||
// 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。
|
||||
|
||||
@@ -80,12 +80,15 @@ func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, ta
|
||||
if name == "resources" {
|
||||
continue
|
||||
}
|
||||
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||
continue
|
||||
}
|
||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
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...)
|
||||
}
|
||||
if name == "resource_bindings" {
|
||||
|
||||
@@ -122,6 +122,13 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
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 {
|
||||
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,
|
||||
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
||||
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 {
|
||||
if part.Kind != "database" && part.Kind != "wiki" {
|
||||
continue
|
||||
@@ -350,6 +358,14 @@ func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner strin
|
||||
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 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份,
|
||||
// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管
|
||||
// 使用的资源不能删)。
|
||||
@@ -365,9 +381,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
|
||||
// 子表先删:resource_bindings → chunks/knowledges、wiki 子表 → wiki 页 → 资源。
|
||||
for _, table := range []string{"resource_bindings", "chunks", "knowledges", "knowledge_tag_relations",
|
||||
"wiki_page_issues", "wiki_log_entries", "wiki_pages", "wiki_folders", "knowledge_tags", "resources"} {
|
||||
for _, table := range jobCreatedRowDeleteOrder {
|
||||
ids := make([]string, 0, 8)
|
||||
for _, id := range set.CreatedIDs(table) {
|
||||
if restored[table][id] {
|
||||
|
||||
@@ -97,7 +97,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) {
|
||||
}
|
||||
verification := &verificationClient{knowledge: weknora.Knowledge{ID: "knowledge-release-safe", KnowledgeBaseID: "kb-release-safe", ParseStatus: "completed"}, chunkTotal: 1, search: []weknora.SearchResult{{ID: "chunk-release-safe", KnowledgeID: "knowledge-release-safe", Score: 0.8}}}
|
||||
verifier, _ := NewWeKnoraVerifier(verification)
|
||||
target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
|
||||
target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -106,7 +106,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"}
|
||||
first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"}
|
||||
if _, err := exporter.Export(ctx, first); err != nil {
|
||||
t.Fatalf("export preflight: %v", err)
|
||||
}
|
||||
|
||||
@@ -84,6 +84,8 @@ const v090Folder = "wf-v090-1"
|
||||
const v090Page = "wp-v090-1"
|
||||
const v090Tag = "tg-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 资源。
|
||||
// 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_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 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 + `')`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
@@ -166,7 +170,7 @@ func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) Sea
|
||||
t.Fatalf("decode chunk: %v", err)
|
||||
}
|
||||
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,
|
||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||
})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user