Compare commits
70 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c5ecdf0f3 | |||
| 9105f8316c | |||
| 74aef1e373 | |||
| 1b09f7d35b | |||
| d8d143eca0 | |||
| 52f4117835 | |||
| 7448d130ec | |||
| f0b12412a1 | |||
| 5b6e154459 | |||
| 8930ef29cd | |||
| a55d7f454e | |||
| b55292bba1 | |||
| 02ee5da231 | |||
| e744114ff4 | |||
| c8f05ee46f | |||
| 1e8d8e3cdf | |||
| 842bfccc1b | |||
| 740f0e69ba | |||
| 020cae1228 | |||
| 017cbcb851 | |||
| b3992bfa0f | |||
| 2902ba0af2 | |||
| 555bc6ff56 | |||
| 1dda055e4c | |||
| f87d3fad9b | |||
| 23b19350cc | |||
| 1a9d1fff83 | |||
| 822fb652ff | |||
| 600e9a2dc2 | |||
| eed83039ab | |||
| 43b1e423fe | |||
| 5aa32492de | |||
| 6816289552 | |||
| 1d33ff6976 | |||
| 1d880a0f49 | |||
| c239a5ef0e | |||
| 226d47a72d | |||
| 0f89c82625 | |||
| 9d8a40beab | |||
| 5d525ff592 | |||
| 09b2c1dce5 | |||
| 80d5078363 | |||
| 00c4c13283 | |||
| 65653e5c01 | |||
| ce02ae4eef | |||
| 8d44d54dc7 | |||
| 1c065846f6 | |||
| f38541db06 | |||
| f533c63fef | |||
| c56ab5850b | |||
| 1419ee03fc | |||
| 4e655fb977 | |||
| 99d6109bef | |||
| cb9f0c389f | |||
| 1580ebd826 | |||
| 2c0bb32183 | |||
| 87f97a2f9b | |||
| 154b0b62ad | |||
| 9470a127f7 | |||
| 4a2b2b7d84 | |||
| a9870beade | |||
| 533db535f1 | |||
| 330fd12b3f | |||
| f33730ed74 | |||
| f5e0f8d20f | |||
| 6e67034fbd | |||
| 76671e0784 | |||
| 8835a473dd | |||
| 93aabc8a81 | |||
| 3e7fcce0b1 |
@@ -21,6 +21,14 @@ DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT=
|
||||
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=
|
||||
# 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.
|
||||
QA_AI_TRUST_TLS_PROXY=false
|
||||
|
||||
APP_ADDR=:8080
|
||||
DATABASE_URL=postgres://governance@postgres:5432/governance?sslmode=disable
|
||||
PGPASSFILE=/run/secrets/pgpass
|
||||
|
||||
+348
@@ -1,9 +1,31 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 snapshot/v0.1.97 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 补齐已部署 0.1.96 的独立开发说明与精确提交绑定,恢复版本记录核验所需的开发快照证据;不变更正式版本号,不声称整库同步已经交付。
|
||||
- 更正整库验收文档中仍写“未提交、未部署”的历史状态,保留未接线、未验收与生产执行边界。
|
||||
|
||||
## 开发快照 snapshot/v0.1.96 - 2026-10-27
|
||||
|
||||
目标提交:9105f8316cc870a62b5ddacd1496f0cb0f798d87
|
||||
|
||||
### Added
|
||||
|
||||
- 增加整库 PostgreSQL 只读快照、Elasticsearch PIT 导出及独立资源归档,包含完整 Wiki 表、资源关联和摘要校验。
|
||||
- 增加测试写入服务暂停、持久恢复日志、异常与进程中断恢复原语,并实现候选捕获协调函数。
|
||||
|
||||
### Changed
|
||||
|
||||
- 本版本仅交付基础模块:尚无整库业务调用入口、版本验收绑定、生产预备份与同步恢复工作流、新发布页面及完整存储治理。隔离测试通过不等于完整业务验收通过;不包含生产执行或实际清理授权。
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
@@ -37,6 +59,8 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复钉钉新登记来源仍按旧离线目录身份取件的问题:从当前来源配置读取空间坐标,实时枚举所在目录并严格匹配节点身份;同名文件不替代、目录不完整不误报删除。修复解析监控遗漏 `version_id` 取件任务及缺少业务元数据的失败记录,正确显示失败原因、重试入口与历史。
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
@@ -76,6 +100,330 @@
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.63 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 周报固定保留编辑正文与排版预览的对照界面,移除编辑/预览/对照切换按钮及无用模式状态/样式;自动保存、复制排版内容和下载保持不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.62 - 2026-10-25
|
||||
|
||||
### Added
|
||||
|
||||
- 周报增加“复制排版内容”,复制渲染后的富文本及可读纯文本,不复制Markdown标记或原文查看器;编辑/预览/对照模式均取当前最新正文,保留下载MD原文。兼容局域网HTTP复制并明确报告失败。
|
||||
|
||||
## 开发快照 snapshot/v0.1.61 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 周报中英文正文移除质量统计月份、时间范围及分母规则说明,保留覆盖率、正确率及原自然月计算口径与来源审计。
|
||||
|
||||
## 开发快照 snapshot/v0.1.60 - 2026-10-25
|
||||
|
||||
### Added
|
||||
|
||||
- 右侧问答详情顶部增加上一条、下一条,沿当前筛选后的完整已载入表格顺序切换;首尾自动禁用,后续页载入后自动开放下一条,读取中或失败仍能切换,关闭保留原表格焦点。
|
||||
|
||||
## 开发快照 snapshot/v0.1.59 - 2026-10-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 流水表表头五项筛选不再传入统计看板;看板及PNG只按上方已查询的时间范围和关键词统计。保留表头对流水、明细导出及对应AI范围的限定,并拒绝将带字段筛选的返回误作全范围看板。
|
||||
|
||||
## 开发快照 snapshot/v0.1.58 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 问题流水表最左侧增加序号,按当前筛选结果从1连续编号,后台续载与虚拟滚动保持连续;不改变业务字段、原始数据或完整导出口径。
|
||||
|
||||
## 开发快照 snapshot/v0.1.57 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 五项质量筛选移至表格首行对应列,选择后立即查询;上方查询区不再增加字段选项,零匹配和续载时仍可调整表头条件。
|
||||
- 未覆盖问答的是否正确统一为待确认;仅未覆盖可显示待确认,已覆盖保留正确/错误及点踩优先。列表、详情、筛选、统计、完整导出和编辑约束共享同一有效规则,原始问答及历史人工/模型证据保留,不重新调用模型。
|
||||
|
||||
## 开发快照 snapshot/v0.1.56 - 2026-10-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 五项字段筛选独立换行,保留时间、关键词、查询与同步操作的完整可见范围,修正宽屏旧单行样式挤出筛选区的问题。
|
||||
|
||||
## 开发快照 snapshot/v0.1.55 - 2026-10-25
|
||||
|
||||
### Changed
|
||||
|
||||
- 问题流水表首批到达即可浏览,后续在后台自动续载;列表仅传轻量文本预览,完整问答/引用/媒体按需读取,完整明细另行导出,避免等全部正文下载后才显示。
|
||||
- 新增是否覆盖、是否正确、产品分类、问题类型、根因分析五项筛选,可与时间/关键词组合并查询未设置值;后端按完整总表的当前有效标签筛选,列表、看板及导出条件一致。字段筛选时不套用无明细的历史汇总。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 续载异常明确保留已读部分和失败状态,查询变更取消旧请求;详情保存和AI更新不被迟到分页覆盖,完整导出拒绝使用截断预览或不完整结果。
|
||||
|
||||
## 开发快照 snapshot/v0.1.54 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 回答正确性改为直接依据原问题和实际回答判断:已覆盖只保留正确或错误,只有未覆盖允许待确认,不再要求引用原文作为正确结论的前提;未形成有效回答的技术状态保持未评估,点踩仍优先为错误。
|
||||
- 模型评估、人工复核和详情字段编辑共同约束上述规则。旧已覆盖待确认可限定为仅重评正确性,通过统一有效层写入和不可变审计更新,不修改原始问答、其他已维护字段或历史证据。
|
||||
|
||||
## 开发快照 snapshot/v0.1.53 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 版本记录按参考图重排为当前构建信息卡和紧凑折叠列表,当前运行记录默认展开,其他记录收起;变更按新增、调整、修复、安全分类展示,原始说明和提交信息可展开核验。
|
||||
- 增加所有角色可用的只读刷新,保留管理员同步、真实版本身份、筛选及完整历史加载;北京时间、长提交与手机排版统一处理,不增加发布或部署权限。
|
||||
|
||||
## 开发快照 snapshot/v0.1.52 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 移除系统顶部的已打开页面标签栏及关闭入口,保留左侧功能导航、当前位置、来源路径和表格分页。
|
||||
- 左侧导航文字放大至16px、图标放大至20px,图标区域24px、导航项最小高度44px,手机抽屉同步生效。
|
||||
|
||||
## 开发快照 snapshot/v0.1.51 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 按人视图也直接展示所属部门名称,多部门逐行显示、完整路径悬停可看,去掉“个直属部门”折叠摘要;列宽与按区域统一。两个排行复用同一展示实现,移除不再使用的旧分支和样式;统计、兼属和50人分页不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.50 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 按区域人员表“所属部门”直接显示部门名称,多部门逐行列出并保留完整路径悬停说明;移除该视图的“个直属部门”折叠入口。人员与部门列加宽,区域列收紧;按人视图保留原详情入口和列宽,排序、去重、周期与分页不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.49 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 区域统计“部门/人员”列移除“本部门直属 N 人”小字;保留独立总人数列、部门展开、直属人员明细和兼属标记,统计数据与其他分析视图不变。
|
||||
|
||||
## 开发快照 snapshot/v0.1.48 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 区域统计按部门表格将“总人数”独立为一列,放在“访问人数”前;移除原访问人数格内的小字总人数。保留含子部门的稳定身份去重口径,人员行对应总人数/访问人数/访问比例均显示“—”,不改变一级默认展开及另外两个分析视图。
|
||||
|
||||
## 开发快照 snapshot/v0.1.47 - 2026-10-24
|
||||
|
||||
### Changed
|
||||
|
||||
- 区域统计按部门视图默认只展开到一级部门,二级及以下初始收起;保留手动逐级展开、直属人员、既有统计口径及按区域/按人视图。
|
||||
|
||||
## 开发快照 snapshot/v0.1.46 - 2026-10-21
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计新增“按部门/按区域/按人”分析切换;按部门保留原树形与直属人员。按区域查看已保存区域内人员,按人查看完整去重名册,均按提问次数降序并保留零提问人员,固定50人/页与页码选择,展示区域、所属部门、次数和最近提问时间。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新分析复用同一累计/自然月/自然周快照,不额外创建模型或聚合作业;同区域多部门人员只列一次,跨区域及未归属者单列待核对,不自动选主区域。分析分页与切换只读,不改变原问答、区域映射、部门汇总、已保存周报及外部发送闸门。
|
||||
|
||||
## 开发快照 snapshot/v0.1.45 - 2026-10-21
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计部门展开后展示直属人员及直属人数;人员行保留本统计范围的提问次数、最近提问时间与零使用人员,多部门人员显示“兼属 N 部门”,悬停可查看完整部门路径,也可点击或键盘展开名单。人员行只读,不参与部门勾选或区域绑定。
|
||||
|
||||
### Changed
|
||||
|
||||
- 兼属按稳定身份的不同直接部门去重,不把祖先继承计为额外部门,不合并同名不同人。累计、自然月及自然周统计范围、分支/区域去重人数与次数保持,展开人员不会重复累计;无部门关联人员明确列出,未命名如实提示,不新增绩效裁决、源端修改或模型调用。
|
||||
|
||||
## 开发快照 snapshot/v0.1.44 - 2026-10-21
|
||||
|
||||
### Changed
|
||||
|
||||
- 问题统计看板去掉个人月明细入口,十一张卡片右上角新增“统计口径”,悬停、键盘聚焦及触屏可查看实际范围、公式与排除数量;图片导出保留完整十一项及口径入口,不包含交互浮层。
|
||||
- 覆盖率与正确率趋势改为北京时间逐自然月独立计算,每月1日重新累计;使用总表当前有效结论、人工优先及点踩否,分别按是÷(是+否)计算,待确认等排除,空月/零分母留空。旧周上报、冻结及第40–43周累计证据保留,不再混画到月轴。
|
||||
- 每周看板的两项质量仪表与新建/主动重新预填周报使用月内累计;跨月周取周一所在月并截止该月底,非跨月周截止该周实际时点,当前周不预读未来。保留已保存周报正文、修订与重试标识,不自动改写旧稿,不修改源问答或触发付费模型及对外发送。
|
||||
|
||||
## 开发快照 snapshot/v0.1.43 - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
- 知识覆盖率与回答正确率趋势新增第40–43周“总表累计”绿色曲线:按北京时间各自然周截止纳入整张总表的累计问题,使用当前有效字段及点踩结论动态计算;覆盖率和正确率分别使用“是÷(是+否)”,待确认等未明确结论不进入对应分母,零分母不伪造百分比。逐点展示实际截止、累计条数、分子分母及规则版本,保留原历史上报和冻结证据。
|
||||
- 字段依据区区分真实模型返回与本地规则/历史唯一标签复用:语言识别、中文原文保留及历史分类复用逐字段展示来源与回填状态,明确标注“非模型”,不把外部受控任务冒充平台服务模型配置。
|
||||
- 看板每30秒顺序读取最新总表,当前选周截止推进至当前时点,已闭周查询保持原范围;离开或换条件取消旧请求,读取失败明确提示,不展示过期图表或导出旧图。
|
||||
|
||||
## 开发快照 snapshot/v0.1.42 - 2026-10-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- 问题存在当前点踩时,总表有效“是否正确”固定为“否”,列表、详情和动态质量统计使用同一规则;通过已保存来源关联读取本地镜像最新反馈,避免导入快照漏掉后续点踩。仅点赞或无反馈不推定正确,原问答、旧模型结论、人工复核与字段修改审计保持不变。
|
||||
- 详情对已点踩问题锁定“是否正确”并简洁说明;后端拒绝改为“是”或“待确认”的冲突选择,其余字段仍可编辑。迁移59只补充派生读模型、反馈索引及总表快照失效通知,不回写 DobotAI 源数据,也不重算或覆盖旧周冻结与历史上报。
|
||||
|
||||
## 开发快照 snapshot/v0.1.41 - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
- 周报生成升级为按北京时间自然周保存的 Markdown 编辑器,提供编辑、预览、对照、自动保存、立即保存及 MD/本周明细 CSV 下载;每个租户每周一份共享草稿,切周或离开前保存未提交输入,刷新与重新打开恢复正文。
|
||||
- 按周报模板预填英文在上、中文在下的各六节正文,复用正式总表和已保存区域统计;历史周优先使用相应上报/冻结质量指标,缺失才使用当周实时指标。统计建议可人工修改,重点保留待填写,不编造 FAQ 调整或英文事项,不自动发送或归档。
|
||||
- 治理库新增迁移 58:独立稀疏字段覆盖、不可变字段改动审计、周草稿及逐版保存收据。保存绑定输入与编辑版本,同 nonce 重试不重复留档,冲突和读回失败保留输入;已有草稿重新预填须明确确认,存在人工数据时拒绝删除式降级迁移。
|
||||
|
||||
### Changed
|
||||
|
||||
- 详情顶部五个质量字段可直接下拉修改,范围取源主表实际使用的覆盖/正确性选项及与模型共享的产品、问题、根因字典;只保存明确选择的字段,不补齐其他空白、不把模型值冒充整条人工复核。移除单独人工复核/反馈展示,保留原始问答、旧人工历史和后台留痕。
|
||||
- 区域统计的月份及 ISO 周同时支持下拉选择和直接输入,合法值在回车或失焦后应用;未完成、非法及未来输入在本地提示,不发送错误统计请求,保留原自然月/周和缓存口径。
|
||||
|
||||
## 开发快照 snapshot/v0.1.40 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计明确支持按累计、北京时间自然月、北京时间自然周三种范围;自然周按周一至周日,可选择历史周,校验跨年周次、非法周和未来周,独立缓存包含周次及组织版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 部门树默认显示公司、中心及二级部门,更深层收起;保留手动展开与搜索,父行去重人数和提问次数不随收起变化。
|
||||
- 选中部门后在当前统计页选择区域并绑定,复用预览、双版本锁和保存后独立读回,不跳转另一张映射表;父选仍覆盖后代,既有非选中部门规则保留。
|
||||
- 区域设置重做为原页面内的名称列表面板,支持新增、改名、删除及未保存草稿保护。删除已绑定区域须确认解除直接绑定,目录与规则一次保存,不删除原问答;重复点击原删除位置只取消确认。
|
||||
- 区域筛选及绑定选项取已保存目录,新增/改名/删除后刷新,删除当前筛选项回全部;问题统计看板的平均使用频率和使用覆盖率沿用同一已保存组织配置,保留自然月口径与零分母未知,不重新计算冻结历史。
|
||||
|
||||
## 开发快照 snapshot/v0.1.39 - 2026-10-19
|
||||
|
||||
### Changed
|
||||
|
||||
- “问题流水”改为“问题流水表”;详情从右侧非模态弹出,不再生成左侧遮罩或焦点陷阱。移除详情中的区域、组织关联/版本/快照、记录来源、问答状态与流程触发人员展示,原始数据与审计不删除。
|
||||
- 是否覆盖、是否正确、产品分类、问题类型、根因分析置于详情顶部固定区域,正文独立滚动;查询与立即同步统一尺寸和基线。
|
||||
- 字段评估与中文翻译统一为“AI分析”,分别预览缺口、确认后按实际需要创建两类持久任务;部分成功重试保留幂等标识,跳过已确认种类与零缺口种类,不覆盖人工或已有非空结论。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 大流水表保留全量载入与无分页滚动,改为仅渲染可见行和缓冲行、稳定行引用及固定列宽;列表长文本限预览,详情与导出仍取完整原文,重复后台状态不再驱动整表刷新。
|
||||
- AI执行改为数据库准入控制的默认4并发、独立任务租约与过期栅栏;慢模型调用不阻塞其他工作槽或自动扫描。429遵守共享有界冷却;输出截断单独归因,最多三次有界重试并逐次扩大输出预算,最终失败保留可见状态。
|
||||
- 兼容源引用的knowledge_title字段,不将只有标题的引用伪造为正文证据;证据不足仍待确认,不将模型自报置信度当作准确率。修正人工复核区仍声称AI未接入的旧提示。
|
||||
|
||||
## 开发快照 snapshot/v0.1.38 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计新增可展开部门树:部门、访问人数、访问比例、访问次数、最近提问时间五列,访问人数附当前通讯录总人数;整支含自身和全部子部门,按稳定人员身份去重,调岗依当前归属,零分母显示“—”,收起不重算数字。
|
||||
- 统计仅读独立治理总表中的提问事件,支持累计与北京时间自然月;单并发后台聚合、请求合并和60秒缓存,目录或区域配置版本变化立即隔离旧缓存;加载/失败不伪装零数据,不占用代理转发链路。
|
||||
|
||||
### Changed
|
||||
|
||||
- 原“区域配置”入口改为“区域统计”,区域设置保留自定义区域新增/改名、未使用区域删除、部门映射预览与双版本锁保存;勾选父部门联选全部后代,取消子支时解除祖先整支选中,防止未选部门被父级新规则误覆盖。
|
||||
- 统计与区域设置共享选择;搜索、按区域查看及展开收起只改变可见行,既有总表、原始问答、历史趋势、模型任务与生产数据不修改。
|
||||
|
||||
## 开发快照 snapshot/v0.1.37 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 统计看板的覆盖率、正确率趋势支持独立持久保存的用户历史报表值,按北京时间ISO自然周展示、精确到两位小数并注明来源;和系统冻结使用分开的曲线,不伪造记录数、分子分母或冻结时间。
|
||||
|
||||
### Changed
|
||||
|
||||
- 历史汇总只影响两个趋势图,不覆盖当前周质量或原始问答;关键词筛选不挪用无明细的历史汇总,所选截止后的数据不提前展示,缺失周留空。页面和完整PNG共用相同绘图数据。
|
||||
- 增加治理侧迁移57:历史统计独立表保留来源指纹与导入审计,禁止原位覆盖/删除,存在历史数据时拒绝破坏性down;普通来源同步不能覆盖该表,不修改DobotAI生产或既有冻结证据。
|
||||
|
||||
## 开发快照 snapshot/v0.1.36 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 管理员可独立配置、真实测试问答评估模型;字段分析与原问题译中支持单条/筛选范围预览、后台持久批次、暂停/恢复/失败重试、真实进度及逐字段依据与模型版本。自动处理默认关闭,首次启用排除历史,关闭暂停未开始任务并停止新增。
|
||||
- 原问题采用本地语种识别,排除型号、协议、URL与代码的干扰;中文直接复用原文,外语译中保留原始问题和既有人工译文。历史流程人员摘要保留原对象,并使用明确稳定身份与谨慎的唯一姓名兜底关联目录。
|
||||
|
||||
### Changed
|
||||
|
||||
- 全部问答看板与PNG改读独立正式总表的有效字段,保留旧源和冻结历史,不把历史标签伪装成人工复核。覆盖固定执行精确连续文本规则A,模型只补正式字典内四字段,`待确认`、`未知`及正确行合法空根因不重复排队。
|
||||
- 流水查询/同步区紧凑展示,移除两条指定技术提示与常驻本地库数量,保留真实失败和权限阻断;支持双击详情与固定浅底深字标签。新增治理侧迁移54–56,不修改DobotAI源库;新源事件结束后才首次收录,后续源更新或删除仍不覆盖总表。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 总表有效字段使用明确版本来源,前端不再用旧纯规则/人工契约拒绝历史与AI有效标签;原源数据契约和非空人工结论仍严格校验。
|
||||
- 历史导入记录允许管理员手动补缺,正常自动入场仍限新成功问答;持久重试保留累计尝试次数与固定分母,过期租约及输入/人工版本漂移阻止迟到结果覆盖。
|
||||
|
||||
### Security
|
||||
|
||||
- 独立主密钥加密存储、write-only服务密钥、管理员同源操作、乐观版本和幂等收据;不回显或默认复制Agent密钥,录入仅有效HTTPS/本机回环。模型请求保留公网地址校验、禁止重定向与证书校验,允许独立安全DNS适配Fake-IP而不放宽私网边界。
|
||||
- 调用只携带所需原问答/获准片段,不发送无关人员与部门;保持原始payload与历史非空业务值,不回写源生产库、不启动全历史处理或外部发送。
|
||||
|
||||
## 开发快照 snapshot/v0.1.33 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 问题流水读取治理侧独立正式总表,合并历史 Excel 与已收录的 2.0 问答;历史译文、答案、覆盖/正确标注、分类及人员字段保留原值,缺失不造值,来源可辨。
|
||||
- 新增受输入哈希、已批准逐行清单和真实恢复备份约束的历史导入命令,固定首表与提问时间/提问人/原始问题组合;保留批次、原字段、行号、重复跳过与缺字段暂缓证据。重复导入只读回收据,不覆盖后续主表修改。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理侧加表迁移 53。2.0 镜像仍独立同步,正式主表只接收新事件;稳定来源关联与原始事件键不随本地修改丢失,源端更新和删除不覆盖或清除主表。
|
||||
- 主表评估/复核与可替换的源副本分开持久化;首次收录保留已有评估及审计来源,后续人工复核绑定主表自身的输入版本,不被源同步失效。原 2.0 看板、历史冻结及周报统计范围不因导入被静默混算。
|
||||
|
||||
### Security
|
||||
|
||||
- 主表列表、详情、复核与历史接口复用固定租户、管理员会话、严格参数、同源写意图、乐观锁和幂等回执;拒绝缓存、稳定 ID 与原始溯源不可漂移。字段计数和质量范围只读标量元数据,不为全范围统计解压长答案。
|
||||
- 导入仅连接本地治理库,不连接或修改 DobotAI 2.0 生产源、现有隧道与外部表;应用回退保留加表,有历史导入、本地修改或新增复核时拒绝有损结构回退。
|
||||
|
||||
## 开发快照 snapshot/v0.1.32 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问题统计看板按参考布局提供完整十一项:2.0 累计问题、本周新增、覆盖率与正确率半环、问题类型饼图、产品横条排行、所选自然周逐日折线、区域平均使用频率与使用覆盖率、两条历史质量周趋势。未知分类保留为未分类,未知分母及历史缺失点不伪造为零。
|
||||
- 支持导出当前完整看板 PNG,包含所有图形、中文、图例与数值,独立于屏幕滚动高度;不包含导航、筛选控件、按钮或个人月明细。桌面与窄屏共享同一份数据及响应式图形。
|
||||
- 治理侧保存自然周质量冻结快照与逐条标量贡献;普通 worker 在符合采集条件的下一周一自动冻结上一周,保存实际时点、源观测、版本和分子分母。首次启用前、错过采集或没有完整观测的历史周保持空白,后续人工改判不回写已冻结比率。
|
||||
|
||||
### Changed
|
||||
|
||||
- 看板通过单一只读一致性接口聚合治理副本、有效质量与组织版本,不连接源端、不下载全部长答案;累计、所选自然周和截止月分别计算,原问题关键词按字面筛选。区域分母使用配置后的通讯录去重人数,仅用于使用统计,个人月明细与四页共享查询保留。
|
||||
- 新增加表迁移 52。应用回退保留加表;发现冻结历史时拒绝有损 down。未接入翻译/AI 评估模型、绩效名单、1.0 归档或自动发送。
|
||||
|
||||
### Security
|
||||
|
||||
- 统计接口维持固定租户、管理员会话、同源动作头、严格 JSON 和 no-store;输入指纹变化返回冲突,不混合新旧结论。数据库拒绝修改、删除或追加已提交的冻结贡献;浏览器查询不写指标,PNG 使用自包含 SVG,不加载外部图片或执行原始 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.31 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 区域配置支持新增、改名业务区域;稳定区域 ID 与部门映射同版本保存,改名不丢失归属。部门按一级、二级、三级及更深层级展示,支持层级/完整路径筛选、多选及批量归属。
|
||||
- 勾选、批量应用、预览和保存分离;取消本次勾选不删除既有映射,批量配置父部门不清除未选子部门的显式规则。预览核对去重人数,保存后独立读取并校验配置版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理库迁移 51,为历史区域修订补齐原四区目录;业务目录与映射原子留档,跨页问答、看板、使用统计、个人月明细和周报共用同一版本及名称。旧请求未传目录时沿用当前目录,不恢复固定四区白名单。
|
||||
- 迁移回退发现自定义区域历史时拒绝丢失目录;应用回退可保留加列迁移。统计人数不升级为在职或绩效分母,不改钉钉组织、DobotAI 原始数据及旧 Excel 流程。
|
||||
|
||||
### Security
|
||||
|
||||
- 配置请求拒绝缺失版本、重复 JSON 字段及嵌套 null;区域目录校验稳定 ID、重名及保留键,名称按文本展示,自定义名称不读取原型属性。保留管理员同源写入、租户隔离和双版本冲突保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.30 - 2026-10-18
|
||||
|
||||
### Changed
|
||||
|
||||
- 继续清理问答运营的冗余提示:质量统计移除完整范围留档、模型接入和读取时间说明;个人月明细移除重复的绩效/零记录解释及读取时间,保留实际数量、范围版本、分页和真实错误。质量统计按钮使用简短名称,不改统计与审计逻辑。
|
||||
|
||||
## 开发快照 snapshot/v0.1.29 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营调整为“问题流水、问题统计看板、区域配置、周报生成”四页,流水与看板共用年份、自然周和查询条件;区域页不再显示问题查询框,完整字段及人工复核入口保留。
|
||||
- 重做统计看板:展示完整筛选范围的问题量、覆盖率、正确率、人工复核、北京时间每日趋势、质量分布、区域、问题类型和产品分类;个人月明细折叠保留,未知分类与零分母不虚构结论。
|
||||
- 周报页提供手动草稿、Markdown 预览及 MD/完整明细 CSV 下载。核对副本版本、完整数量、质量范围与覆盖分布后生成;CSV 保留完整十五列并防护公式注入,不发送、不归档、不作为正式持久化周报验收。
|
||||
|
||||
### Changed
|
||||
|
||||
- 删除问答记录、同步栏和区域页中的冗余解释文字、读取时间与源连接提示,保留真实错误、未同步、权限阻断和安全告警。
|
||||
|
||||
## 开发快照 snapshot/v0.1.28 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营新增持久本地副本,每 5 分钟后台同步并支持立即同步;列表、详情、检索、质量范围和使用统计改为读取本地数据库。
|
||||
- AI 答案详情提供安全 Markdown 预览与原文查看,支持表格、代码块和链接;不执行原始 HTML,外部图片默认不请求。
|
||||
|
||||
### Changed
|
||||
|
||||
- 增加治理侧问答副本表与同步状态;同步由普通 worker 执行,使用独立只读源连接,源失败保留最后成功副本,权限校验失败阻断读取。
|
||||
- 副本激活与质量输入变化的复核失效同事务提交;同步持久去重、租约校验及重启恢复不改变源问答或现有生产写入。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 本地读取不再逐条重复写质量留档或解压完整范围长答案来统计字段,保留完整列、输入版本一致性和真实缺失值。
|
||||
- 初次观察即已同步完成时自动重查列表,避免较早的首次未同步错误一直停留。
|
||||
|
||||
## 开发快照 snapshot/v0.1.27 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -125,6 +125,16 @@ make list # 查看检查清单与适用范围
|
||||
|
||||
版本与变更见 [CHANGELOG](CHANGELOG.md),正式版本流程见 [发布 Runbook](docs/RELEASE_RUNBOOK.md)。`make version` 查看构建身份;日常开发构建与正式构建分开标识,软件版本 tag 不等同于知识发布批次。
|
||||
|
||||
## 问答运营模型配置
|
||||
|
||||
管理员在「系统设置 → 服务配置 → 问答评估模型」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
|
||||
|
||||
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
|
||||
|
||||
当本机代理的 Fake-IP DNS 导致公网端点被安全守卫拒绝时,可仅为这两个治理组件设置 `QA_AI_DNS_OVER_TLS=alidns`:通过证书验证的公共 DNS-over-TLS 解析,再按同样的公网 IP、HTTPS 和禁止重定向规则发请求;不修改系统 DNS、代理或隧道,不允许以启用私网访问替代修复。
|
||||
|
||||
问题流水支持先预览已执行筛选/单条范围,再创建持久后台批次;字段分析和原问题译中独立计数,仅补真正空白。暂停不撤回已发请求,共享任务若仍被另一活动批次需要会继续执行;恢复或重试失败项不扩大原批次分母。详情保留逐字段依据、模型/提示词版本及回填/跳过说明。自动处理首次启用排除历史,关闭暂停未开始的自动任务,重开恢复披露的增量积压;不因保存配置而全量外发。
|
||||
|
||||
## 后续方向
|
||||
|
||||
- 扩展多数据源调度与增量同步的覆盖范围。
|
||||
|
||||
+1069
-2
File diff suppressed because it is too large
Load Diff
+20
-1
@@ -20,8 +20,10 @@ import (
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/qawemail"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
@@ -31,10 +33,23 @@ import (
|
||||
// (见 compose.yaml 的 /data/dws 与文件型 keychain 挂载)——凭据只有一份。
|
||||
type dingtalkSourceLister struct{}
|
||||
|
||||
func (dingtalkSourceLister) ReadDWSMetadata(ctx context.Context) (dingtalkdiscovery.CredentialStatus, error) {
|
||||
return dingtalkdiscovery.ReadCredentialStatus(ctx, dingtalkdiscovery.ExecRunner{})
|
||||
}
|
||||
|
||||
func (dingtalkSourceLister) ListAvailableDingtalkSources(ctx context.Context) (dingtalkdiscovery.Result, error) {
|
||||
return dingtalkdiscovery.Discover(ctx, dingtalkdiscovery.ExecRunner{})
|
||||
}
|
||||
|
||||
// 同一份 dws 凭据也用来列在线文档/表格并校验可读。
|
||||
func (dingtalkSourceLister) ListDingtalkDocuments(ctx context.Context, query string, limit int) (dingtalkdiscovery.DocResult, error) {
|
||||
return dingtalkdiscovery.DiscoverDocs(ctx, dingtalkdiscovery.ExecRunner{}, query, limit)
|
||||
}
|
||||
|
||||
func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node string) (dingtalkdiscovery.DocumentNode, error) {
|
||||
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -137,7 +152,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL)
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL, pool)
|
||||
if closer, ok := qaReader.(interface{ Close() }); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
@@ -154,6 +169,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
|
||||
QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil),
|
||||
QAAITrustTLSProxy: getenv("QA_AI_TRUST_TLS_PROXY") == "true",
|
||||
QAQuality: qaopsquality.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY")),
|
||||
QAOrgSync: qaSyncStore,
|
||||
QAOrgSyncEnabled: qaSyncErr == nil && qaSyncSettings.Enabled,
|
||||
@@ -179,6 +197,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
ProductionReleaseAuthorizationToken: releaseAuthorizationToken,
|
||||
// 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。
|
||||
DingtalkSources: dingtalkSourceLister{},
|
||||
DingtalkDocuments: dingtalkSourceLister{},
|
||||
BackupSchedule: postgresstore.NewStore(pool),
|
||||
VersionHistory: versionHistoryStore,
|
||||
VersionHistoryRepo: versionHistoryRepo,
|
||||
|
||||
+12
-7
@@ -2,20 +2,25 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A failed optional source must not replace or take down the main database.
|
||||
func openQAOperations(ctx context.Context, getenv func(string) string, governanceDSN string) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
// API serving never constructs or probes a production-source client. The worker
|
||||
// alone synchronizes the explicitly authorized local copy; this is not a fallback.
|
||||
func openQAOperations(_ context.Context, getenv func(string) string, governanceDSN string, pool *pgxpool.Pool) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled || settings.Problem != "" {
|
||||
if !settings.Enabled {
|
||||
return nil, settings
|
||||
}
|
||||
client, err := dobotaiops.Build(ctx, settings.Connection)
|
||||
if err != nil {
|
||||
settings.Problem = "source_connection_or_permissions_failed"
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
settings.Problem = "local_mirror_tenant_invalid"
|
||||
return nil, settings
|
||||
}
|
||||
return client, settings
|
||||
// Missing/offline source credentials stop synchronization, not last-good local reads.
|
||||
settings.Problem = ""
|
||||
return qaopsmirror.NewStore(pool, settings.TenantKey), settings
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@ import (
|
||||
)
|
||||
|
||||
func TestQAOpsConnectionFailureIsContainedOutsideMainDatabase(t *testing.T) {
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance")
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance", nil)
|
||||
if reader != nil || settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("QA operations must be disabled by default")
|
||||
}
|
||||
env := map[string]string{"DOBOTAI_OPS_READ_ENABLED": "true", "DOBOTAI_OPS_TENANT_KEY": "approved-tenant", "DOBOTAI_OPS_READ_DSN_FILE": "/nonexistent-qaops-fixture-secret"}
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance")
|
||||
if reader != nil || !settings.Enabled || settings.Problem == "" {
|
||||
t.Fatal("failed external connection must be a contained module error")
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance", nil)
|
||||
if reader == nil || !settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("API serving still constructs a source connection instead of a local reader")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +56,10 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers)
|
||||
if mirrorErr != nil {
|
||||
log.Print("QA local mirror configuration invalid; handler was not registered")
|
||||
}
|
||||
worker, err := jobs.NewWorker(jobs.WorkerConfig{
|
||||
Queue: store,
|
||||
WorkerID: config.WorkerID,
|
||||
@@ -67,6 +71,13 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ai := configureQAProcessing(pool, getenv, config.DatabaseURL); ai != nil {
|
||||
go ai.Run(ctx, func(error) { log.Print("QA AI worker unavailable; durable work and original labels retained") })
|
||||
}
|
||||
if mirrorStore != nil {
|
||||
go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") })
|
||||
}
|
||||
go weeklyMailLoop(ctx, pool, getenv)
|
||||
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
|
||||
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
)
|
||||
|
||||
func configureQAProcessing(pool *pgxpool.Pool, getenv func(string) string, governanceDSN string) *qaopsai.Store {
|
||||
return qaopsai.NewFromEnvironment(pool, getenv, governanceDSN)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAIWorkerUsesIndependentGovernanceConfigurationWithoutOpeningSource(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
if configureQAProcessing(nil, get, "postgres://fixture@localhost/local") != nil {
|
||||
t.Fatal("disabled AI worker registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_READ_ENABLED"] = "true"
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-ai-worker"
|
||||
values["DOBOTAI_OPS_READ_DSN_FILE"] = "/nonexistent-fixture-source-secret"
|
||||
if configureQAProcessing(nil, get, "postgres://fixture@localhost/local") == nil {
|
||||
t.Fatal("AI worker still depends on source availability or was not registered")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type recordsSyncSchedulerStore interface {
|
||||
EnqueueDue(context.Context) (bool, error)
|
||||
TrackQualityWeeks(context.Context, time.Time) error
|
||||
FreezePreviousQualityWeek(context.Context, time.Time) (bool, error)
|
||||
}
|
||||
|
||||
func runRecordsSyncCycle(ctx context.Context, store recordsSyncSchedulerStore, at time.Time) error {
|
||||
_, syncErr := store.EnqueueDue(ctx)
|
||||
trackingErr := store.TrackQualityWeeks(ctx, at)
|
||||
if trackingErr != nil {
|
||||
return errors.Join(syncErr, trackingErr)
|
||||
}
|
||||
_, freezeErr := store.FreezePreviousQualityWeek(ctx, at)
|
||||
return errors.Join(syncErr, freezeErr)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type frozenScheduleSpy struct {
|
||||
calls []string
|
||||
trackErr error
|
||||
}
|
||||
|
||||
func (s *frozenScheduleSpy) EnqueueDue(context.Context) (bool, error) {
|
||||
s.calls = append(s.calls, "sync")
|
||||
return true, nil
|
||||
}
|
||||
func (s *frozenScheduleSpy) TrackQualityWeeks(context.Context, time.Time) error {
|
||||
s.calls = append(s.calls, "track")
|
||||
return s.trackErr
|
||||
}
|
||||
func (s *frozenScheduleSpy) FreezePreviousQualityWeek(context.Context, time.Time) (bool, error) {
|
||||
s.calls = append(s.calls, "freeze")
|
||||
return true, nil
|
||||
}
|
||||
func TestRecordsSchedulerActuallyCapturesFrozenWeeklyMetrics(t *testing.T) {
|
||||
s := &frozenScheduleSpy{}
|
||||
if e := runRecordsSyncCycle(context.Background(), s, time.Now()); e != nil || !reflect.DeepEqual(s.calls, []string{"sync", "track", "freeze"}) {
|
||||
t.Fatal("weekly capture is not on the real scheduler invocation path", e, s.calls)
|
||||
}
|
||||
broken := &frozenScheduleSpy{trackErr: errors.New("isolated tracking unavailable")}
|
||||
if e := runRecordsSyncCycle(context.Background(), broken, time.Now()); e == nil || !reflect.DeepEqual(broken.calls, []string{"sync", "track"}) {
|
||||
t.Fatal("snapshot failure must not suppress source sync or freeze untracked history")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configureRecordsSync(pool *pgxpool.Pool, getenv func(string) string, governanceDSN string, handlers map[string]jobs.Handler) (*qaopsmirror.Store, error) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
return nil, qaopsmirror.ErrInvalid
|
||||
}
|
||||
store := qaopsmirror.NewStore(pool, settings.TenantKey)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleSync(ctx, job, func(ctx context.Context) (qaopsmirror.Source, error) {
|
||||
current := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !current.Enabled || current.Problem != "" || current.TenantKey != settings.TenantKey {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
// One source connection, shared by every manifest and bounded payload read in this job.
|
||||
current.Connection.MaxConns = 1
|
||||
current.Connection.MinConns = 0
|
||||
return dobotaiops.Build(ctx, current.Connection)
|
||||
})
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// The next due time and automatic operation key live in PostgreSQL, so a worker
|
||||
// restart does not reset the five-minute cadence or duplicate an active import.
|
||||
func runRecordsSyncScheduler(ctx context.Context, store *qaopsmirror.Store, onError func(error)) {
|
||||
tick := time.NewTicker(15 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if e := runRecordsSyncCycle(ctx, store, time.Now()); e != nil && ctx.Err() == nil && onError != nil {
|
||||
onError(e)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLocalMirrorWorkerRegistrationNeverConnectsSource(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
handlers := map[string]jobs.Handler{}
|
||||
if store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers); e != nil || store != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled mirror registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_READ_ENABLED"] = "true"
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-worker-tenant"
|
||||
values["DOBOTAI_OPS_READ_DSN_FILE"] = "/nonexistent-fixture-source-secret"
|
||||
store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers)
|
||||
if e != nil || store == nil || handlers[qaopsmirror.NewStore(nil, "fixture-worker-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("local mirror handler missing; registration must not connect to source", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/qawemail"
|
||||
)
|
||||
|
||||
// weeklyMailLoop sends the confirmed weekly report exactly inside the configured slot.
|
||||
// It runs in the ordinary worker so the console never depends on a browser staying open.
|
||||
func weeklyMailLoop(ctx context.Context, pool *pgxpool.Pool, getenv func(string) string) {
|
||||
tenant := getenv("DOBOTAI_OPS_TENANT_KEY")
|
||||
if tenant == "" {
|
||||
log.Print("weekly mail disabled: tenant key not configured")
|
||||
return
|
||||
}
|
||||
store := qawemail.NewStore(pool, tenant, getenv("QA_AI_MASTER_KEY_FILE"), nil)
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
lastState := ""
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
result, err := store.SendDue(runCtx, time.Now())
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("weekly mail attempt failed: %v", err)
|
||||
continue
|
||||
}
|
||||
if result.State != lastState {
|
||||
lastState = result.State
|
||||
log.Printf("weekly mail state=%s week=%s reason=%s", result.State, result.Week, result.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,10 @@ services:
|
||||
VERSION_HISTORY_LINK_ORIGIN: "${VERSION_HISTORY_LINK_ORIGIN:-}"
|
||||
VERSION_HISTORY_HTTP_TIMEOUT: "${VERSION_HISTORY_HTTP_TIMEOUT:-15s}"
|
||||
VERSION_HISTORY_MAX_PAGES: "${VERSION_HISTORY_MAX_PAGES:-200}"
|
||||
# Mount this independent master-key file read-only using the deployment overlay.
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
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.
|
||||
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
|
||||
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
|
||||
@@ -99,6 +103,8 @@ services:
|
||||
environment:
|
||||
<<: *app-environment
|
||||
WORKER_ID: worker-1
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
PP_SCAN_ENABLED: "${PP_SCAN_ENABLED:-false}"
|
||||
PP_SCAN_ALLOWED_ROOT: "${PP_SCAN_CONTAINER_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}"
|
||||
PP_SCAN_LEDGER_PATH: "${PP_SCAN_CONTAINER_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}/public-weknora-sync/state.jsonl"
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# 知识库级版本同步:开发与验收清单
|
||||
|
||||
## 交付边界
|
||||
|
||||
本清单记录已确认需求与验收条件,不表示功能已实现。日常编辑按文档,生产版本及恢复按知识库完整状态;发布管理仅有对内、对外两个目标。开发授权不包含生产同步、生产恢复或真实数据清理。生产执行仍须在发布管理经管理员授权;保留数量、天数、容量预算未设置,自动清理默认关闭。
|
||||
|
||||
现有文档包发布与执行级补偿只能作为复用基础,不能作为本清单完成证据。静态样图不作为产品运行证据。组织绩效与周报外发不在本次范围。
|
||||
|
||||
## 已确认:封存隔离方案 A
|
||||
|
||||
用户选择封存期间自动暂停测试 WeKnora 服务,封存后恢复,不修改 WeKnora 源码。测试问答在暂停期间暂不可用,停用时长须实测;不暂停生产服务,也不因此取得生产同步、恢复或真实清理授权。
|
||||
|
||||
实现要求:先等待处理任务完成,枚举并核实全部测试写入者和副本;暂停后重新检查状态,数据库、索引和对象存储保持可读。持久记录暂停前运行状态及作业归属,覆盖成功、失败、取消和进程重启后的恢复;仅恢复本作业暂停的服务,并读回服务健康。完整归档封存后即可恢复测试服务,后续生产传输从归档读取,不延长测试停用时间。
|
||||
|
||||
方案已确认不等于暂停/恢复功能已实现;恢复保障验证前不停止运行中的测试服务。
|
||||
|
||||
## 开发与测试顺序
|
||||
|
||||
1. 核查实际 WeKnora 的文档删除、Wiki 更新与完成信号,以及跨数据库、对象、索引的快照与恢复契约。
|
||||
2. 实现完整版本清单、一致性校验、授权与持久化作业;逐项运行失败用例再实现通过。
|
||||
3. 接通实际导出、独立生产预备份、传输、验证、恢复及持久化进度;隔离环境演练故障、重启与重试。
|
||||
4. 发布管理接真实接口,存储管理接真实测量及依赖保护;验证浏览器交互与权限。
|
||||
5. 完整回归、审查、提交交付;生产实测单列等待授权,不以隔离验收代替。
|
||||
|
||||
## 验收项目
|
||||
|
||||
| ID | 范围 | 必须证明的行为 | 状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| V01 | 两个目标 | 只按对内、对外操作;身份来自已配置映射,不按名称猜测 | 待验证 |
|
||||
| V02 | 测试就绪 | 全部解析、索引及 Wiki 就绪;问答与性能验收绑定本版,旧验收不能放行新变化 | 待验证 |
|
||||
| V03 | Wiki 撤销 | 删除文档后验证共享正文、实体、概念、边与引用的实际变化;删除成功或引用剥离不能代替此证据 | 待验证 |
|
||||
| V04 | 完整固定版本 | 清单覆盖文档集合、处理结果、资源、索引、完整 Wiki;无部分文档配整库 Wiki 的路径 | 待验证 |
|
||||
| V05 | 并发修改 | 导出中发生源变更时拒绝不一致版本,或由已证明的固定快照协议隔离;导出前后表面计数相同不算充分证明 | 待验证 |
|
||||
| V06 | 内容范围 | 仅允许知识数据;账号、会话、凭据及无关知识库不被同步或恢复 | 待验证 |
|
||||
| B01 | 写前预备份 | 每次生产变更前创建旧状态完整备份,校验恢复资料完整性;失败时零生产知识写入 | 待验证 |
|
||||
| B02 | 独立恢复依赖 | 资源在测试侧删除后,保留版本仍能恢复,不依赖测试临时对象或短期签名地址 | 待验证 |
|
||||
| B03 | 完整 Wiki 资产 | 每版保存完整 Wiki 及引用关联,校验摘要、数量和版本绑定 | 待验证 |
|
||||
| S01 | 数据同步 | 数据库、资源、索引、Wiki 均真实落地并校验,增量仅为传输优化 | 待验证 |
|
||||
| S02 | 无生产再计算 | 生产侧不解析、Embedding 或生成 Wiki,使用测试验收结果 | 待验证 |
|
||||
| S03 | 一致生效 | 不宣称不存在的跨系统原子性;明确可见性保护、失败补偿与验证边界 | 待验证 |
|
||||
| S04 | 故障与恢复 | 各阶段失败、超时与进程重启后可追溯、可恢复,不重复破坏性动作 | 待验证 |
|
||||
| S05 | 幂等与互斥 | 重复请求不启动重复同步;同目标同步、恢复、清理之间互斥;不同请求体复用键被拒绝 | 待验证 |
|
||||
| R01 | 版本恢复 | 恢复生产整套文档、资源、索引与 Wiki;测试知识库不回退 | 待验证 |
|
||||
| R02 | 恢复失败 | 不标记成功、不丢旧恢复依据,明确受影响阶段及后续可执行措施 | 待验证 |
|
||||
| R03 | 速度 | 分开实测备份与恢复耗时、数据量、吞吐及环境;未经测量不承诺快速 | 待验证 |
|
||||
| P01 | 作业阶段 | 持久化准备、备份、同步、验证、恢复阶段与开始/更新时间、错误;生产验证成功才完成 | 待验证 |
|
||||
| P02 | 四类进度 | 数据库记录、资源文件/字节、索引分块、Wiki 页面/关联数据来自实际测量;总量未知不造百分比 | 待验证 |
|
||||
| P03 | 明细 | 可查看实际对象、数量、字节、校验及异常;筛选与总量不依赖前端当前页 | 待验证 |
|
||||
| U01 | 主要入口 | 对内/对外切换、启动同步、版本与快照、当前作业预备份入口均可见;旧版历史可追溯 | 待验证 |
|
||||
| U02 | 权限 | 未就绪明确阻断原因;会话注入操作者;只读/工程师不能获得生产执行权限 | 待验证 |
|
||||
| U03 | 操作确认 | 启动、恢复显示准确目标及影响并保留授权;运行中禁止重复启动 | 待验证 |
|
||||
| D01 | 存储策略 | 未设阈值如实显示未设置,自动清理默认关闭,不隐含年龄删除 | 待验证 |
|
||||
| D02 | 占用测量 | 区分逻辑大小、独占、共享、实际占用;无法测量显示未知,不当成零 | 待验证 |
|
||||
| D03 | 保护引用 | 当前恢复依据、活跃作业、锁定/保留版本及共享资源受到保护 | 待验证 |
|
||||
| D04 | 清理预览 | 列明对象、依赖、受影响版本及可测释放量;执行前重新核验引用与活跃作业 | 待验证 |
|
||||
| D05 | 容量门禁 | 空间不足告警或阻断,不为继续作业偷删受保护备份 | 待验证 |
|
||||
| D06 | 测试残留 | 覆盖取件缓存、临时解析、同步暂存、失败上传、删除/重解析残留,不删除源文件 | 待验证 |
|
||||
| D07 | 实际回收 | 区分逻辑删除与实际释放,核查对象历史版本/分片及数据库、索引回收;保留版本清理后仍可恢复 | 待验证 |
|
||||
|
||||
## 证据登记规则
|
||||
|
||||
每项完成需附实现位置、运行命令与退出码、可回看的证据路径、验证环境及尚未覆盖范围。单元测试、隔离数据库集成、模拟外部服务、真实测试知识库、生产验收分别标注,不能相互替代。
|
||||
|
||||
真实清理和生产恢复尚未授权的项目保持待授权/待验证;不得为了打勾执行。整项范围未覆盖不得以子切片通过称为本阶段完成。
|
||||
|
||||
## 已运行的基础模块证据(不等于整体验收)
|
||||
|
||||
实现位置:`internal/librarysnapshot/` 与 `internal/releaseadapter/v071/library_*.go`。
|
||||
|
||||
- PostgreSQL 整库只读 Repeatable Read 导出:显式包含空 Wiki 表;未完成解析、删除文档残留任务、死信、未知 schema、Neo4j 启用场景拒绝自动放行。
|
||||
- Elasticsearch 使用 PIT 与 search_after,核查精确总量、返回范围、重复项与部分结果;PIT 只证明索引自身的视图。
|
||||
- 候选归档独立持有资源字节,校验表、scope、资源依赖、索引关联及摘要;内容寻址复用、重开加载、同一文件描述符校验读取、共享/独占引用字节已测试。引用字节不是物理占用或实际可回收字节。
|
||||
- `go test -race ./internal/librarysnapshot ./internal/releaseadapter/v071 -count=1`:退出码 0;默认跳过需要显式配置的隔离集成,不能据此声称集成通过。
|
||||
- 隔离 PostgreSQL + Elasticsearch 集成另行运行,退出码 0。只创建随机 `kg_library_test_` 前缀夹具;结束后 PostgreSQL 同前缀库残留计数为 0。
|
||||
- MVCC 反向自检:仅通过 Go overlay 把 Repeatable Read 改为 Read Committed,同一真实隔离集成退出码 1,失败断言为 `mixed PostgreSQL versions during export`。原始实现复跑退出码 0。
|
||||
- `make verify`:退出码 0。本地门禁不是远端 CI,也不是新 UI 或真实知识库完整验收。
|
||||
|
||||
证据保存在本机仓库忽略目录 `backups/library-sync-foundation-20261027/`:`unit-tests.jsonl`、`kg-library-integration.log`、`kg-library-mvcc-negative.log`、`kg-library-verify.log`。隔离执行脚本副本同目录留存,不含静态凭据;运行时从本地测试容器读取。
|
||||
|
||||
### 当前不能放行的边界
|
||||
|
||||
1. `ArchiveLibraryCandidate` 的 seal 只代表归档完整性,不代表跨系统同一时点、Wiki 语义验收通过或生产授权。尚未接到生产执行器。
|
||||
2. 数据库 MVCC 与 ES PIT 是各自独立的快照,不能把两者拼接视为一致整版。用户已确认方案 A:封存期间自动暂停测试服务;全部写入者隔离、异常恢复及实际停用时长尚待实现与验证,不修改 WeKnora 源码,不暂停生产。
|
||||
3. 已检查本地 v0.7.1 源码:`EnqueueWikiRetract` 在持久化 pending op 失败时记录警告后返回;因此 pending/dead-letter 都为空仍不证明撤销语义已处理。必须补充删除后共享 Wiki 内容的实测与验收绑定。
|
||||
4. 生产预备份、独立恢复演练、持久化协调作业、授权 API、真实进度、发布页面与完整存储治理仍未交付;以上验收项目保持待验证。
|
||||
5. 基础模块已随 `0.1.96 / 9105f8316cc870a62b5ddacd1496f0cb0f798d87` 提交、推送并部署到本地测试治理平台;运行 API/worker 的二进制摘要已读回校验。该部署不等于业务功能接线或完整验收通过;未执行生产同步、恢复或真实业务清理。完整验收仍受本节及下述缺失接线阻塞。
|
||||
|
||||
## 方案 A:暂停与恢复原语的实测证据
|
||||
|
||||
新增 `internal/libraryfreeze/`,包含持久化作业日志、源服务组互斥、暂停前原运行状态、不可变容器 ID、恢复读回,以及本地 Unix socket Docker 控制器。Docker 控制器只接受对应 source 且 `environment=test`、`freeze-role=writer` 的容器;不按模糊名称选取,不控制数据库/索引存储,不使用远程默认 Docker context。运行容器必须有健康检查。
|
||||
|
||||
已经执行的验证:
|
||||
|
||||
- `go test -race ./internal/libraryfreeze ./internal/librarysnapshot ./internal/releaseadapter/v071 -count=1`,退出码 0。
|
||||
- `KG_FREEZE_DOCKER_ISOLATED=1 go test -race -v ./internal/libraryfreeze -run '^TestFreezeIsolatedDocker$' -count=1`,退出码 0。使用已缓存 busybox 创建随机标签、无网络、无宿主挂载的一次性容器,真实验证停止→捕获窗口→重启健康、原本停止容器不启动;控制子进程在停止后退出,再由新恢复调用读持久日志启动原容器。清理后按标签读回无残留。
|
||||
- 异常覆盖:停止回包丢失、停止未生效、新副本出现、容器被替换、捕获错误/panic/取消、日志写入失败、恢复健康失败、畸形日志、同源并发及重复恢复。捕获 panic 和日志失写故障先实际报红,修复后通过。
|
||||
- 不使用有延迟强杀计时器的停止方式;仅发送 SIGTERM 并等待实际停止。若停止结果不明且服务仍运行,不把“现在运行”误判为已恢复,日志保持待恢复,防止随后迟到的停止把服务留在关闭状态。
|
||||
- 新增 Docker 集成用例已在 `scripts/test-scope.json` 精确声明 opt-in;普通 CI 明确跳过,不冒称执行。完整 `make verify` 退出码 0,属于本地门禁。
|
||||
|
||||
证据:本机 `backups/library-sync-foundation-20261027/kg-freeze-docker-integration.log`、`kg-library-freeze-verify.log`。
|
||||
|
||||
已新增 `internal/releaseadapter/v071/library_capture.go`,在源服务组互斥下串起预检、暂停、停后复检、PG/ES 导出、独立归档和恢复。协调测试使用 PG/服务控制夹具与 HTTP 搜索夹具,覆盖预检忙时零停止、暂停前后新增任务阻断、搜索失败恢复、旧作业重放不重新暂停、跨 scope 复用拒绝、归档丢失不返回成功;不把这组夹具当成实际业务知识库全链路验收。最终竞态回归、隔离 Docker 重跑与 `make verify` 均退出码 0,最终日志为同目录 `kg-freeze-docker-final.log`、`kg-library-freeze-final-verify.log`。
|
||||
|
||||
**仍缺少的接线**:真实测试部署的全部写入者枚举及标签/健康契约、全源任务就绪检查的实际提供方、worker 调用捕获协调函数、启动恢复入口和持续恢复调度。单独的本地 Docker 控制器不能控制远端测试主机;远端场景需在测试主机运行受限执行器,不能向浏览器或普通 API 暴露 Docker socket。上述测试不能证明这些接线已完成,尚未暂停实际测试 WeKnora。
|
||||
@@ -29,6 +29,7 @@ require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/yuin/goldmark v1.7.4 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
|
||||
@@ -52,6 +52,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/yuin/goldmark v1.7.4 h1:BDXOHExt+A7gwPCJgPIIq7ENvceR7we7rOS9TNoLZeg=
|
||||
github.com/yuin/goldmark v1.7.4/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CredentialStatus contains metadata only, never credential values.
|
||||
type CredentialStatus struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at,omitempty"`
|
||||
}
|
||||
|
||||
func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) {
|
||||
raw, err := runner.RunDWS(ctx, "auth", "status", "--readonly", "--format", "json")
|
||||
if err != nil {
|
||||
return CredentialStatus{}, errors.New("could not read DWS credential status")
|
||||
}
|
||||
var decoded struct {
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
}
|
||||
if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil {
|
||||
return CredentialStatus{}, errors.New("invalid DWS credential status")
|
||||
}
|
||||
return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCredentialStatusReadOnlyMetadata(t *testing.T) {
|
||||
key := "auth status --readonly --format json"
|
||||
runner := &fakeRunner{responses: map[string]string{key: `{"authenticated":true,"refresh_token_valid":true,"expires_at":"2026-10-26T20:21:10+08:00","refresh_expires_at":"2026-11-25T18:21:10+08:00","access_token":"not-a-real-secret"}`}}
|
||||
result, err := ReadCredentialStatus(context.Background(), runner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !result.Authenticated || !result.RefreshTokenValid || len(runner.seen) != 1 || runner.seen[0] != key {
|
||||
t.Fatalf("unexpected status or command: %+v %+v", result, runner.seen)
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
if strings.Contains(string(raw), "not-a-real-secret") || strings.Contains(string(raw), "access_token") {
|
||||
t.Fatal("credential leaked")
|
||||
}
|
||||
}
|
||||
func TestCredentialStatusRejectsUnknownOutput(t *testing.T) {
|
||||
_, err := ReadCredentialStatus(context.Background(), &fakeRunner{})
|
||||
if err == nil {
|
||||
t.Fatal("missing authentication field accepted")
|
||||
}
|
||||
}
|
||||
func TestCredentialStatusLoggedOut(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{"auth status --readonly --format json": `{"authenticated":false}`}}
|
||||
got, err := ReadCredentialStatus(context.Background(), runner)
|
||||
if err != nil || got.Authenticated {
|
||||
t.Fatalf("%+v %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DocumentNode 是一篇钉钉在线文档/表格,用于「钉钉文档·表格」这一类数据源:
|
||||
// 它不在知识库、也不在钉盘的目录树里,只能按节点单独登记。
|
||||
type DocumentNode struct {
|
||||
NodeID string `json:"node_id"`
|
||||
NodeType string `json:"node_type"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
ContentType string `json:"content_type"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// DocResult 是一次文档发现的结果。Notice 说明「为什么没列全」,不把失败伪装成空列表。
|
||||
type DocResult struct {
|
||||
Documents []DocumentNode `json:"documents"`
|
||||
Notice string `json:"notice,omitempty"`
|
||||
FetchedAt time.Time `json:"fetched_at"`
|
||||
}
|
||||
|
||||
// RecentDocsArgs 列出最近编辑的文档;没有关键词时的默认入口。
|
||||
func RecentDocsArgs(limit int) []string {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
return []string{"drive", "+recent", "--operate-type", "1", "--limit", "20", "--page-all",
|
||||
"--max-items", fmt.Sprint(limit), "--max-pages", "10"}
|
||||
}
|
||||
|
||||
// SearchDocsArgs 按关键词在文档空间检索。
|
||||
func SearchDocsArgs(query string, limit int) []string {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
return []string{"drive", "+search-docs", "--query", query, "--limit", fmt.Sprint(limit)}
|
||||
}
|
||||
|
||||
// DocInfoArgs / SheetListArgs 是校验「这篇还能不能读」的只读命令:
|
||||
// 文档取元信息,表格取工作表清单——都真实打一次接口,不用缓存谎报可读。
|
||||
func DocInfoArgs(node string) []string { return []string{"doc", "info", "--node", node} }
|
||||
func SheetListArgs(node string) []string { return []string{"sheet", "list", "--node", node} }
|
||||
|
||||
// IsSheet 判断节点是否表格:表格要用 sheet 校验,文档用 doc。
|
||||
func IsSheet(contentType string) bool {
|
||||
kind := strings.ToUpper(strings.TrimSpace(contentType))
|
||||
return strings.Contains(kind, "SHEET") || strings.Contains(kind, "ABLE")
|
||||
}
|
||||
|
||||
// DiscoverDocs 枚举可登记的在线文档:有关键词就检索,没有就给最近编辑的一批。
|
||||
// 与 Discover 一样,读不到就返回 ErrUnavailable,而不是空结果。
|
||||
func DiscoverDocs(ctx context.Context, runner Runner, query string, limit int) (DocResult, error) {
|
||||
result := DocResult{FetchedAt: time.Now().UTC()}
|
||||
args := RecentDocsArgs(limit)
|
||||
if trimmed := strings.TrimSpace(query); trimmed != "" {
|
||||
args = SearchDocsArgs(trimmed, limit)
|
||||
}
|
||||
raw, err := runner.RunDWS(ctx, args...)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
docs, notice, err := parseDocs(raw)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
result.Documents, result.Notice = docs, notice
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ValidateDocument 真实读一次节点,返回它的规范元信息;读不到就是不可登记。
|
||||
func ValidateDocument(ctx context.Context, runner Runner, node string) (DocumentNode, error) {
|
||||
node = strings.TrimSpace(node)
|
||||
if node == "" {
|
||||
return DocumentNode{}, fmt.Errorf("%w: empty node", ErrUnavailable)
|
||||
}
|
||||
raw, err := runner.RunDWS(ctx, DocInfoArgs(node)...)
|
||||
if err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
doc, err := parseDocInfo(raw)
|
||||
if err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
if doc.NodeID == "" {
|
||||
doc.NodeID = node
|
||||
}
|
||||
if IsSheet(doc.ContentType) {
|
||||
if _, err := runner.RunDWS(ctx, SheetListArgs(doc.NodeID)...); err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("%w: %s", ErrUnavailable, err.Error())
|
||||
}
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// parseDocs 解析 `drive +recent` / `drive +search-docs`:
|
||||
// {"ok":true,"data":{"items":[{nodeId,nodeType,name,docUrl,contentType,accessTime}]}}
|
||||
// 第二个返回值是「结果不完整」的说明(服务端还有下一页或条目被截断)。
|
||||
func parseDocs(raw []byte) ([]DocumentNode, string, error) {
|
||||
var payload struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Count int `json:"count"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
Items []struct {
|
||||
NodeID string `json:"nodeId"`
|
||||
NodeType string `json:"nodeType"`
|
||||
Name string `json:"name"`
|
||||
DocURL string `json:"docUrl"`
|
||||
ContentType string `json:"contentType"`
|
||||
AccessTime string `json:"accessTime"`
|
||||
} `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return nil, "", fmt.Errorf("decode docs: %w", err)
|
||||
}
|
||||
if !payload.OK {
|
||||
return nil, "", errors.New("docs listing reported failure")
|
||||
}
|
||||
out := make([]DocumentNode, 0, len(payload.Data.Items))
|
||||
seen := map[string]bool{}
|
||||
for _, item := range payload.Data.Items {
|
||||
id := strings.TrimSpace(item.NodeID)
|
||||
if id == "" || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
nodeType := strings.TrimSpace(item.NodeType)
|
||||
if nodeType == "" {
|
||||
nodeType = "file"
|
||||
}
|
||||
out = append(out, DocumentNode{
|
||||
NodeID: id,
|
||||
NodeType: nodeType,
|
||||
Name: strings.TrimSpace(item.Name),
|
||||
URL: strings.TrimSpace(item.DocURL),
|
||||
ContentType: strings.TrimSpace(item.ContentType),
|
||||
UpdatedAt: strings.TrimSpace(item.AccessTime),
|
||||
})
|
||||
}
|
||||
notice := ""
|
||||
if payload.Data.HasMore {
|
||||
notice = fmt.Sprintf("只列出前 %d 篇,还有更多;用关键词检索可以找到其余的。", len(out))
|
||||
}
|
||||
return out, notice, nil
|
||||
}
|
||||
|
||||
// parseDocInfo 解析 `dws doc info --node`。服务端字段是 camelCase,部分历史响应是
|
||||
// snake_case,两种都认,避免因为命名差异把可读文档判成不可读。
|
||||
func parseDocInfo(raw []byte) (DocumentNode, error) {
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return DocumentNode{}, fmt.Errorf("decode doc info: %w", err)
|
||||
}
|
||||
if ok, present := payload["ok"].(bool); present && !ok {
|
||||
return DocumentNode{}, errors.New("doc info reported failure")
|
||||
}
|
||||
source := payload
|
||||
if data, ok := payload["data"].(map[string]any); ok {
|
||||
source = data
|
||||
}
|
||||
pick := func(keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if value, ok := source[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
doc := DocumentNode{
|
||||
NodeID: pick("nodeId", "node_id", "dentUuid", "dentryUuid", "id"),
|
||||
NodeType: pick("nodeType", "node_type"),
|
||||
Name: pick("name", "title", "docName"),
|
||||
URL: pick("docUrl", "doc_url", "url"),
|
||||
ContentType: pick("contentType", "content_type", "extension"),
|
||||
UpdatedAt: pick("updateTime", "updatedAt", "modifiedTime"),
|
||||
}
|
||||
if doc.NodeType == "" {
|
||||
doc.NodeType = "file"
|
||||
}
|
||||
if doc.Name == "" {
|
||||
return DocumentNode{}, errors.New("doc info has no title")
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const recentDocsFixture = `{"ok":true,"data":{"count":2,"hasMore":false,"items":[
|
||||
{"nodeId":"node-a","nodeType":"file","name":"售后周会纪要","docUrl":"https://alidocs.dingtalk.com/i/nodes/node-a","contentType":"ALIDOC","accessTime":"2026-10-25T10:00:00Z"},
|
||||
{"nodeId":"node-b","nodeType":"file","name":"服务工单统计","docUrl":"https://alidocs.dingtalk.com/i/nodes/node-b","contentType":"ALISHEET","accessTime":"2026-10-24T09:00:00Z"}]}}`
|
||||
|
||||
func TestDiscoverDocsListsRecentDocumentsWithTheirType(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{strings.Join(RecentDocsArgs(50), " "): recentDocsFixture}}
|
||||
result, err := DiscoverDocs(context.Background(), runner, "", 50)
|
||||
if err != nil {
|
||||
t.Fatalf("discover docs: %v", err)
|
||||
}
|
||||
if len(result.Documents) != 2 {
|
||||
t.Fatalf("documents = %d, want 2", len(result.Documents))
|
||||
}
|
||||
// 文档与表格必须能区分:表格要走 sheet 校验,文档走 doc。
|
||||
if got := result.Documents[1]; got.ContentType != "ALISHEET" || !IsSheet(got.ContentType) {
|
||||
t.Fatalf("sheet node not recognised: %+v", got)
|
||||
}
|
||||
if IsSheet(result.Documents[0].ContentType) {
|
||||
t.Fatal("an ALIDOC document must not be treated as a sheet")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDocsSearchesByKeywordWhenOneIsGiven(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{strings.Join(SearchDocsArgs("周会", 50), " "): recentDocsFixture}}
|
||||
if _, err := DiscoverDocs(context.Background(), runner, " 周会 ", 50); err != nil {
|
||||
t.Fatalf("search docs: %v", err)
|
||||
}
|
||||
if got := runner.seen[0]; !strings.Contains(got, "+search-docs") || !strings.Contains(got, "--query 周会") {
|
||||
t.Fatalf("keyword search was not used: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDocsReportsUnavailableInsteadOfAnEmptyList(t *testing.T) {
|
||||
runner := &fakeRunner{failures: map[string]error{strings.Join(RecentDocsArgs(50), " "): errors.New("token expired")}}
|
||||
if _, err := DiscoverDocs(context.Background(), runner, "", 50); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("want ErrUnavailable, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDocumentAsksForSheetSheetsWhenTheNodeIsATable(t *testing.T) {
|
||||
runner := &fakeRunner{responses: map[string]string{
|
||||
strings.Join(DocInfoArgs("node-b"), " "): `{"ok":true,"data":{"nodeId":"node-b","name":"服务工单统计","contentType":"ALISHEET"}}`,
|
||||
strings.Join(SheetListArgs("node-b"), " "): `{"ok":true,"data":{"sheets":[{"sheetId":"s1","name":"10月"}]}}`,
|
||||
}}
|
||||
doc, err := ValidateDocument(context.Background(), runner, "node-b")
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if doc.Name != "服务工单统计" {
|
||||
t.Fatalf("name = %q", doc.Name)
|
||||
}
|
||||
if len(runner.seen) != 2 || !strings.HasPrefix(runner.seen[1], "sheet list") {
|
||||
t.Fatalf("a table must be verified with sheet list, calls = %v", runner.seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDocumentRejectsUnreadableNodes(t *testing.T) {
|
||||
runner := &fakeRunner{failures: map[string]error{strings.Join(DocInfoArgs("node-x"), " "): errors.New("404")}}
|
||||
if _, err := ValidateDocument(context.Background(), runner, "node-x"); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("want ErrUnavailable, got %v", err)
|
||||
}
|
||||
if _, err := ValidateDocument(context.Background(), runner, " "); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal("an empty node must not validate")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var QualityFilterKeys = []string{"coverage", "is_correct", "product_category", "problem_type", "root_cause"}
|
||||
|
||||
func ValidQualityFilters(filters map[string]string) bool {
|
||||
if len(filters) > 5 {
|
||||
return false
|
||||
}
|
||||
for key, value := range filters {
|
||||
found := false
|
||||
for _, allowed := range QualityFilterKeys {
|
||||
if key == allowed {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found || value == "" || !utf8.ValidString(value) || utf8.RuneCountInString(value) > 200 || strings.ContainsRune(value, 0) {
|
||||
return false
|
||||
}
|
||||
if value == "__empty__" {
|
||||
continue
|
||||
}
|
||||
if key == "coverage" && value != "是" && value != "否" && value != "否但不计入" && value != "部分覆盖" && value != "待确认" {
|
||||
return false
|
||||
}
|
||||
if key == "is_correct" && value != "是" && value != "否" && value != "待确认" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dobotaiops
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMasterCoverageUsesExactMarkerAndNonemptySuccessfulRead(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
answer string
|
||||
available bool
|
||||
want string
|
||||
}{{"已有资料", true, "covered"}, {"包含暂无已发布的资料", true, "uncovered"}, {"暂 无已发布", true, "covered"}, {"", true, ""}, {" \n", true, ""}, {"已有资料", false, ""}} {
|
||||
got := CheckMasterCoverage(c.answer, c.available)
|
||||
if got.Verdict != c.want {
|
||||
t.Errorf("available=%v verdict=%q want=%q", c.available, got.Verdict, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxMirrorRecords = 100000
|
||||
const mirrorFingerprintSQL = `encode(sha256(convert_to((payload-'_quality_observed_at')::text,'UTF8')),'hex')`
|
||||
|
||||
type MirrorKey struct {
|
||||
ID string
|
||||
Fingerprint string
|
||||
}
|
||||
type MirrorManifest struct {
|
||||
Keys []MirrorKey
|
||||
AsOf time.Time
|
||||
Safety SourceSafety
|
||||
}
|
||||
type MirrorRecord struct {
|
||||
Key MirrorKey
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
func validMirrorTenant(tenant string) bool {
|
||||
return strings.TrimSpace(tenant) == tenant && len(tenant) > 0 && len(tenant) <= 128 && !strings.ContainsRune(tenant, 0)
|
||||
}
|
||||
|
||||
// Only a manifest (IDs and stable hashes), not all long answers, crosses the
|
||||
// network on unchanged polls. Each read retains the source ACL and read-only gates.
|
||||
func (c *Client) ReadMirrorManifest(ctx context.Context, tenant string) (MirrorManifest, error) {
|
||||
out := MirrorManifest{Keys: []MirrorKey{}}
|
||||
if !validMirrorTenant(tenant) {
|
||||
return out, ErrInvalidQuery
|
||||
}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&out.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+` FROM records ORDER BY id LIMIT 100001`, tenant)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k MirrorKey
|
||||
if rows.Scan(&k.ID, &k.Fingerprint) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out.Keys) >= MaxMirrorRecords {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out.Keys = append(out.Keys, k)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
out.Safety = c.Safety()
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) ReadMirrorRecords(ctx context.Context, tenant string, ids []string) ([]MirrorRecord, error) {
|
||||
if !validMirrorTenant(tenant) || len(ids) == 0 || len(ids) > 100 {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
if id == "" || len(id) > 256 || strings.ContainsRune(id, 0) || seen[id] {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
out := make([]MirrorRecord, 0, len(ids))
|
||||
size := 0
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+`,payload FROM records WHERE id=ANY($2::text[]) ORDER BY id`, tenant, ids)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r MirrorRecord
|
||||
if rows.Scan(&r.Key.ID, &r.Key.Fingerprint, &r.Payload) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
size += len(r.Payload)
|
||||
if len(r.Payload) > 8<<20 || size > 32<<20 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out) != len(ids) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMirrorSourceManifestDetectsUpdatesWithoutVolatileTimes(t *testing.T) {
|
||||
p := fixturePool(t)
|
||||
c := buildReadOnlyClient(t, qaRecordsFixture(t, p))
|
||||
ctx := context.Background()
|
||||
a, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(a.Keys) != 4 || a.AsOf.IsZero() {
|
||||
t.Fatal("full fixed-channel manifest is missing", e, len(a.Keys))
|
||||
}
|
||||
b, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(b.Keys) != len(a.Keys) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
old := map[string]string{}
|
||||
for i, k := range a.Keys {
|
||||
old[k.ID] = k.Fingerprint
|
||||
if k != b.Keys[i] {
|
||||
t.Fatal("source clock alone changed the content fingerprint")
|
||||
}
|
||||
}
|
||||
rows, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || len(rows) != 1 || rows[0].Key.Fingerprint != old["turn-3"] {
|
||||
t.Fatal("bounded safe payload fetch failed", e)
|
||||
}
|
||||
before, e := DecodeMirrorPayload(string(rows[0].Payload))
|
||||
if e != nil || before.Feedback.Up != 1 || before.Identity.StaffID == "" {
|
||||
t.Fatal("safe payload lost required fields", e)
|
||||
}
|
||||
execFixture(t, p, `UPDATE answer_feedback SET value='down' WHERE id='fb1'`)
|
||||
after, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || after[0].Key.Fingerprint == old["turn-3"] {
|
||||
t.Fatal("feedback update on old question was missed", e)
|
||||
}
|
||||
rec, _ := DecodeMirrorPayload(string(after[0].Payload))
|
||||
if rec.QualityInputHash != before.QualityInputHash {
|
||||
t.Fatal("feedback invalidated unrelated human quality input")
|
||||
}
|
||||
execFixture(t, p, `UPDATE turns SET answer='changed answer' WHERE id='turn-3'`)
|
||||
after, e = c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
rec, _ = DecodeMirrorPayload(string(after[0].Payload))
|
||||
if e != nil || rec.QualityInputHash == before.QualityInputHash {
|
||||
t.Fatal("answer change was missed")
|
||||
}
|
||||
if _, e = c.ReadMirrorRecords(ctx, "default", make([]string, 101)); e == nil {
|
||||
t.Fatal("unbounded payload fetch allowed")
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ type ActorIdentity struct {
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
RegionNames []string `json:"region_names"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
@@ -57,7 +58,7 @@ func decodeRecord(raw string) (Record, error) {
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
func (c *RecordsRepository) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return UsageGroups{}, err
|
||||
}
|
||||
@@ -69,11 +70,11 @@ func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageG
|
||||
return UsageGroups{}, patternErr
|
||||
}
|
||||
result := UsageGroups{Groups: []UsageGroup{}}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ type QualityScope struct {
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
func (c *RecordsRepository) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
@@ -23,11 +23,15 @@ func (c *Client) ReadQualityScope(ctx context.Context, query RecordQuery) (Quali
|
||||
return QualityScope{}, err
|
||||
}
|
||||
result := QualityScope{Keys: []QualityKey{}}
|
||||
err = c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
err = c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
scopeSQL := c.baseSQL + ` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `
|
||||
if c.qualityScopeSQL != "" {
|
||||
scopeSQL = c.qualityScopeSQL
|
||||
}
|
||||
rows, err := q.Query(ctx, scopeSQL+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RecordQuerier and RecordTransaction keep the projection identical while an
|
||||
// explicitly selected reader supplies either source-ACL or local-snapshot transactions.
|
||||
type RecordRow = rowScanner
|
||||
type RecordQuerier = querier
|
||||
type RecordTransaction func(context.Context, func(context.Context, RecordQuerier) error) error
|
||||
type RecordsRepositoryOptions struct {
|
||||
BaseSQL string
|
||||
SummarySQL string
|
||||
QualityScopeSQL string
|
||||
Transaction RecordTransaction
|
||||
ValidateWindow func(Window) error
|
||||
ReadAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
TenantKey string
|
||||
}
|
||||
type RecordsRepository struct {
|
||||
baseSQL string
|
||||
summarySQL string
|
||||
qualityScopeSQL string
|
||||
transact RecordTransaction
|
||||
validateQueryWindow func(Window) error
|
||||
readAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewRecordsRepository(o RecordsRepositoryOptions) *RecordsRepository {
|
||||
asOf := o.ReadAsOf
|
||||
if asOf == nil {
|
||||
asOf = func(ctx context.Context, q RecordQuerier, t *time.Time) error {
|
||||
return q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(t)
|
||||
}
|
||||
}
|
||||
return &RecordsRepository{summarySQL: o.SummarySQL, qualityScopeSQL: o.QualityScopeSQL, baseSQL: o.BaseSQL, transact: o.Transaction, validateQueryWindow: o.ValidateWindow, readAsOf: asOf, tenant: o.TenantKey}
|
||||
}
|
||||
func (c *RecordsRepository) WithSummarySQL(sql string) *RecordsRepository {
|
||||
out := *c
|
||||
out.summarySQL = sql
|
||||
return &out
|
||||
}
|
||||
func (c *Client) recordRepository() *RecordsRepository {
|
||||
return NewRecordsRepository(RecordsRepositoryOptions{BaseSQL: recordsBaseSQL, Transaction: c.withReadOnlyTx, ValidateWindow: c.validateQueryWindow})
|
||||
}
|
||||
func (c *Client) ListRecords(ctx context.Context, q RecordQuery) (RecordPage, error) {
|
||||
return c.recordRepository().ListRecords(ctx, q)
|
||||
}
|
||||
func (c *Client) GetRecord(ctx context.Context, tenant, id string) (Record, error) {
|
||||
return c.recordRepository().GetRecord(ctx, tenant, id)
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, q RecordQuery) (UsageGroups, error) {
|
||||
return c.recordRepository().ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, q RecordQuery) (QualityScope, error) {
|
||||
return c.recordRepository().ReadQualityScope(ctx, q)
|
||||
}
|
||||
|
||||
// DecodeMirrorPayload accepts only the source adapter's fixed safe projection;
|
||||
// credentials and arbitrary source tables are never part of this protocol.
|
||||
func DecodeMirrorPayload(raw string) (Record, error) { return decodeRecord(raw) }
|
||||
@@ -18,6 +18,21 @@ import (
|
||||
const CoverageRuleVersion = "governance-answer-substring-v1"
|
||||
const noPublishedMarker = "暂无已发布"
|
||||
|
||||
// The master follows the explicitly approved v2 policy; legacy/source checks stay immutable.
|
||||
func CheckMasterCoverage(answer string, available bool) CoverageCheck {
|
||||
result := CoverageCheck{State: "pending", RuleVersion: "master-answer-substring-v2"}
|
||||
if !available || strings.TrimSpace(answer) == "" {
|
||||
return result
|
||||
}
|
||||
result.State = "checked"
|
||||
result.Verdict = "covered"
|
||||
if strings.Contains(answer, noPublishedMarker) {
|
||||
result.Verdict = "uncovered"
|
||||
result.MatchedText = noPublishedMarker
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
var ErrRecordNotFound = errors.New("qa record not found")
|
||||
|
||||
type CoverageCheck struct {
|
||||
@@ -54,6 +69,11 @@ type RecordFeedback struct {
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
ContentProjection string `json:"content_projection,omitempty"`
|
||||
FieldEditRevision int64 `json:"field_edit_revision,omitempty"`
|
||||
BackgroundTasks json.RawMessage `json:"background_tasks,omitempty"`
|
||||
RecordOrigin string `json:"record_origin,omitempty"`
|
||||
MasterFields map[string]string `json:"master_fields,omitempty"`
|
||||
QualityObservedAt time.Time `json:"-"`
|
||||
QualityInputHash string `json:"-"`
|
||||
Quality json.RawMessage `json:"quality,omitempty"`
|
||||
@@ -77,10 +97,14 @@ type Record struct {
|
||||
}
|
||||
|
||||
type RecordQuery struct {
|
||||
Window Window
|
||||
Keyword string
|
||||
Cursor string
|
||||
Limit int
|
||||
Summary bool
|
||||
Filters map[string]string
|
||||
MatchIDs []string
|
||||
MatchVersion string
|
||||
Window Window
|
||||
Keyword string
|
||||
Cursor string
|
||||
Limit int
|
||||
}
|
||||
|
||||
type QualityKey struct {
|
||||
@@ -91,15 +115,16 @@ type QualityKey struct {
|
||||
InputHash string `json:"input_hash"`
|
||||
}
|
||||
type RecordPage struct {
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision,omitempty"`
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
}
|
||||
|
||||
type recordCursor struct {
|
||||
@@ -172,7 +197,7 @@ func recordKeywordPattern(keyword string) (string, error) {
|
||||
return "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + "%", nil
|
||||
}
|
||||
|
||||
func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return RecordPage{}, err
|
||||
}
|
||||
@@ -180,6 +205,16 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
return RecordPage{}, fmt.Errorf("%w: invalid record filters", ErrInvalidQuery)
|
||||
}
|
||||
scopeBytes, _ := json.Marshal([]string{query.Window.TenantKey, query.Window.Start.UTC().Format(time.RFC3339Nano), query.Window.End.UTC().Format(time.RFC3339Nano), query.Keyword})
|
||||
if len(query.Filters) > 0 {
|
||||
if query.MatchIDs == nil {
|
||||
return RecordPage{}, ErrInvalidQuery
|
||||
}
|
||||
extra, _ := json.Marshal(struct {
|
||||
Filters map[string]string
|
||||
Version string
|
||||
}{query.Filters, query.MatchVersion})
|
||||
scopeBytes = append(scopeBytes, extra...)
|
||||
}
|
||||
scopeSum := sha256.Sum256(scopeBytes)
|
||||
scope := hex.EncodeToString(scopeSum[:])
|
||||
var cursor recordCursor
|
||||
@@ -197,12 +232,22 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
}
|
||||
args := []any{query.Window.TenantKey, query.Window.Start, query.Window.End, pattern}
|
||||
page := RecordPage{Items: make([]Record, 0), Columns: make([]string, 0)}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := c.readAsOf(ctx, q, &page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns, rawActors, rawQuality string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
summarySQL := c.baseSQL + recordColumnsSQL
|
||||
if c.summarySQL != "" {
|
||||
summarySQL = c.summarySQL
|
||||
}
|
||||
summaryFilter := recordFilterSQL
|
||||
summaryArgs := append(append([]any{}, args...), noPublishedMarker)
|
||||
if query.MatchIDs != nil {
|
||||
summaryFilter += " AND id=ANY($6::text[])"
|
||||
summaryArgs = append(summaryArgs, query.MatchIDs)
|
||||
}
|
||||
if err := q.QueryRow(ctx, summarySQL+summaryFilter, summaryArgs...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
|
||||
@@ -223,8 +268,14 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
page.Columns = append(page.Columns, column)
|
||||
}
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT payload::text FROM records WHERE `+recordFilterSQL+`
|
||||
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, append(args, before, cursor.ID, query.Limit+1)...)
|
||||
listFilter := recordFilterSQL
|
||||
listArgs := append(append([]any{}, args...), before, cursor.ID, query.Limit+1)
|
||||
if query.MatchIDs != nil {
|
||||
listFilter += " AND id=ANY($8::text[])"
|
||||
listArgs = append(listArgs, query.MatchIDs)
|
||||
}
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE `+listFilter+`
|
||||
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, listArgs...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: record list failed", ErrUnavailable)
|
||||
}
|
||||
@@ -259,14 +310,14 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
func (c *RecordsRepository) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || (c.tenant != "" && tenantKey != c.tenant) || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
return Record{}, ErrInvalidQuery
|
||||
}
|
||||
var item Record
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
var raw string
|
||||
err := q.QueryRow(ctx, recordsBaseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
err := q.QueryRow(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ type CatalogSource struct {
|
||||
LastRefreshDurationMS int64 `json:"last_refresh_duration_ms"`
|
||||
// ScanProgress / ScanMessage 只在 SnapshotStatus == "scanning" 时有值:新来源在首次扫描
|
||||
// 完成前也出现在「来源与目录」里,带着百分比与进度文案,不必等到快照落地才看得见。
|
||||
ScanProgress int `json:"scan_progress,omitempty"`
|
||||
ScanProgress int `json:"scan_progress"`
|
||||
ScanMessage string `json:"scan_message,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQueuedCatalogSourceIncludesNumericZeroProgress(t *testing.T) {
|
||||
source := CatalogSource{SnapshotStatus: "scanning", ScanProgress: 0}
|
||||
body, err := json.Marshal(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var decoded map[string]any
|
||||
if err = json.Unmarshal(body, &decoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value, ok := decoded["scan_progress"]; !ok || value != float64(0) {
|
||||
t.Fatalf("queued source must satisfy the frontend numeric progress contract: %s", body)
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,9 @@ func isAuthEndpoint(method, path string) bool {
|
||||
|
||||
// classify maps a request to the minimum role required.
|
||||
func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/source-connections/audit" {
|
||||
return roleAdmin
|
||||
}
|
||||
// The member roster exposes account identities and roles: admin-only for
|
||||
// every method, checked before the read shortcut below.
|
||||
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
func TestDWSNameConflictIsNotASuccessfulRegistration(t *testing.T) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: postgresstore.ErrDingtalkSpaceNameTaken}
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "wiki", SpaceID: "testspace"}}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", nil)
|
||||
registerSpaceThroughDWS(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("name conflict must not claim success: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 登记走 dws 不是侧车:解析出来的键、名称、根节点直接决定新来源的确定性 id。
|
||||
func TestResolveSpaceViaDWSUsesTheSpaceCredentialsAlreadyHeld(t *testing.T) {
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{
|
||||
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{
|
||||
{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"},
|
||||
{Name: "视觉文档", SpaceID: "9JOGO9EEOMLMWX4Q"},
|
||||
},
|
||||
DriveSpaces: []dingtalkdiscovery.DriveSpace{
|
||||
{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a"},
|
||||
},
|
||||
}}
|
||||
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(
|
||||
context.Background(), lister, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
|
||||
if !ok || rootKey != "space-9JOGOLBQndOyaz4Q" || name != "国内技术支持管理" || rootID != "9JOGOLBQndOyaz4Q" || spaceID != "9JOGOLBQndOyaz4Q" {
|
||||
t.Fatalf("knowledge base resolved as key=%q name=%q root=%q space=%q ok=%v", rootKey, name, rootID, spaceID, ok)
|
||||
}
|
||||
|
||||
// 钉盘的根是 rootFolderId,不是空间 id:抓取侧按它遍历。
|
||||
rootKey, _, rootID, _, ok = resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("102571304"))
|
||||
if !ok || rootID != "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a" || rootKey != "space-102571304" {
|
||||
t.Fatalf("drive space resolved as key=%q root=%q ok=%v", rootKey, rootID, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSpaceViaDWSLeavesUnknownSpacesToTheFallback(t *testing.T) {
|
||||
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{}}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("unknownspace1")); ok {
|
||||
t.Fatal("an unknown space must not resolve")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok {
|
||||
t.Fatal("without a lister nothing can resolve")
|
||||
}
|
||||
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok {
|
||||
t.Fatal("a URL without a space id must not resolve")
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,11 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"})
|
||||
return
|
||||
}
|
||||
// dws 已经持有有效凭据(access 自动续期、refresh 一个月),登记也该走它:
|
||||
// 只有 dws 解析不出这个空间时,才回落到老的扫码侧车。
|
||||
if registered, ok := registerSpaceThroughDWS(w, r, config, strings.TrimSpace(input.URL), operationID); ok || registered {
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)})
|
||||
status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload)
|
||||
if status != http.StatusOK {
|
||||
@@ -136,7 +141,7 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
return
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(),
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
@@ -239,3 +244,76 @@ func proxyDingtalk(method, path string, body []byte) (int, []byte) {
|
||||
}
|
||||
return resp.StatusCode, data
|
||||
}
|
||||
|
||||
// resolveSpaceViaDWS 用 dws 列举结果定位一个空间:返回确定性登记键、名称与根节点。
|
||||
// 认不出就 ok=false,调用方回落到老的扫码侧车(历史空间仍能被登记)。
|
||||
func resolveSpaceViaDWS(ctx context.Context, lister dingtalkSourcesLister, rawURL string) (rootKey, name, rootID, spaceID string, ok bool) {
|
||||
spaceID = extractDingtalkSpaceID(rawURL)
|
||||
if lister == nil || spaceID == "" {
|
||||
return "", "", "", "", false
|
||||
}
|
||||
discovered, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
return "", "", "", "", false
|
||||
}
|
||||
for _, base := range discovered.KnowledgeBases {
|
||||
if base.SpaceID == spaceID {
|
||||
// 知识库:URL 里的 id 就是空间 id,抓取侧按 spaces/<id> 匹配。
|
||||
return "space-" + spaceID, base.Name, spaceID, spaceID, true
|
||||
}
|
||||
}
|
||||
for _, space := range discovered.DriveSpaces {
|
||||
if space.SpaceID == spaceID && space.RootFolderID != "" {
|
||||
return "space-" + spaceID, space.Name, space.RootFolderID, spaceID, true
|
||||
}
|
||||
}
|
||||
return "", "", "", "", false
|
||||
}
|
||||
|
||||
// registerSpaceThroughDWS 用 dws 凭据直接登记来源,不再要求扫码会话。
|
||||
func registerSpaceThroughDWS(w http.ResponseWriter, r *http.Request, config Config, rawURL, operationID string) (bool, bool) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(ctx, config.DingtalkSources, rawURL)
|
||||
if !ok {
|
||||
return false, false
|
||||
}
|
||||
store, wired := config.Store.(interface {
|
||||
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
|
||||
})
|
||||
if !wired {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
|
||||
return true, false
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: rootKey, Name: name, SpaceID: spaceID, RootID: rootID, Now: config.Now(), Actor: actorFor(r),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源,但空间标识不一致;请核对已有来源,不能按名称判定添加成功。"})
|
||||
return true, false
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试。",
|
||||
})
|
||||
return true, false
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return true, false
|
||||
}
|
||||
if enqueuer, wired := config.Store.(interface {
|
||||
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
|
||||
}); wired {
|
||||
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{
|
||||
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: name,
|
||||
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
|
||||
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
|
||||
}
|
||||
}
|
||||
log.Printf("dingtalk space %q registered as connection %s by %s (dws)", name, connectionID, actorFor(r))
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
|
||||
"connection_id": connectionID, "name": name,
|
||||
}})
|
||||
return true, true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dwsMetadataReader interface {
|
||||
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
|
||||
}
|
||||
|
||||
func readDWSCredentials(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
reader, ok := config.DingtalkSources.(dwsMetadataReader)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "DWS credential status not configured"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
result, err := reader.ReadDWSMetadata(ctx)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法读取 DWS 凭证状态"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": result})
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type monitorRemovalRetrier interface {
|
||||
RetryMonitorRemoval(context.Context, string, string, time.Time) error
|
||||
}
|
||||
|
||||
func retryMonitorRemoval(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if identity.Role != roleEngineer && identity.Role != roleAdmin {
|
||||
writeJSON(w, 403, map[string]string{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != "monitor-removal-retry" {
|
||||
writeJSON(w, 403, map[string]string{"error": "write intent required"})
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" || len(id) > 128 {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid publication"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(monitorRemovalRetrier)
|
||||
if !ok {
|
||||
writeJSON(w, 501, map[string]string{"error": "removal retry not configured"})
|
||||
return
|
||||
}
|
||||
err := store.RetryMonitorRemoval(r.Context(), id, actorFor(r), time.Now().UTC())
|
||||
if errors.Is(err, postgresstore.ErrPublicationStateConflict) {
|
||||
writeJSON(w, 409, map[string]string{"error": "状态或治理规则已变化,不能重复提交"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "测试库移除重试失败"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]string{"status": "accepted"})
|
||||
}
|
||||
|
||||
type monitorTaskReader interface {
|
||||
ListMonitorTasks(context.Context, postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error)
|
||||
}
|
||||
|
||||
func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
f := postgresstore.MonitorTaskFilter{Search: q.Get("q"), Source: q.Get("source"), Scope: q.Get("scope"), Action: q.Get("action"), Status: q.Get("status"), Stage: q.Get("stage"), ID: q.Get("id"), Target: q.Get("target"), Since: q.Get("since"), Until: q.Get("until"), Limit: 20}
|
||||
for k, p := range map[string]*int{"limit": &f.Limit, "offset": &f.Offset} {
|
||||
if q.Get(k) != "" {
|
||||
n, e := strconv.Atoi(q.Get(k))
|
||||
if e != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid pagination"})
|
||||
return
|
||||
}
|
||||
*p = n
|
||||
}
|
||||
}
|
||||
if f.Limit < 1 || f.Limit > 100 || f.Offset < 0 || len(f.Search) > 512 || len(f.Source) > 128 || len(f.ID) > 128 {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
|
||||
return
|
||||
}
|
||||
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished"}} {
|
||||
if !strings.Contains("|"+pair[1]+"|", "|"+pair[0]+"|") {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, v := range []string{f.Since, f.Until} {
|
||||
if v != "" {
|
||||
if _, e := time.Parse(time.RFC3339, v); e != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid date"})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
store, ok := config.Store.(monitorTaskReader)
|
||||
if !ok {
|
||||
writeJSON(w, 501, map[string]string{"error": "monitor tasks not configured"})
|
||||
return
|
||||
}
|
||||
page, e := store.ListMonitorTasks(r.Context(), f)
|
||||
if e != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, map[string]any{"data": page})
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type monitorTasksTestStore struct {
|
||||
fakeJobStore
|
||||
filter postgresstore.MonitorTaskFilter
|
||||
}
|
||||
|
||||
func (s *monitorTasksTestStore) ListMonitorTasks(_ context.Context, f postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error) {
|
||||
s.filter = f
|
||||
return postgresstore.MonitorTaskPage{Items: []postgresstore.MonitorTask{}, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
|
||||
}
|
||||
func TestMonitorTasksRoute(t *testing.T) {
|
||||
s := &monitorTasksTestStore{}
|
||||
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?status=active&limit=20&offset=40", nil)
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
|
||||
w := httptest.NewRecorder()
|
||||
h, err := NewHandler(Config{Store: s})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if s.filter.Status != "active" || s.filter.Offset != 40 {
|
||||
t.Fatalf("filter %#v", s.filter)
|
||||
}
|
||||
for _, query := range []string{"status=garbage", "stage=internal&scope=internal", "limit=101", "offset=-1", "since=bad"} {
|
||||
r := httptest.NewRequest("GET", "/api/v1/monitor/tasks?"+query, nil).WithContext(req.Context())
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, r)
|
||||
if rr.Code != 400 {
|
||||
t.Fatalf("invalid %s: %d", query, rr.Code)
|
||||
}
|
||||
}
|
||||
unauth := httptest.NewRecorder()
|
||||
h.ServeHTTP(unauth, httptest.NewRequest("GET", "/api/v1/monitor/tasks", nil))
|
||||
if unauth.Code != 401 {
|
||||
t.Fatalf("unauthenticated %d", unauth.Code)
|
||||
}
|
||||
removal := httptest.NewRecorder()
|
||||
h.ServeHTTP(removal, httptest.NewRequest("POST", "/api/v1/test-publications/example/removal-retry", nil).WithContext(req.Context()))
|
||||
if removal.Code != 403 {
|
||||
t.Fatalf("viewer removal %d", removal.Code)
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,31 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
var guardBaseURL func(any, string)
|
||||
guardBaseURL = func(node any, path string) {
|
||||
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" {
|
||||
t.Fatalf("unapproved endpoint exposure at %s", path)
|
||||
}
|
||||
next := key
|
||||
if path != "" {
|
||||
next = path + "." + key
|
||||
}
|
||||
guardBaseURL(child, next)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range value {
|
||||
guardBaseURL(child, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
var tree any
|
||||
_ = json.Unmarshal(contract, &tree)
|
||||
guardBaseURL(tree, "")
|
||||
lower := strings.ToLower(string(contract))
|
||||
for _, forbidden := range []string{"secret_ref", "authorization_code", "manifest_sha256", "knowledge_id", "test_kb_id", "base_url", "download_code", "cookie"} {
|
||||
for _, forbidden := range []string{"secret_ref", "authorization_code", "manifest_sha256", "knowledge_id", "test_kb_id", "download_code", "cookie"} {
|
||||
if strings.Contains(lower, forbidden) {
|
||||
t.Fatalf("OpenAPI contract must not expose %q", forbidden)
|
||||
}
|
||||
@@ -104,6 +127,46 @@ func TestOpenAPICatalogMutationsRequireIdempotencyKeyHeader(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAAIContractDescribesAllAdministratorPathsAndWriteOnlyCredential(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../api/openapi.yaml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var document struct {
|
||||
Paths map[string]map[string]any `json:"paths"`
|
||||
Components struct {
|
||||
Schemas map[string]map[string]any `json:"schemas"`
|
||||
} `json:"components"`
|
||||
}
|
||||
if json.Unmarshal(raw, &document) != nil {
|
||||
t.Fatal("invalid API document")
|
||||
}
|
||||
for _, route := range []struct{ path, method string }{{"/settings", "get"}, {"/settings", "post"}, {"/settings/test", "post"}, {"/automation", "post"}, {"/previews", "post"}, {"/batches", "post"}, {"/batches/{id}/actions", "post"}, {"/status", "get"}, {"/records/{id}", "get"}} {
|
||||
path := "/api/v1/qa-ops/ai" + route.path
|
||||
op, ok := document.Paths[path][route.method].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing %s %s", route.method, path)
|
||||
}
|
||||
responses, _ := op["responses"].(map[string]any)
|
||||
for _, status := range []string{"400", "401", "403", "500", "503"} {
|
||||
if responses[status] == nil {
|
||||
t.Fatalf("missing %s for %s", status, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
safe := document.Components.Schemas["QAAISafeSettings"]
|
||||
properties, _ := safe["properties"].(map[string]any)
|
||||
if properties["api_key"] != nil || properties["key_ciphertext"] != nil || properties["key_configured"] == nil || safe["additionalProperties"] != false {
|
||||
t.Fatal("safe settings contract exposes secrets or accepts unknown fields")
|
||||
}
|
||||
input := document.Components.Schemas["QAAISaveSettings"]
|
||||
properties, _ = input["properties"].(map[string]any)
|
||||
key, _ := properties["api_key"].(map[string]any)
|
||||
if key["writeOnly"] != true {
|
||||
t.Fatal("API key request property is not write-only")
|
||||
}
|
||||
}
|
||||
|
||||
func stringValue(value any) string {
|
||||
result, _ := value.(string)
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func qaAIError(w http.ResponseWriter, err error) {
|
||||
status, code, message := 503, "qa_ai_unavailable", "问答AI存储或安全配置不可用,请检查独立模型配置与执行器;未将失败伪装为成功或空结果"
|
||||
switch {
|
||||
case errors.Is(err, qaopsai.ErrInvalid):
|
||||
status, code, message = 400, "qa_ai_invalid_request", "参数、正式标签或模型输出校验未通过;更换API地址时须重新录入密钥,不能把旧密钥发送到新地址"
|
||||
case errors.Is(err, qaopsai.ErrConflict):
|
||||
status, code, message = 409, "qa_ai_version_conflict", "配置、输入、人工复核或预览已变化,请刷新;现有结论未被覆盖"
|
||||
default:
|
||||
var remote *qaopsai.RemoteError
|
||||
if errors.As(err, &remote) {
|
||||
status, code, message = 422, "qa_ai_"+remote.Code, "模型服务明确拒绝或未返回合格结果,配置未启用;请核对密钥、模型与JSON输出支持"
|
||||
}
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
func qaAIReady(w http.ResponseWriter, r *http.Request, c Config) bool {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return false
|
||||
}
|
||||
if r.Method != "GET" && !authorizeQAIntent(w, r, "qa-ai") {
|
||||
return false
|
||||
}
|
||||
if c.QAAI == nil {
|
||||
qaAIError(w, qaopsai.ErrUnavailable)
|
||||
return false
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return false
|
||||
}
|
||||
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
|
||||
}
|
||||
func registerQAAIRoutes(mux *http.ServeMux, c Config) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
data, err := c.QAAI.GetSettings(r.Context())
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
for _, test := range []bool{false, true} {
|
||||
path := "POST /api/v1/qa-ops/ai/settings"
|
||||
if test {
|
||||
path += "/test"
|
||||
}
|
||||
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input qaopsai.SaveSettings
|
||||
if decodeQualityJSON(w, r, &input, "base_revision", "base_url", "model", "key_action") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if input.APIKey != "" && !qaAISecretTransport(r, c) {
|
||||
writeJSON(w, 400, map[string]string{"code": "qa_ai_secure_transport_required", "error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
var data qaopsai.Settings
|
||||
var err error
|
||||
if test {
|
||||
data, err = c.QAAI.TestSettings(r.Context(), input)
|
||||
} else {
|
||||
data, err = c.QAAI.SaveSettings(r.Context(), input, identity.Username)
|
||||
}
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
}
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/automation", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Kind string `json:"kind"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &input, "kind", "enabled") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.SetAutomation(r.Context(), input.Kind, input.Enabled, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/previews", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input qaopsai.Scope
|
||||
if decodeQualityJSON(w, r, &input, "kind") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.Preview(r.Context(), input, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/batches", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
PreviewID string `json:"preview_id"`
|
||||
Nonce string `json:"nonce"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &input, "preview_id", "nonce") != nil {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.Start(r.Context(), input.PreviewID, input.Nonce, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/ai/batches/{id}/actions", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Action string `json:"action"`
|
||||
Nonce string `json:"nonce"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &input, "action", "nonce") != nil || r.Header.Get("Idempotency-Key") != input.Nonce {
|
||||
qaAIError(w, qaopsai.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
data, err := c.QAAI.ManageBatch(r.Context(), r.PathValue("id"), input.Action, input.Nonce, identity.Username)
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
data, err := c.QAAI.GetStatus(r.Context())
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/ai/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !qaAIReady(w, r, c) {
|
||||
return
|
||||
}
|
||||
data, err := c.QAAI.RecordEvidence(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaAIError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": data})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAIUnavailableDoesNotFalselyClaimNoModelCallOccurred(t *testing.T) {
|
||||
response := httptest.NewRecorder()
|
||||
qaAIError(response, qaopsai.ErrUnavailable)
|
||||
if strings.Contains(response.Body.String(), "未调用模型") {
|
||||
t.Fatal("a persistence failure after a model call was reported as no call")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIEndpointsRequireAdminAndExplicitSameOriginWriteIntent(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["fixture-ai-admin"] = "usr-boss"
|
||||
auth.sessions["fixture-ai-viewer"] = "usr-eye"
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, route := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/ai/settings", ""}, {"GET", "/api/v1/qa-ops/ai/status", ""}, {"POST", "/api/v1/qa-ops/ai/settings", `{}`}, {"POST", "/api/v1/qa-ops/ai/settings/test", `{}`}, {"POST", "/api/v1/qa-ops/ai/previews", `{}`}, {"POST", "/api/v1/qa-ops/ai/batches", `{}`}, {"POST", "/api/v1/qa-ops/ai/automation", `{}`}, {"POST", "/api/v1/qa-ops/ai/batches/fixture/actions", `{}`}} {
|
||||
for _, who := range []struct {
|
||||
token string
|
||||
want int
|
||||
}{{"", 401}, {"fixture-ai-viewer", 403}, {"fixture-ai-admin", 503}} {
|
||||
request := httptest.NewRequest(route.method, route.path, strings.NewReader(route.body))
|
||||
if who.token != "" {
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: who.token})
|
||||
}
|
||||
request.Header.Set("X-Governance-Action", "qa-ai")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != who.want {
|
||||
t.Fatalf("%s %s role=%s status=%d want=%d", route.method, route.path, who.token, response.Code, who.want)
|
||||
}
|
||||
}
|
||||
if route.method == "POST" {
|
||||
request := httptest.NewRequest(route.method, route.path, strings.NewReader(route.body))
|
||||
request.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-ai-admin"})
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 403 {
|
||||
t.Fatal("write without explicit action was accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,10 +31,14 @@ func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attributio
|
||||
return p, nil
|
||||
}
|
||||
func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion {
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory"}
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
|
||||
trigger := item.TriggerPerson
|
||||
if raw, ok := item.MasterFields["trigger_person"]; ok {
|
||||
trigger = raw
|
||||
}
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID, item.Asker, trigger)
|
||||
o := &dobotaiops.RecordOrganization{Version: attributionVersion(p), State: person.State, Departments: person.Departments, Region: person.Region, SourceDepartment: item.Department, SourceRegion: item.Region, DepartmentOrigin: "unavailable", RegionOrigin: "unavailable"}
|
||||
if item.Department != "" {
|
||||
o.DepartmentOrigin = "source_snapshot"
|
||||
@@ -92,7 +96,7 @@ type qaUsage struct {
|
||||
|
||||
func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage {
|
||||
result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}}
|
||||
keys := append(append([]string{}, qaopsorg.RegionNames...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
keys := append(append([]string{}, p.Metadata.RegionLabels()...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
@@ -108,7 +112,12 @@ func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, qu
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
n, ok = p.Metadata.View.Regions[key]
|
||||
for _, region := range p.Metadata.RegionDefinitions() {
|
||||
if region.Name == key {
|
||||
n, ok = p.Metadata.View.Regions[region.ID]
|
||||
break
|
||||
}
|
||||
}
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qaDashboardReader interface {
|
||||
ReadMasterDashboard(context.Context, dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error)
|
||||
}
|
||||
|
||||
func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-dashboard") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
Filters map[string]string `json:"filters,omitempty"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaDashboardReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
window, e := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters})
|
||||
if e != nil {
|
||||
if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
writeQualityError(w, e)
|
||||
return
|
||||
}
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": dashboard})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dashboardReaderSpy struct {
|
||||
attributedReader
|
||||
calls int
|
||||
masterCalls int
|
||||
query dobotaiops.RecordQuery
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *dashboardReaderSpy) ReadDashboard(_ context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
|
||||
s.calls++
|
||||
s.query = q
|
||||
return qaopsmirror.Dashboard{TotalIssues: 7, NewThisWeek: 2}, s.err
|
||||
}
|
||||
func (s *dashboardReaderSpy) ReadMasterDashboard(ctx context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
|
||||
s.masterCalls++
|
||||
return s.ReadDashboard(ctx, q)
|
||||
}
|
||||
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
||||
reader := &dashboardReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dash-admin"] = "usr-boss"
|
||||
auth.sessions["dash-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
good := `{"start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00","keyword":"100%_"}`
|
||||
for _, c := range []struct {
|
||||
token, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"", "qa-dashboard", "", good, 401}, {"dash-viewer", "qa-dashboard", "", good, 403}, {"dash-admin", "", "", good, 403}, {"dash-admin", "qa-dashboard", "https://untrusted.invalid", good, 403},
|
||||
{"dash-admin", "qa-dashboard", "", `null`, 400}, {"dash-admin", "qa-dashboard", "", `{"start":null,"end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", `{"tenant":"other","start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", good, 200},
|
||||
} {
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
r.Header.Set("X-Governance-Action", c.action)
|
||||
r.Header.Set("Origin", c.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("dashboard status=%d want=%d", w.Code, c.status)
|
||||
}
|
||||
if w.Code == 200 && w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("private dashboard response may be cached")
|
||||
}
|
||||
}
|
||||
if reader.masterCalls != 1 || reader.calls != 1 || reader.query.Window.TenantKey != "fixed-dashboard-tenant" || reader.query.Keyword != "100%_" {
|
||||
t.Fatal("rejected requests reached the reader or browser controlled the tenant")
|
||||
}
|
||||
reader.err = qaopsquality.ErrConflict
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(good))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-dashboard")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("quality input drift status=%d want409", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type departmentStatisticsReader interface {
|
||||
ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error)
|
||||
}
|
||||
|
||||
func qaDepartmentStatistics(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-department-statistics") {
|
||||
return
|
||||
}
|
||||
var q qaopsmirror.DepartmentStatisticsQuery
|
||||
if r.URL.RawQuery != "" || decodeQualityJSON(w, r, &q, "period") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
now := c.Now()
|
||||
if _, _, e := q.Bounds(now); e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(departmentStatisticsReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
data, e := reader.ReadDepartmentStatistics(r.Context(), q, now)
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if data.State == "pending" {
|
||||
status = http.StatusAccepted
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"data": data})
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type departmentStatisticsFixture struct {
|
||||
masterFixtureReader
|
||||
reads int
|
||||
}
|
||||
|
||||
func (f *departmentStatisticsFixture) ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error) {
|
||||
f.reads++
|
||||
return qaopsmirror.DepartmentStatisticsResult{State: "pending", RetryAfter: 1}, nil
|
||||
}
|
||||
func TestDepartmentStatisticsRouteIsAsynchronousStrictAndAdminOnly(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dept-fixture-admin"] = "usr-boss"
|
||||
auth.sessions["dept-fixture-viewer"] = "usr-eye"
|
||||
reader := &departmentStatisticsFixture{}
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixture-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
body, token, intent, site string
|
||||
want int
|
||||
}{
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 202},
|
||||
{`{"period":"month","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "same-origin", 202},
|
||||
{`{"period":"all"}`, "", "qa-department-statistics", "", 401},
|
||||
{`{"period":"all"}`, "dept-fixture-viewer", "qa-department-statistics", "", 403},
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "", "", 403},
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "cross-site", 403},
|
||||
{`{"period":"all","tenant":"other"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"all","period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`null`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"month","month":"2027-01"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"all","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
} {
|
||||
r := httptest.NewRequest("POST", "/api/v1/qa-ops/departments/statistics", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
if c.intent != "" {
|
||||
r.Header.Set("X-Governance-Action", c.intent)
|
||||
}
|
||||
if c.site != "" {
|
||||
r.Header.Set("Sec-Fetch-Site", c.site)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.want {
|
||||
t.Fatalf("department statistics got %d want %d", w.Code, c.want)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("employee department stats became publicly cacheable")
|
||||
}
|
||||
}
|
||||
if reader.reads != 2 {
|
||||
t.Fatal("malformed or unauthorized request reached aggregation", reader.reads)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func masterNoStore(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/master/") || strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/departments/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Master reads and reviews own their state; no source client is accepted as fallback.
|
||||
type qaMasterStore interface {
|
||||
ListMasterRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error)
|
||||
GetMasterRecord(context.Context, string, string) (dobotaiops.Record, error)
|
||||
ReadMasterQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
MasterQualityStore() *qaopsquality.Store
|
||||
}
|
||||
type qaMasterReader struct {
|
||||
QAOpsReader
|
||||
master qaMasterStore
|
||||
}
|
||||
|
||||
func (s qaMasterReader) ListRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return s.master.ListMasterRecords(ctx, q)
|
||||
}
|
||||
func (s qaMasterReader) GetRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.master.GetMasterRecord(ctx, tenant, id)
|
||||
}
|
||||
func (s qaMasterReader) ReadQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.master.ReadMasterQualityScope(ctx, q)
|
||||
}
|
||||
func (s qaMasterReader) ReadStoredQuality(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
if reader, ok := s.master.(interface {
|
||||
ReadMasterQualityViews(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
}); ok {
|
||||
return reader.ReadMasterQualityViews(ctx, keys)
|
||||
}
|
||||
return s.master.MasterQualityStore().ReadViews(ctx, keys)
|
||||
}
|
||||
func withQAMaster(w http.ResponseWriter, r *http.Request, c Config, handler func(http.ResponseWriter, *http.Request, Config)) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
master, ok := c.QAOps.(qaMasterStore)
|
||||
if !ok {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
c.QAOps = qaMasterReader{QAOpsReader: c.QAOps, master: master}
|
||||
c.QAQuality = master.MasterQualityStore()
|
||||
if master.MasterQualityStore() == nil {
|
||||
c.QAQuality = nil
|
||||
}
|
||||
handler(w, r, c)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type downvoteSnapshotReader struct {
|
||||
QAOpsReader
|
||||
view qaopsquality.View
|
||||
}
|
||||
|
||||
func (s downvoteSnapshotReader) ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
return map[string]qaopsquality.View{"fixture-feedback-race": s.view}, nil
|
||||
}
|
||||
|
||||
func TestMasterQualityEnrichmentUsesOneFeedbackDecisionEvenWhenVoteChangesBetweenReads(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
old, current dobotaiops.RecordFeedback
|
||||
label, correctness, rule string
|
||||
}{
|
||||
{"new-downvote", dobotaiops.RecordFeedback{}, dobotaiops.RecordFeedback{Down: 1}, "否", "incorrect", "downvote-is-incorrect-v1"},
|
||||
{"withdrawn-current-vote", dobotaiops.RecordFeedback{Down: 1}, dobotaiops.RecordFeedback{}, "是", "correct", ""},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
view := qaopsquality.View{EffectiveSource: "master-effective-fields-v1", FeedbackRule: test.rule, Effective: qaopsquality.Fields{Correctness: test.correctness}, MasterFeedback: &test.current}
|
||||
c := Config{QAOps: downvoteSnapshotReader{view: view}, QAQuality: &qualityFake{}}
|
||||
item := dobotaiops.Record{ID: "fixture-feedback-race", RecordOrigin: "dobotai_2_0", Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}
|
||||
if err := enrichQAQualityRecord(context.Background(), c, &item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if item.Feedback != test.current || item.MasterFields["is_correct"] != test.label {
|
||||
t.Fatal("detail combines an old feedback snapshot with a newer quality decision")
|
||||
}
|
||||
page := dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: item.ID, RecordOrigin: item.RecordOrigin, Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}}}
|
||||
// The common projection must be shared by the list and detail enrichment paths.
|
||||
if err := enrichQAQualityPage(context.Background(), c, &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page.Items[0].Feedback != test.current || page.Items[0].MasterFields["is_correct"] != test.label {
|
||||
t.Fatal("list combines an old feedback snapshot with a newer quality decision")
|
||||
}
|
||||
var quality map[string]any
|
||||
if json.Unmarshal(item.Quality, &quality) != nil {
|
||||
t.Fatal("quality response missing")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsfields"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type masterFieldWriter interface {
|
||||
PatchMasterFields(context.Context, string, qaopsmirror.MasterFieldPatch, string) (qaopsmirror.MasterFieldReceipt, error)
|
||||
}
|
||||
|
||||
func qaMasterFieldOptions(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"version": "qa-master-options-v1", "fields": qaopsfields.EditableOptions()}})
|
||||
}
|
||||
func qaMasterFieldPatch(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-master-fields") {
|
||||
return
|
||||
}
|
||||
var q qaopsmirror.MasterFieldPatch
|
||||
if decodeQualityJSON(w, r, &q, "input_hash", "input_epoch", "base_revision", "base_review_revision", "nonce", "fields") != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "字段选项或编辑参数无效"})
|
||||
return
|
||||
}
|
||||
writer, ok := c.QAOps.(masterFieldWriter)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
result, err := writer.PatchMasterFields(r.Context(), r.PathValue("id"), q, identity.Username)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, qaopsquality.ErrDownvoted):
|
||||
writeJSON(w, 409, map[string]string{"error": "问题已点踩,是否正确固定为否;未保存冲突选择,请重新读取"})
|
||||
case errors.Is(err, qaopsquality.ErrConflict):
|
||||
writeJSON(w, 409, map[string]string{"error": "字段或问答版本已变化,请重新读取后修改;未覆盖其他人的内容"})
|
||||
case errors.Is(err, dobotaiops.ErrInvalidQuery):
|
||||
writeJSON(w, 400, map[string]string{"error": "字段选项无效,未保存;请选择主表允许的内容"})
|
||||
default:
|
||||
qaOpsError(w, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type masterFixtureReader struct {
|
||||
calls int
|
||||
tenant string
|
||||
}
|
||||
|
||||
func (f *masterFixtureReader) ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
panic("master must never fall back to replaceable mirror/source reads")
|
||||
}
|
||||
func (f *masterFixtureReader) GetRecord(context.Context, string, string) (dobotaiops.Record, error) {
|
||||
panic("master must never fetch the production source")
|
||||
}
|
||||
func (f *masterFixtureReader) Available(context.Context) error { return nil }
|
||||
func (f *masterFixtureReader) Safety() dobotaiops.SourceSafety { return dobotaiops.SourceSafety{} }
|
||||
func (f *masterFixtureReader) MasterQualityStore() *qaopsquality.Store { return nil }
|
||||
func (f *masterFixtureReader) ListMasterRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
f.calls++
|
||||
f.tenant = q.Window.TenantKey
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{}, Columns: []string{"question"}, AsOf: time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC), LocalRevision: 3}, nil
|
||||
}
|
||||
func (f *masterFixtureReader) GetMasterRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
f.calls++
|
||||
f.tenant = tenant
|
||||
return dobotaiops.Record{ID: id, Question: "fixture master"}, nil
|
||||
}
|
||||
func (f *masterFixtureReader) ReadMasterQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return dobotaiops.QualityScope{}, nil
|
||||
}
|
||||
func TestQAMasterUsesFixedTenantAndNeverSourceFallback(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["fixture-master-admin"] = "usr-boss"
|
||||
reader := &masterFixtureReader{}
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixed-master-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
base := "/api/v1/qa-ops/master/records"
|
||||
for _, c := range []struct {
|
||||
path string
|
||||
cookie bool
|
||||
status int
|
||||
}{{base + "?start=2026-10-05T00:00:00Z&end=2026-10-12T00:00:00Z", true, 200}, {base + "/fixture-id", true, 200}, {base + "?tenant=other", true, 400}, {base, false, 401}} {
|
||||
r := httptest.NewRequest(http.MethodGet, c.path, nil)
|
||||
if c.cookie {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-master-admin"})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("master route %s: got %d, wanted %d", c.path, w.Code, c.status)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("master employee data was cacheable")
|
||||
}
|
||||
}
|
||||
if reader.calls != 2 || reader.tenant != "fixed-master-tenant" {
|
||||
t.Fatal("master fixed-tenant read path missing")
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, base+"/fixture-id/reviews", strings.NewReader(`{}`))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-master-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("master review lacked explicit same-origin intent gate", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type mirroredQualitySource struct {
|
||||
qualitySource
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *mirroredQualitySource) ReadStoredQuality(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.reads++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(true)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestMirroredQualityQueriesDoNotRepeatObservationWrites(t *testing.T) {
|
||||
source := &mirroredQualitySource{qualitySource: qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Question: "fixture", Answer: "暂无已发布"}}}
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
source.record.QualityInputHash = e.Hash
|
||||
legacy := &qualityFake{fail: true}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
h, e2 := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: legacy, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e2 != nil {
|
||||
t.Fatal(e2)
|
||||
}
|
||||
for _, q := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/records/fixture-turn", ""}, {"GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", ""}, {"POST", "/api/v1/qa-ops/quality/query", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`}} {
|
||||
w := qualityRequest(h, q.method, q.path, "quality-admin", q.body)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatal("local mirror read went back through observation writes", q.path, w.Code)
|
||||
}
|
||||
}
|
||||
if source.reads != 3 || legacy.calls != 0 {
|
||||
t.Fatal("batched stored projection not used", source.reads, legacy.calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type qaMirrorSyncStore interface {
|
||||
GetSyncStatus(context.Context) (qaopsmirror.Status, error)
|
||||
EnqueueSync(context.Context, string, string) (qaopsmirror.SyncReceipt, bool, error)
|
||||
}
|
||||
|
||||
func qaRecordsSync(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步入口不接受查询参数"})
|
||||
return
|
||||
}
|
||||
store, ok := c.QAOps.(qaMirrorSyncStore)
|
||||
if !ok || !c.QAOpsEnabled {
|
||||
writeJSON(w, 503, map[string]string{"error": "本地问答同步未接线,未创建任务"})
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
state, e := store.GetSyncStatus(r.Context())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": state})
|
||||
return
|
||||
}
|
||||
if !authorizeQAIntent(w, r, "qa-records-sync") {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" || len(key) > 128 || strings.TrimSpace(key) != key {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求需要有效 Idempotency-Key,重试须复用原标识"})
|
||||
return
|
||||
}
|
||||
var body *struct{}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&body) != nil || body == nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求体必须是空对象"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, replayed, e := store.EnqueueSync(r.Context(), key, identity.Username)
|
||||
if e != nil {
|
||||
status := 503
|
||||
message := "同步未成功入队,已有本地数据保持不变"
|
||||
if errors.Is(e, qaopsmirror.ErrInvalid) {
|
||||
status = 400
|
||||
message = "同步请求标识无效"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrConflict) {
|
||||
status = 409
|
||||
message = "同步标识已用于另一操作,请重新发起"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrWorkerUnavailable) {
|
||||
message = "问答同步执行器未在线,未创建任务"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
return
|
||||
}
|
||||
operation := "created"
|
||||
if replayed {
|
||||
operation = "replayed"
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": receipt, "operation": operation})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type mirrorSyncSpy struct {
|
||||
qaOpsSpy
|
||||
syncCalls int
|
||||
key, actor string
|
||||
}
|
||||
|
||||
func (s *mirrorSyncSpy) GetSyncStatus(context.Context) (qaopsmirror.Status, error) {
|
||||
return qaopsmirror.Status{Mode: "local", IntervalSeconds: 300, WorkerReady: true}, nil
|
||||
}
|
||||
func (s *mirrorSyncSpy) EnqueueSync(_ context.Context, key, actor string) (qaopsmirror.SyncReceipt, bool, error) {
|
||||
s.syncCalls++
|
||||
s.key = key
|
||||
s.actor = actor
|
||||
return qaopsmirror.SyncReceipt{JobID: "fixture-mirror-job"}, false, nil
|
||||
}
|
||||
func TestQAMirrorSyncRequiresSessionIntentAndIdempotency(t *testing.T) {
|
||||
spy := &mirrorSyncSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
auth.sessions["mirror-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsEnabled: true, QAOpsTenantKey: "fixture-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, token, key, intent, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", "", "", "", "", "", 401}, {"GET", "mirror-viewer", "", "", "", "", 403}, {"GET", "mirror-admin", "", "", "", "", 200},
|
||||
{"POST", "mirror-admin", "op-one", "", "", "{}", 403}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "https://foreign.invalid", "{}", 403},
|
||||
{"POST", "mirror-admin", "", "qa-records-sync", "", "{}", 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "null", 400},
|
||||
{"POST", "mirror-admin", "op-one", "qa-records-sync", "", `{"tenant":"forged"}`, 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "{}", 202},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/v1/qa-ops/sync", strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("Idempotency-Key", tc.key)
|
||||
req.Header.Set("X-Governance-Action", tc.intent)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("%s %s got %d want %d: %s", tc.method, tc.body, w.Code, tc.status, w.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.syncCalls != 1 || spy.key != "op-one" || spy.actor == "" {
|
||||
t.Fatal("invalid sync reached store or operator was not session-stamped")
|
||||
}
|
||||
req := httptest.NewRequest("GET", "/api/v1/qa-ops/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
var body struct {
|
||||
Data struct {
|
||||
Cache *qaopsmirror.Status `json:"cache"`
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &body) != nil || body.Data.Cache == nil || body.Data.Cache.Mode != "local" {
|
||||
t.Fatal("local serving mode missing from status")
|
||||
}
|
||||
}
|
||||
func TestQAMirrorSyncNamespaceCannotBypassEntry(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
h, _ := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
req := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"type":"qaops.records.sync.fixture","payload":{},"idempotency_key":"bypass"}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("generic jobs endpoint bypassed mirror sync admission", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -97,11 +97,7 @@ func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error)
|
||||
if f.Activity != "all" && f.Activity != "used" && f.Activity != "zero" {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
validRegion := f.Region == "" || f.Region == "unassigned" || f.Region == "cross_region"
|
||||
for _, r := range qaopsorg.RegionNames {
|
||||
validRegion = validRegion || f.Region == r
|
||||
}
|
||||
if !validRegion {
|
||||
if !utf8.ValidString(f.Region) || len(f.Region) > 256 || strings.TrimSpace(f.Region) != f.Region || strings.ContainsAny(f.Region, "\x00\r\n") {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
|
||||
@@ -288,6 +284,16 @@ func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Region != "" && f.Region != "unassigned" && f.Region != "cross_region" {
|
||||
found := false
|
||||
for _, name := range p.Metadata.RegionLabels() {
|
||||
found = found || f.Region == name
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Department != "" {
|
||||
found := false
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
|
||||
@@ -61,7 +61,16 @@ func qaOpsStatus(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
warnings = append(warnings, "database_transport_unencrypted")
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}})
|
||||
data := map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}
|
||||
if mirror, ok := config.QAOps.(qaMirrorSyncStore); ok {
|
||||
cache, err := mirror.GetSyncStatus(r.Context())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
data["cache"] = cache
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": data})
|
||||
}
|
||||
|
||||
func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
@@ -73,7 +82,10 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
allowed := map[string]bool{"start": true, "end": true, "keyword": true, "cursor": true, "limit": true}
|
||||
allowed := map[string]bool{"start": true, "end": true, "keyword": true, "cursor": true, "limit": true, "projection": true}
|
||||
for _, key := range dobotaiops.QualityFilterKeys {
|
||||
allowed[key] = true
|
||||
}
|
||||
for key, items := range values {
|
||||
if !allowed[key] || len(items) != 1 {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
@@ -93,12 +105,27 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
filters := map[string]string{}
|
||||
for _, key := range dobotaiops.QualityFilterKeys {
|
||||
if value := values.Get(key); value != "" {
|
||||
filters[key] = value
|
||||
}
|
||||
}
|
||||
if !dobotaiops.ValidQualityFilters(filters) {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
mode := values.Get("projection")
|
||||
if mode != "" && mode != "summary" && mode != "full" {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
projection, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit})
|
||||
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit, Summary: mode == "summary", Filters: filters})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
@@ -108,6 +135,11 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
if mode == "summary" {
|
||||
for i := range page.Items {
|
||||
page.Items[i] = qaRecordPreview(page.Items[i])
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
@@ -144,7 +176,7 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
func qaOpsError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusServiceUnavailable
|
||||
code := "source_unavailable"
|
||||
message := "问答数据源不可用,请检查独立只读连接;原有知识治理功能不受影响"
|
||||
message := "问答记录当前不可用;本地模式请检查同步状态,原有知识治理功能不受影响"
|
||||
if errors.Is(err, errQAOrganization) {
|
||||
code = "organization_unavailable"
|
||||
message = "通讯录或区域配置读取失败,未将不可用数据伪装成空列,请重试"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -36,9 +37,14 @@ func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
raw, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
var fields map[string]json.RawMessage
|
||||
var extra any
|
||||
invalidJSON := readErr != nil || json.Unmarshal(raw, &fields) != nil || fields == nil || fields["base_revision"] == nil || walkQualityJSON(check) != nil || check.Decode(&extra) != io.EOF
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
if invalidJSON || decoder.Decode(&request) != nil || decoder.Decode(&extra) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,6 +52,12 @@ func TestQAOrganizationGuardsIdentityIntentAndErrors(t *testing.T) {
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{} {}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":null}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":null,"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[null],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[{"id":"edu","name":null}],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[],"rules":[]}`, 400},
|
||||
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
{"POST", base + "/preview", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
} {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package httpapi
|
||||
|
||||
import "knowledge-governance/internal/dobotaiops"
|
||||
|
||||
func qaPreviewText(s string) string {
|
||||
r := []rune(s)
|
||||
if len(r) > 400 {
|
||||
return string(r[:400]) + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Summaries never replace immutable business content or a full export response.
|
||||
func qaRecordPreview(item dobotaiops.Record) dobotaiops.Record {
|
||||
item.ContentProjection = "summary"
|
||||
item.Question = qaPreviewText(item.Question)
|
||||
item.Answer = qaPreviewText(item.Answer)
|
||||
fields := make(map[string]string, len(item.MasterFields))
|
||||
for key, value := range item.MasterFields {
|
||||
if key == "question" || key == "answer" || key == "question_chinese" {
|
||||
value = qaPreviewText(value)
|
||||
}
|
||||
fields[key] = value
|
||||
}
|
||||
item.MasterFields = fields
|
||||
item.References = nil
|
||||
item.Media = nil
|
||||
return item
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type qaPreviewSpy struct {
|
||||
qaOpsSpy
|
||||
record dobotaiops.Record
|
||||
}
|
||||
|
||||
func (s *qaPreviewSpy) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
s.query = q
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{s.record}, Total: 1}, nil
|
||||
}
|
||||
func TestQALightweightListPreservesFullRecordAndRejectsUnknownProjection(t *testing.T) {
|
||||
full := strings.Repeat("长😀", 900)
|
||||
spy := &qaPreviewSpy{record: dobotaiops.Record{ID: "preview-fixture", Question: full, Answer: full, MasterFields: map[string]string{"question_chinese": full, "product_category": "MG400"}, References: json.RawMessage(`[{"content":"private-reference-body"}]`), Media: json.RawMessage(`[{"url":"private-media"}]`)}}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["admin-qa-fixture"] = "usr-boss"
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsTenantKey: "approved-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
|
||||
for _, mode := range []string{"summary", "full", "invalid"} {
|
||||
req := httptest.NewRequest("GET", base+"&projection="+mode, nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
|
||||
out := httptest.NewRecorder()
|
||||
h.ServeHTTP(out, req)
|
||||
if mode == "invalid" {
|
||||
if out.Code != 400 {
|
||||
t.Fatal("unknown projection accepted")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if out.Code != 200 {
|
||||
t.Fatalf("projection %s status %d", mode, out.Code)
|
||||
}
|
||||
var data struct{ Data dobotaiops.RecordPage }
|
||||
if json.Unmarshal(out.Body.Bytes(), &data) != nil || len(data.Data.Items) != 1 {
|
||||
t.Fatal("invalid page")
|
||||
}
|
||||
row := data.Data.Items[0]
|
||||
if mode == "summary" {
|
||||
if utf8.RuneCountInString(row.Answer) > 401 || row.Answer == full || strings.Contains(out.Body.String(), "private-reference-body") || strings.Contains(out.Body.String(), "private-media") {
|
||||
t.Fatal("summary leaked full content")
|
||||
}
|
||||
} else if row.Answer != full || !strings.Contains(out.Body.String(), "private-reference-body") {
|
||||
t.Fatal("full export content changed")
|
||||
}
|
||||
}
|
||||
if spy.record.Answer != full || spy.record.MasterFields["question_chinese"] != full {
|
||||
t.Fatal("preview mutated original")
|
||||
}
|
||||
_ = http.StatusOK
|
||||
}
|
||||
|
||||
func TestQARecordsAcceptFiveExactFiltersAndRejectUnsupportedValues(t *testing.T) {
|
||||
spy := &qaOpsSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["admin-qa-fixture"] = "usr-boss"
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsTenantKey: "approved-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
|
||||
for _, suffix := range []string{"&coverage=是&is_correct=否&product_category=MG400&problem_type=参数&root_cause=知识缺失", "&root_cause=__empty__"} {
|
||||
req := httptest.NewRequest("GET", base+suffix, nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
|
||||
out := httptest.NewRecorder()
|
||||
h.ServeHTTP(out, req)
|
||||
if out.Code != 200 || len(spy.query.Filters) == 0 {
|
||||
t.Fatalf("filter not forwarded: %d", out.Code)
|
||||
}
|
||||
}
|
||||
for _, suffix := range []string{"&coverage=invalid", "&is_correct=是&is_correct=否", "&product_category=" + strings.Repeat("x", 501)} {
|
||||
req := httptest.NewRequest("GET", base+suffix, nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
|
||||
out := httptest.NewRecorder()
|
||||
h.ServeHTTP(out, req)
|
||||
if out.Code != 400 {
|
||||
t.Fatal("invalid filters accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/strictjson"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -22,6 +23,21 @@ type QAQualityStore interface {
|
||||
Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error)
|
||||
}
|
||||
|
||||
type storedQAQualityReader interface {
|
||||
ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
}
|
||||
|
||||
func qaQualityViews(ctx context.Context, c Config, records []dobotaiops.Record) (map[string]qaopsquality.View, error) {
|
||||
if reader, ok := c.QAOps.(storedQAQualityReader); ok {
|
||||
keys := make([]dobotaiops.QualityKey, 0, len(records))
|
||||
for _, r := range records {
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.ID, InputHash: r.QualityInputHash})
|
||||
}
|
||||
return reader.ReadStoredQuality(ctx, keys)
|
||||
}
|
||||
return c.QAQuality.Observe(ctx, records)
|
||||
}
|
||||
|
||||
type qaQualityReader interface {
|
||||
ReadQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
}
|
||||
@@ -44,7 +60,7 @@ func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Recor
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, []dobotaiops.Record{*item})
|
||||
views, err := qaQualityViews(ctx, c, []dobotaiops.Record{*item})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -52,14 +68,31 @@ func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Recor
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
item.Quality, err = json.Marshal(v)
|
||||
return attachQAQualityView(item, v)
|
||||
}
|
||||
|
||||
func attachQAQualityView(item *dobotaiops.Record, view qaopsquality.View) error {
|
||||
// A vote may change between the payload and quality reads; return the vote
|
||||
// that actually produced this decision, not a contradictory older snapshot.
|
||||
if view.MasterFeedback != nil && item.RecordOrigin != "" {
|
||||
item.Feedback = *view.MasterFeedback
|
||||
fields := make(map[string]string, len(item.MasterFields)+1)
|
||||
for key, value := range item.MasterFields {
|
||||
fields[key] = value
|
||||
}
|
||||
fields["is_correct"] = map[string]string{"correct": "是", "incorrect": "否", "pending": "待确认"}[view.Effective.Correctness]
|
||||
item.MasterFields = fields
|
||||
}
|
||||
raw, err := json.Marshal(view)
|
||||
item.Quality = raw
|
||||
return err
|
||||
}
|
||||
|
||||
func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordPage) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, page.Items)
|
||||
views, err := qaQualityViews(ctx, c, page.Items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -68,7 +101,7 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
page.Items[i].Quality, err = json.Marshal(v)
|
||||
err = attachQAQualityView(&page.Items[i], v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -80,42 +113,15 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
|
||||
dobotaiops.AddRecordColumns(page, columns...)
|
||||
return nil
|
||||
}
|
||||
func walkQualityJSON(d *json.Decoder) error {
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
if delimiter, ok := token.(json.Delim); ok {
|
||||
if delimiter != '{' && delimiter != '[' {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for d.More() {
|
||||
if delimiter == '{' {
|
||||
key, e := d.Token()
|
||||
name, ok := key.(string)
|
||||
if e != nil || !ok || keys[name] {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys[name] = true
|
||||
}
|
||||
if walkQualityJSON(d) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
_, err = d.Token()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func walkQualityJSON(d *json.Decoder) error { return strictjson.Walk(d) }
|
||||
func decodeQualityJSON(w http.ResponseWriter, r *http.Request, target any, required ...string) error {
|
||||
return decodeGovernanceJSON(w, r, target, 64<<10, required...)
|
||||
}
|
||||
func decodeGovernanceJSON(w http.ResponseWriter, r *http.Request, target any, maxBytes int64, required ...string) error {
|
||||
if r.URL.RawQuery != "" {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10))
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBytes))
|
||||
if err != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
@@ -197,7 +203,12 @@ func qaQualityQuery(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
views, err := c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
var views map[string]qaopsquality.View
|
||||
if stored, ok := c.QAOps.(storedQAQualityReader); ok {
|
||||
views, err = stored.ReadStoredQuality(r.Context(), scope.Keys)
|
||||
} else {
|
||||
views, err = c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
}
|
||||
if err != nil || len(views) != len(scope.Keys) {
|
||||
if err == nil {
|
||||
err = qaopsquality.ErrUnavailable
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAUsageConsumesTheCustomRegionCatalog(t *testing.T) {
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "fixture-directory", Regions: []qaopsorg.RegionDefinition{{ID: "edu", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "edu"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "a", Name: "示例部门"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"a"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
usage := summarizeQAUsage(dobotaiops.UsageGroups{Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-person"}, Total: 3, Succeeded: 2, Failed: 1}}}, p, dobotaiops.RecordQuery{})
|
||||
if usage.Questions != 3 || usage.IdentifiedUsers != 1 {
|
||||
t.Fatal("the historical whitelist dropped custom-region events")
|
||||
}
|
||||
found := false
|
||||
for _, row := range usage.Rows {
|
||||
if row.Key == "国内教育" {
|
||||
found = true
|
||||
if row.Questions != 3 || row.RosterPeople == nil || *row.RosterPeople != 1 || row.Users == nil || *row.Users != 1 {
|
||||
t.Fatal("custom-region counts or roster denominator were lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("custom-region row missing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type weeklyDraftStore interface {
|
||||
ReadWeeklyDraft(context.Context, string, time.Time) (qaopsmirror.WeeklyDraft, error)
|
||||
SaveWeeklyDraft(context.Context, string, qaopsmirror.WeeklyDraftRequest, string, time.Time) (qaopsmirror.WeeklyDraftReceipt, error)
|
||||
PrefillWeeklyDraft(context.Context, string, qaopsmirror.WeeklyDraftPrefillRequest, string, time.Time) (qaopsmirror.WeeklyDraftReceipt, error)
|
||||
}
|
||||
|
||||
func weeklyDraftError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, qaopsquality.ErrConflict):
|
||||
writeJSON(w, 409, map[string]string{"error": "本周草稿已被其他窗口修改;你的文字未被覆盖,请先下载或核对服务器版本", "code": "weekly_draft_conflict"})
|
||||
case errors.Is(err, dobotaiops.ErrInvalidQuery):
|
||||
writeJSON(w, 400, map[string]string{"error": "周次或草稿内容无效,请使用已到达的合法ISO周,正文不超过256KiB", "code": "weekly_draft_invalid"})
|
||||
default:
|
||||
writeJSON(w, 503, map[string]string{"error": "草稿存储暂不可用,请保留文字并重试;未标记为已保存", "code": "weekly_draft_unavailable"})
|
||||
}
|
||||
}
|
||||
func qaWeeklyDraftRead(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
weeklyDraftError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
store, ok := c.QAOps.(weeklyDraftStore)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
weeklyDraftError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
out, err := store.ReadWeeklyDraft(r.Context(), r.PathValue("week"), c.Now())
|
||||
if err != nil {
|
||||
weeklyDraftError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": out})
|
||||
}
|
||||
func qaWeeklyDraftWrite(w http.ResponseWriter, r *http.Request, c Config, prefill bool) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-draft") {
|
||||
return
|
||||
}
|
||||
store, ok := c.QAOps.(weeklyDraftStore)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
weeklyDraftError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
var out qaopsmirror.WeeklyDraftReceipt
|
||||
var err error
|
||||
if prefill {
|
||||
var q qaopsmirror.WeeklyDraftPrefillRequest
|
||||
if decodeQualityJSON(w, r, &q, "base_revision", "nonce") != nil {
|
||||
weeklyDraftError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
out, err = store.PrefillWeeklyDraft(r.Context(), r.PathValue("week"), q, identity.Username, c.Now())
|
||||
} else {
|
||||
var q qaopsmirror.WeeklyDraftRequest
|
||||
if decodeGovernanceJSON(w, r, &q, 512<<10, "base_revision", "nonce", "markdown") != nil {
|
||||
weeklyDraftError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
out, err = store.SaveWeeklyDraft(r.Context(), r.PathValue("week"), q, identity.Username, c.Now())
|
||||
}
|
||||
if err != nil {
|
||||
weeklyDraftError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": out})
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qawemail"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type weeklyMailStore interface {
|
||||
ReadSettings(context.Context) (qawemail.Settings, error)
|
||||
SaveSettings(context.Context, string, qawemail.SettingsInput) (qawemail.Settings, error)
|
||||
Confirm(context.Context, string, string) (qawemail.Confirmation, error)
|
||||
Unconfirm(context.Context, string) error
|
||||
ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error)
|
||||
Sends(context.Context, string) ([]qawemail.Send, error)
|
||||
TestSend(context.Context, string) (string, error)
|
||||
SaveDashboardImage(context.Context, string, []byte) error
|
||||
SendDue(context.Context, time.Time) (qawemail.DueResult, error)
|
||||
}
|
||||
|
||||
func weeklyMailError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, qawemail.ErrConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "发送设置已被其他人修改,请重新读取后再保存"})
|
||||
case errors.Is(err, qawemail.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "发送设置无效:请检查服务器、发件地址、收件人与时间"})
|
||||
case errors.Is(err, qawemail.ErrUnavailable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "周报邮件暂不可用,请稍后重试;未标记为已发送"})
|
||||
default:
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func qaWeeklyMailSettings(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := c.QAWeeklyMail.(weeklyMailStore)
|
||||
if !ok {
|
||||
weeklyMailError(w, qawemail.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
settings, err := store.ReadSettings(r.Context())
|
||||
if err != nil {
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": settings})
|
||||
case http.MethodPost:
|
||||
if !authorizeQAIntent(w, r, "qa-weekly-mail") {
|
||||
return
|
||||
}
|
||||
if identity, ok := sessionFrom(r.Context()); !ok || identity.Role != "admin" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可修改邮件发送设置"})
|
||||
return
|
||||
}
|
||||
var input qawemail.SettingsInput
|
||||
if decodeQualityJSON(w, r, &input) != nil {
|
||||
weeklyMailError(w, qawemail.ErrInvalid)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
actor := identity.Username
|
||||
settings, err := store.SaveSettings(r.Context(), actor, input)
|
||||
if err != nil {
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": settings})
|
||||
default:
|
||||
w.Header().Set("Allow", "GET, POST")
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "不支持的方法"})
|
||||
}
|
||||
}
|
||||
|
||||
func qaWeeklyMailConfirm(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet && !authorizeQAIntent(w, r, "qa-weekly-mail") {
|
||||
return
|
||||
}
|
||||
store, ok := c.QAWeeklyMail.(weeklyMailStore)
|
||||
if !ok {
|
||||
weeklyMailError(w, qawemail.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
week := r.PathValue("week")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
confirmation, err := store.ReadConfirmation(r.Context(), week)
|
||||
if err != nil {
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"confirmation": confirmation}})
|
||||
case http.MethodPost:
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
actor := identity.Username
|
||||
confirmation, err := store.Confirm(r.Context(), week, actor)
|
||||
if err != nil {
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"confirmation": confirmation}})
|
||||
case http.MethodDelete:
|
||||
if err := store.Unconfirm(r.Context(), week); err != nil {
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"confirmation": nil}})
|
||||
default:
|
||||
w.Header().Set("Allow", "GET, POST, DELETE")
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "不支持的方法"})
|
||||
}
|
||||
}
|
||||
|
||||
func qaWeeklyMailSends(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
store, ok := c.QAWeeklyMail.(weeklyMailStore)
|
||||
if !ok {
|
||||
weeklyMailError(w, qawemail.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
sends, err := store.Sends(r.Context(), r.URL.Query().Get("week"))
|
||||
if err != nil {
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"sends": sends}})
|
||||
}
|
||||
|
||||
func qaWeeklyMailTest(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") {
|
||||
return
|
||||
}
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || identity.Role != "admin" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可发送测试邮件"})
|
||||
return
|
||||
}
|
||||
store, found := c.QAWeeklyMail.(weeklyMailStore)
|
||||
if !found {
|
||||
weeklyMailError(w, qawemail.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Week string `json:"week"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request) != nil {
|
||||
weeklyMailError(w, qawemail.ErrInvalid)
|
||||
return
|
||||
}
|
||||
messageID, err := store.TestSend(r.Context(), request.Week)
|
||||
if err != nil {
|
||||
if errors.Is(err, qawemail.ErrInvalid) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请先保存该周周报正文,并确认已配置服务器、发件人、收件人与授权码"})
|
||||
return
|
||||
}
|
||||
reason := err.Error()
|
||||
if len(reason) > 300 {
|
||||
reason = reason[:300]
|
||||
}
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "测试发送失败:" + reason})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"sent": true, "week": request.Week, "message_id": messageID}})
|
||||
}
|
||||
|
||||
func qaWeeklyMailImage(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") {
|
||||
return
|
||||
}
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || identity.Role != "admin" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可上传周报附图"})
|
||||
return
|
||||
}
|
||||
store, found := c.QAWeeklyMail.(weeklyMailStore)
|
||||
if !found {
|
||||
weeklyMailError(w, qawemail.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
PNGBase64 string `json:"png_base64"`
|
||||
}
|
||||
// The chart is megabytes of base64, far above the tiny quality-edit limit.
|
||||
if decodeGovernanceJSON(w, r, &request, 12<<20) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "看板图片数据无效或过大(上限 8MB)"})
|
||||
return
|
||||
}
|
||||
png, err := base64.StdEncoding.DecodeString(request.PNGBase64)
|
||||
if err != nil || len(png) < 8 || len(png) > 8<<20 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "图片无效或超过 8MB"})
|
||||
return
|
||||
}
|
||||
if err := store.SaveDashboardImage(r.Context(), r.PathValue("week"), png); err != nil {
|
||||
if errors.Is(err, qawemail.ErrInvalid) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请先确认本周周报,再附上统计看板图片"})
|
||||
return
|
||||
}
|
||||
weeklyMailError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"saved": true, "bytes": len(png)}})
|
||||
}
|
||||
@@ -19,6 +19,8 @@ import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
@@ -102,11 +104,14 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAAI *qaopsai.Store
|
||||
QAAITrustTLSProxy bool
|
||||
QAQuality QAQualityStore
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
QAOps QAOpsReader
|
||||
QAWeeklyMail any
|
||||
QAOpsTenantKey string
|
||||
QAOpsEnabled bool
|
||||
QAOpsProblem string
|
||||
@@ -142,8 +147,10 @@ type Config struct {
|
||||
// DingtalkSources 枚举「我账号下能看到」的钉钉知识库与钉盘空间(只读,dws)。
|
||||
// 未接线时对应路由返回 501,页面显示"列不出来"而不是空列表。
|
||||
DingtalkSources dingtalkSourcesLister
|
||||
NewID func() (string, error)
|
||||
Auth *AuthConfig
|
||||
// DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。
|
||||
DingtalkDocuments dingtalkDocLister
|
||||
NewID func() (string, error)
|
||||
Auth *AuthConfig
|
||||
}
|
||||
|
||||
func NewHandler(config Config) (http.Handler, error) {
|
||||
@@ -176,6 +183,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
registerQAAIRoutes(mux, config)
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { qaQualityHistory(w, r, config) })
|
||||
@@ -188,9 +198,30 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/preview", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("PUT /api/v1/qa-ops/organization/regions", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/sync", func(w http.ResponseWriter, r *http.Request) { qaRecordsSync(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/sync", func(w http.ResponseWriter, r *http.Request) { qaRecordsSync(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
qaOpsStatus(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-drafts/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftRead(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-drafts/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftWrite(w, r, config, false) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-drafts/{week}/prefill", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftWrite(w, r, config, true) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/settings", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSettings(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/settings", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSettings(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
|
||||
mux.HandleFunc("DELETE /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/sends", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSends(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/test", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailTest(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailImage(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/field-options", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldOptions(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/fields", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldPatch(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/records", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, listQAOpsRecords) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/records/{id}", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, getQAOpsRecord) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/quality/query", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualityQuery) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualityReview) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualityHistory) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/records/{id}/quality/inputs/{epoch}", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualitySnapshot) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
listQAOpsRecords(w, r, config)
|
||||
})
|
||||
@@ -367,6 +398,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/monitor/knowledge-bases/{id}/files", func(w http.ResponseWriter, r *http.Request) {
|
||||
monitorFiles(w, r, config.Monitor)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/monitor/tasks", func(w http.ResponseWriter, r *http.Request) {
|
||||
listMonitorTasks(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/monitor/metrics", func(w http.ResponseWriter, r *http.Request) {
|
||||
monitorMetrics(w, r, config.Monitor)
|
||||
})
|
||||
@@ -388,6 +422,7 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("DELETE /api/v1/filename-filters", func(w http.ResponseWriter, r *http.Request) {
|
||||
mutateFilenameFilter(w, r, config, true)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/source-connections/audit", func(w http.ResponseWriter, r *http.Request) { listSourceAudit(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/source-connections", func(w http.ResponseWriter, r *http.Request) {
|
||||
listSourceConnections(w, r, config.Store)
|
||||
})
|
||||
@@ -397,6 +432,13 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/dingtalk-spaces", func(w http.ResponseWriter, r *http.Request) {
|
||||
registerDingtalkSpace(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/source-catalog/available", func(w http.ResponseWriter, r *http.Request) {
|
||||
listAvailableSources(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/source-catalog/validate", func(w http.ResponseWriter, r *http.Request) {
|
||||
validateSourceSelection(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/dingtalk-spaces/credential-status", func(w http.ResponseWriter, r *http.Request) { readDWSCredentials(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/dingtalk-spaces/available", func(w http.ResponseWriter, r *http.Request) {
|
||||
listDingtalkSources(w, r, config)
|
||||
})
|
||||
@@ -518,6 +560,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
})
|
||||
// 需下架条目的移除入口:把「被禁止导入但仍存活在测试库」的知识从测试库移除
|
||||
// (置 disabling + 入队既有 test.remove 工作流)。与开始处理同级:engineer 即可。
|
||||
mux.HandleFunc("POST /api/v1/test-publications/{id}/removal-retry", func(w http.ResponseWriter, r *http.Request) {
|
||||
retryMonitorRemoval(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/test-publications/{id}/removal", func(w http.ResponseWriter, r *http.Request) {
|
||||
startTestPublicationRemoval(w, r, config)
|
||||
})
|
||||
@@ -548,9 +593,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.authRoutes(mux)
|
||||
config.userRoutes(mux)
|
||||
return config.Auth.authenticate(mux), nil
|
||||
return masterNoStore(config.Auth.authenticate(mux)), nil
|
||||
}
|
||||
return mux, nil
|
||||
return masterNoStore(mux), nil
|
||||
}
|
||||
|
||||
type createJobRequest struct {
|
||||
@@ -569,7 +614,7 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON request"})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) {
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) || strings.HasPrefix(input.Type, qaopsmirror.SyncJobPrefix) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type sourceAuditReader interface {
|
||||
ListSourceAudit(context.Context, int, int) (postgresstore.SourceAuditPage, error)
|
||||
}
|
||||
|
||||
func listSourceAudit(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := 100, 0
|
||||
for key, target := range map[string]*int{"limit": &limit, "offset": &offset} {
|
||||
if value := r.URL.Query().Get(key); value != "" {
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid pagination"})
|
||||
return
|
||||
}
|
||||
*target = n
|
||||
}
|
||||
}
|
||||
if limit < 1 || limit > 100 || offset < 0 {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid pagination"})
|
||||
return
|
||||
}
|
||||
reader, ok := config.Store.(sourceAuditReader)
|
||||
if !ok {
|
||||
writeJSON(w, 501, map[string]string{"error": "audit not configured"})
|
||||
return
|
||||
}
|
||||
page, err := reader.ListSourceAudit(r.Context(), limit, offset)
|
||||
if err != nil {
|
||||
writeJSON(w, 500, map[string]string{"error": "无法读取数据源操作记录"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, map[string]any{"data": page})
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSourceAuditRequiresAdmin(t *testing.T) {
|
||||
if got := classifyRole(http.MethodGet, "/api/v1/source-connections/audit"); got != roleAdmin {
|
||||
t.Fatalf("audit exposes actors: required role %s", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
// dingtalkDocLister 是本路由需要的文档能力面:列在线文档/表格、并真实读一次确认可读。
|
||||
// 与知识库/钉盘共用同一份 dws 凭据,注入方在 cmd/api。
|
||||
type dingtalkDocLister interface {
|
||||
ListDingtalkDocuments(ctx context.Context, query string, limit int) (dingtalkdiscovery.DocResult, error)
|
||||
ValidateDingtalkDocument(ctx context.Context, node string) (dingtalkdiscovery.DocumentNode, error)
|
||||
}
|
||||
|
||||
// availableItem 是「添加数据源」向导第一步展示的候选条目,四类来源同一形状。
|
||||
type availableItem struct {
|
||||
Ref string `json:"ref"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
var availableSourceTypes = map[string]bool{"wiki": true, "drive": true, "doc": true, "pp": true}
|
||||
|
||||
// listAvailableSources 处理 GET /api/v1/source-catalog/available?type=&q=&limit=:
|
||||
// 向导用它列「可加入的数据源」。类型不同,形状相同——前端不需要为每类写一套。
|
||||
func listAvailableSources(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
kind := strings.TrimSpace(r.URL.Query().Get("type"))
|
||||
if !availableSourceTypes[kind] {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type 必须是 wiki、drive、doc 或 pp"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
limit := 50
|
||||
if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" {
|
||||
if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && parsed <= 200 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
query := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
items := make([]availableItem, 0, 16)
|
||||
notice := ""
|
||||
switch kind {
|
||||
case "wiki", "drive":
|
||||
lister := config.DingtalkSources
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
|
||||
return
|
||||
}
|
||||
result, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
writeDiscoveryFailure(w, err)
|
||||
return
|
||||
}
|
||||
if kind == "wiki" {
|
||||
for _, base := range result.KnowledgeBases {
|
||||
items = append(items, availableItem{Ref: base.URL, Name: base.Name, Kind: "wiki", URL: base.URL})
|
||||
}
|
||||
notice = result.KnowledgeNotice
|
||||
} else {
|
||||
for _, space := range result.DriveSpaces {
|
||||
items = append(items, availableItem{Ref: dingtalkdiscovery.SpaceURL(space.SpaceID), Name: space.Name, Kind: "drive", URL: dingtalkdiscovery.SpaceURL(space.SpaceID)})
|
||||
}
|
||||
notice = result.DriveNotice
|
||||
}
|
||||
case "doc":
|
||||
lister := config.DingtalkDocuments
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk document discovery is not wired"})
|
||||
return
|
||||
}
|
||||
result, err := lister.ListDingtalkDocuments(ctx, query, limit)
|
||||
if err != nil {
|
||||
writeDiscoveryFailure(w, err)
|
||||
return
|
||||
}
|
||||
for _, doc := range result.Documents {
|
||||
items = append(items, availableItem{
|
||||
Ref: doc.NodeID, Name: doc.Name, Kind: "doc",
|
||||
ContentType: doc.ContentType, URL: doc.URL, UpdatedAt: doc.UpdatedAt,
|
||||
})
|
||||
}
|
||||
notice = result.Notice
|
||||
case "pp":
|
||||
// PP 是公开只读目录:没有可枚举的账号级列表,向导要求直接给资料中心地址,
|
||||
// 由第 4 步的校验去真打一次。这里返回空列表并说明原因,不伪装成"没权限"。
|
||||
notice = "PP 资料下载中心没有可列举的账号级列表,请在第 2 步填写资料中心地址。"
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"type": kind, "items": items, "notice": notice, "fetched_at": time.Now().UTC(),
|
||||
}})
|
||||
}
|
||||
|
||||
// validateSourceSelection 处理 POST /api/v1/source-catalog/validate:
|
||||
// 添加前真读一次,读不到就不让进下一步——避免加入一堆永远同步不了的来源。
|
||||
func validateSourceSelection(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Type string `json:"type"`
|
||||
Refs []string `json:"refs"`
|
||||
}
|
||||
if decodeJSONStrict(r, &body) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_request_body"})
|
||||
return
|
||||
}
|
||||
kind := strings.TrimSpace(body.Type)
|
||||
if !availableSourceTypes[kind] || len(body.Refs) == 0 || len(body.Refs) > 50 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type 无效,或一次校验的条目数不在 1–50 之间"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
switch kind {
|
||||
case "doc":
|
||||
lister := config.DingtalkDocuments
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk document discovery is not wired"})
|
||||
return
|
||||
}
|
||||
verified := make([]map[string]string, 0, len(body.Refs))
|
||||
for _, ref := range body.Refs {
|
||||
doc, err := lister.ValidateDingtalkDocument(ctx, ref)
|
||||
if err != nil {
|
||||
writeDiscoveryFailure(w, err)
|
||||
return
|
||||
}
|
||||
verified = append(verified, map[string]string{"ref": doc.NodeID, "name": doc.Name, "content_type": doc.ContentType})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"ok": true, "type": kind, "items": verified, "discovered": len(verified),
|
||||
}})
|
||||
case "wiki", "drive":
|
||||
lister := config.DingtalkSources
|
||||
if lister == nil {
|
||||
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
|
||||
return
|
||||
}
|
||||
result, err := lister.ListAvailableDingtalkSources(ctx)
|
||||
if err != nil {
|
||||
writeDiscoveryFailure(w, err)
|
||||
return
|
||||
}
|
||||
known := map[string]string{}
|
||||
if kind == "wiki" {
|
||||
for _, base := range result.KnowledgeBases {
|
||||
known[base.URL] = base.Name
|
||||
}
|
||||
} else {
|
||||
for _, space := range result.DriveSpaces {
|
||||
known[dingtalkdiscovery.SpaceURL(space.SpaceID)] = space.Name
|
||||
}
|
||||
}
|
||||
verified := make([]map[string]string, 0, len(body.Refs))
|
||||
for _, ref := range body.Refs {
|
||||
name, ok := known[strings.TrimSpace(ref)]
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "当前钉钉账号已看不到该来源,请刷新后再选"})
|
||||
return
|
||||
}
|
||||
verified = append(verified, map[string]string{"ref": ref, "name": name})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"ok": true, "type": kind, "items": verified, "discovered": len(verified),
|
||||
}})
|
||||
case "pp":
|
||||
// PP 的可用性由真正的下载探测在登记流程里判定,这里只做形式校验。
|
||||
for _, ref := range body.Refs {
|
||||
if !strings.HasPrefix(strings.TrimSpace(ref), "http") {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "PP 需要 http(s) 资料中心地址"})
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"ok": true, "type": kind, "discovered": len(body.Refs)}})
|
||||
}
|
||||
}
|
||||
|
||||
func writeDiscoveryFailure(w http.ResponseWriter, err error) {
|
||||
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "dingtalk_discovery_unavailable",
|
||||
"hint": "dws 未登录或缺少读权限;请刷新钉钉会话,或让管理员检查 dws 凭据。",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list sources"})
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
)
|
||||
|
||||
type fakeDingtalkDocuments struct {
|
||||
docs dingtalkdiscovery.DocResult
|
||||
listErr error
|
||||
validated []string
|
||||
validateAs dingtalkdiscovery.DocumentNode
|
||||
validateEr error
|
||||
}
|
||||
|
||||
func (f *fakeDingtalkDocuments) ListDingtalkDocuments(_ context.Context, _ string, _ int) (dingtalkdiscovery.DocResult, error) {
|
||||
return f.docs, f.listErr
|
||||
}
|
||||
|
||||
func (f *fakeDingtalkDocuments) ValidateDingtalkDocument(_ context.Context, node string) (dingtalkdiscovery.DocumentNode, error) {
|
||||
f.validated = append(f.validated, node)
|
||||
return f.validateAs, f.validateEr
|
||||
}
|
||||
|
||||
func availableRequest(role, url string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodGet, url, nil)
|
||||
if role == "" {
|
||||
return request
|
||||
}
|
||||
return request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
|
||||
}
|
||||
|
||||
func decodeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode body %s: %v", rec.Body.String(), err)
|
||||
}
|
||||
data, _ := payload["data"].(map[string]any)
|
||||
return data
|
||||
}
|
||||
|
||||
func TestListAvailableSourcesKeepsOneShapeForEveryType(t *testing.T) {
|
||||
docs := &fakeDingtalkDocuments{docs: dingtalkdiscovery.DocResult{Documents: []dingtalkdiscovery.DocumentNode{
|
||||
{NodeID: "node-a", Name: "售后周会纪要", ContentType: "ALIDOC", URL: "https://alidocs.dingtalk.com/i/nodes/node-a"},
|
||||
{NodeID: "node-b", Name: "服务工单统计", ContentType: "ALISHEET"},
|
||||
}}}
|
||||
config := Config{DingtalkDocuments: docs}
|
||||
rec := httptest.NewRecorder()
|
||||
listAvailableSources(rec, availableRequest(roleAdmin, "/api/v1/source-catalog/available?type=doc"), config)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
data := decodeEnvelope(t, rec)
|
||||
items, _ := data["items"].([]any)
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("items = %d, want 2", len(items))
|
||||
}
|
||||
first, _ := items[0].(map[string]any)
|
||||
// 四类来源同一形状:ref/name/kind 一定在,类型差异只放在 content_type。
|
||||
for _, key := range []string{"ref", "name", "kind"} {
|
||||
if _, ok := first[key]; !ok {
|
||||
t.Fatalf("item missing %q: %v", key, first)
|
||||
}
|
||||
}
|
||||
if first["kind"] != "doc" || first["content_type"] != "ALIDOC" {
|
||||
t.Fatalf("doc item = %v", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAvailableSourcesRejectsUnknownTypesAndReportsMissingWiring(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
listAvailableSources(rec, availableRequest(roleAdmin, "/api/v1/source-catalog/available?type=__nope__"), Config{})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("unknown type = %d, want 400", rec.Code)
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
listAvailableSources(rec, availableRequest(roleAdmin, "/api/v1/source-catalog/available?type=doc"), Config{})
|
||||
if rec.Code != http.StatusNotImplemented {
|
||||
t.Fatalf("unwired doc = %d, want 501", rec.Code)
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
listAvailableSources(rec, availableRequest("", "/api/v1/source-catalog/available?type=doc"), Config{})
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("anonymous = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAvailableSourcesExplainsWhyPpHasNoAccountLevelList(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
listAvailableSources(rec, availableRequest(roleAdmin, "/api/v1/source-catalog/available?type=pp"), Config{})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
data := decodeEnvelope(t, rec)
|
||||
if items, _ := data["items"].([]any); len(items) != 0 {
|
||||
t.Fatalf("pp items = %d, want 0", len(items))
|
||||
}
|
||||
if notice, _ := data["notice"].(string); !strings.Contains(notice, "资料中心地址") {
|
||||
t.Fatalf("notice = %q", notice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSourceSelectionProvesDocumentsAreReadable(t *testing.T) {
|
||||
docs := &fakeDingtalkDocuments{validateAs: dingtalkdiscovery.DocumentNode{NodeID: "node-a", Name: "售后周会纪要", ContentType: "ALIDOC"}}
|
||||
body, _ := json.Marshal(map[string]any{"type": "doc", "refs": []string{"node-a"}})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/validate", bytes.NewReader(body))
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
validateSourceSelection(rec, request, Config{DingtalkDocuments: docs})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(docs.validated) != 1 || docs.validated[0] != "node-a" {
|
||||
t.Fatalf("validated = %v", docs.validated)
|
||||
}
|
||||
if data := decodeEnvelope(t, rec); data["discovered"] != float64(1) {
|
||||
t.Fatalf("discovered = %v", data["discovered"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSourceSelectionFailsWhenTheDocumentIsGone(t *testing.T) {
|
||||
docs := &fakeDingtalkDocuments{validateEr: dingtalkdiscovery.ErrUnavailable}
|
||||
body, _ := json.Marshal(map[string]any{"type": "doc", "refs": []string{"node-gone"}})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/validate", bytes.NewReader(body))
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
validateSourceSelection(rec, request, Config{DingtalkDocuments: docs})
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSourceSelectionRejectsSpacesTheAccountCanNoLongerSee(t *testing.T) {
|
||||
config := Config{DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{
|
||||
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "产品知识库", URL: "https://alidocs.dingtalk.com/i/spaces/keep/overview"}},
|
||||
}}}
|
||||
body, _ := json.Marshal(map[string]any{"type": "wiki", "refs": []string{"https://alidocs.dingtalk.com/i/spaces/gone/overview"}})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/validate", bytes.NewReader(body))
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
validateSourceSelection(rec, request, config)
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409 body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSourceSelectionRejectsEmptyAndOversizedSelections(t *testing.T) {
|
||||
for _, refs := range [][]string{{}, make([]string, 51)} {
|
||||
body, _ := json.Marshal(map[string]any{"type": "doc", "refs": refs})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/validate", bytes.NewReader(body))
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
|
||||
rec := httptest.NewRecorder()
|
||||
validateSourceSelection(rec, request, Config{})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("refs=%d status = %d, want 400", len(refs), rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFreezeCancelledCaptureCannotSucceed(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
result, err := e.Run(ctx, "cancelled", func(context.Context) (string, error) { cancel(); return strings.Repeat("a", 64), nil })
|
||||
if err == nil || result.State == "succeeded" {
|
||||
t.Fatalf("cancelled work succeeded: %+v %v", result, err)
|
||||
}
|
||||
if !c.services[0].Running || !c.services[0].Healthy {
|
||||
t.Fatal("cancel prevented recovery")
|
||||
}
|
||||
}
|
||||
|
||||
type faultyControl struct {
|
||||
*fixtureControl
|
||||
mode string
|
||||
}
|
||||
|
||||
func (c *faultyControl) Stop(ctx context.Context, id string) error {
|
||||
if c.mode == "stop-noop" {
|
||||
return nil
|
||||
}
|
||||
err := c.fixtureControl.Stop(ctx, id)
|
||||
if c.mode == "lost-ack" {
|
||||
return errors.New("lost stop acknowledgement")
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (c *faultyControl) Start(ctx context.Context, id string) error {
|
||||
err := c.fixtureControl.Start(ctx, id)
|
||||
if c.mode == "unhealthy" {
|
||||
for i := range c.services {
|
||||
if c.services[i].ID == id {
|
||||
c.services[i].Healthy = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
func TestFreezeFailureBoundaries(t *testing.T) {
|
||||
for _, mode := range []string{"lost-ack", "stop-noop", "unhealthy", "new-replica", "replacement", "capture-error"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
e.control = &faultyControl{fixtureControl: c, mode: mode}
|
||||
called := false
|
||||
result, err := e.Run(context.Background(), "fault-job", func(context.Context) (string, error) {
|
||||
called = true
|
||||
switch mode {
|
||||
case "new-replica":
|
||||
c.services = append(c.services, Service{ID: "unexpected-app", Running: true, Healthy: true})
|
||||
case "replacement":
|
||||
c.services[0].ID = "replacement-app"
|
||||
case "capture-error":
|
||||
return "", errors.New("fixture error")
|
||||
}
|
||||
return strings.Repeat("a", 64), nil
|
||||
})
|
||||
if err == nil || result.State == "succeeded" {
|
||||
t.Fatalf("fault reported success: %+v %v", result, err)
|
||||
}
|
||||
if (mode == "lost-ack" || mode == "stop-noop") && called {
|
||||
t.Fatal("capture ran without verified stop")
|
||||
}
|
||||
if mode == "replacement" {
|
||||
for _, call := range c.calls {
|
||||
if strings.HasPrefix(call, "start:") {
|
||||
t.Fatal("replacement was started")
|
||||
}
|
||||
}
|
||||
} else if !c.services[0].Running {
|
||||
t.Fatal("original service not restored")
|
||||
}
|
||||
if mode == "unhealthy" || mode == "replacement" {
|
||||
j, err := e.load("fault-job")
|
||||
if err != nil || terminal(j.State) {
|
||||
t.Fatal("unverified recovery marked terminal")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestFreezeSourceLockBlocksSeparateCoordinator(t *testing.T) {
|
||||
root, c, e := freezeFixture(t)
|
||||
other, err := Open(root, "test-source", c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer other.Close()
|
||||
_, err = e.Run(context.Background(), "outer", func(context.Context) (string, error) {
|
||||
_, blocked := other.Run(context.Background(), "inner", func(context.Context) (string, error) { t.Fatal("overlapping capture"); return "", nil })
|
||||
if blocked == nil {
|
||||
t.Fatal("source lock did not block")
|
||||
}
|
||||
if err := other.Recover(context.Background()); err == nil {
|
||||
t.Fatal("recovery raced active capture")
|
||||
}
|
||||
return strings.Repeat("a", 64), nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func TestFreezeRejectsMalformedRecoveryJournal(t *testing.T) {
|
||||
for _, mode := range []string{"unknown-state", "invalid-service", "duplicate-service", "false-ownership"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
j := journal{Version: 1, Source: "test-source", Job: "invalid", Result: Result{State: "stopping"}, Services: []serviceRecord{{Service: Service{ID: "app-a", Running: true}, StopRequested: true}}}
|
||||
switch mode {
|
||||
case "unknown-state":
|
||||
j.State = "invented"
|
||||
case "invalid-service":
|
||||
j.Services[0].ID = "../../wrong"
|
||||
case "duplicate-service":
|
||||
j.Services = append(j.Services, j.Services[0])
|
||||
case "false-ownership":
|
||||
j.Services[0].Running = false
|
||||
}
|
||||
if err := e.save(j); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Recover(context.Background()); err == nil {
|
||||
t.Fatal("malformed journal accepted")
|
||||
}
|
||||
if len(c.calls) != 0 {
|
||||
t.Fatalf("malformed journal caused service writes: %v", c.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const sourceLabel = "io.knowledge-governance.freeze-source"
|
||||
const environmentLabel = "io.knowledge-governance.environment"
|
||||
const roleLabel = "io.knowledge-governance.freeze-role"
|
||||
|
||||
type DockerController struct {
|
||||
source string
|
||||
timeout time.Duration
|
||||
client *http.Client
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
func NewDockerController(socket, source string, timeout time.Duration) (*DockerController, error) {
|
||||
if !filepath.IsAbs(socket) || !validID(source) || timeout <= 0 || timeout > 5*time.Minute {
|
||||
return nil, errors.New("invalid test Docker controller configuration")
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil || info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("local Docker socket unavailable")
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
client := &http.Client{Transport: transport, Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("Docker redirects prohibited") }}
|
||||
return &DockerController{source: source, timeout: timeout, client: client, transport: transport}, nil
|
||||
}
|
||||
func (d *DockerController) Close() { d.transport.CloseIdleConnections() }
|
||||
func (d *DockerController) request(ctx context.Context, method, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, nil)
|
||||
if err != nil {
|
||||
return errors.New("invalid Docker request")
|
||||
}
|
||||
resp, err := d.client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("test Docker request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("test Docker request rejected")
|
||||
}
|
||||
if out != nil {
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
|
||||
if err != nil || len(data) > 1024*1024 || json.Unmarshal(data, out) != nil {
|
||||
return errors.New("invalid Docker response")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func dockerID(id string) bool {
|
||||
b, err := hex.DecodeString(id)
|
||||
return err == nil && len(b) == 32 && strings.ToLower(id) == id
|
||||
}
|
||||
|
||||
type dockerInspection struct {
|
||||
ID string `json:"Id"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
} `json:"Config"`
|
||||
State struct {
|
||||
Running bool
|
||||
Paused bool
|
||||
Restarting bool
|
||||
Dead bool
|
||||
Status string
|
||||
Health *struct{ Status string }
|
||||
} `json:"State"`
|
||||
}
|
||||
|
||||
func (d *DockerController) inspect(ctx context.Context, id string) (Service, error) {
|
||||
if !dockerID(id) {
|
||||
return Service{}, errors.New("immutable Docker ID required")
|
||||
}
|
||||
var data dockerInspection
|
||||
if err := d.request(ctx, "GET", "/containers/"+id+"/json", &data); err != nil {
|
||||
return Service{}, err
|
||||
}
|
||||
labels := data.Config.Labels
|
||||
if data.ID != id || labels[sourceLabel] != d.source || labels[environmentLabel] != "test" || labels[roleLabel] != "writer" {
|
||||
return Service{}, errors.New("container is not an approved test writer")
|
||||
}
|
||||
if data.State.Paused || data.State.Restarting || data.State.Dead {
|
||||
return Service{}, errors.New("test writer has unstable runtime state")
|
||||
}
|
||||
if data.State.Status != "running" && data.State.Status != "exited" && data.State.Status != "created" {
|
||||
return Service{}, errors.New("unknown test writer runtime state")
|
||||
}
|
||||
if data.State.Running != (data.State.Status == "running") {
|
||||
return Service{}, errors.New("contradictory test writer state")
|
||||
}
|
||||
healthy := data.State.Running && data.State.Health != nil && data.State.Health.Status == "healthy"
|
||||
return Service{ID: id, Running: data.State.Running, Healthy: healthy}, nil
|
||||
}
|
||||
func (d *DockerController) Inventory(ctx context.Context) ([]Service, error) {
|
||||
filters, _ := json.Marshal(map[string][]string{"label": {sourceLabel + "=" + d.source}})
|
||||
var containers []struct {
|
||||
ID string `json:"Id"`
|
||||
}
|
||||
if err := d.request(ctx, "GET", "/containers/json?all=1&filters="+url.QueryEscape(string(filters)), &containers); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(containers) == 0 || len(containers) > 256 {
|
||||
return nil, errors.New("empty or oversized test writer group")
|
||||
}
|
||||
items := make([]Service, 0, len(containers))
|
||||
seen := map[string]bool{}
|
||||
for _, container := range containers {
|
||||
if seen[container.ID] {
|
||||
return nil, errors.New("duplicate Docker instance")
|
||||
}
|
||||
seen[container.ID] = true
|
||||
s, err := d.inspect(ctx, container.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, s)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
func (d *DockerController) wait(ctx context.Context, id string, running bool) error {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s, err := d.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Running == running && (!running || s.Healthy) {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("test writer state did not settle before deadline")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only SIGTERM is sent. There is no delayed SIGKILL timer which could fire after
|
||||
// recovery starts the service again. An unresolved graceful stop remains pending
|
||||
// in the coordinator journal; running-now is not evidence of recovery.
|
||||
func (d *DockerController) Stop(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, d.timeout)
|
||||
defer cancel()
|
||||
s, err := d.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
return nil
|
||||
}
|
||||
if err = d.request(bounded, "POST", "/containers/"+id+"/kill?signal=SIGTERM", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.wait(bounded, id, false)
|
||||
}
|
||||
func (d *DockerController) Start(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, d.timeout)
|
||||
defer cancel()
|
||||
s, err := d.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
if err = d.request(bounded, "POST", "/containers/"+id+"/start", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return d.wait(bounded, id, true)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDockerControllerRefusesWrongScopeAndUnsafeRuntime(t *testing.T) {
|
||||
for _, mode := range []string{"production", "wrong-source", "storage", "paused", "restarting", "dead", "no-health", "short-id", "wrong-response-id", "duplicate"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgf-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(root)
|
||||
socket := filepath.Join(root, "s")
|
||||
listener, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := strings.Repeat("a", 64)
|
||||
if mode == "short-id" {
|
||||
id = "aaa"
|
||||
}
|
||||
writes := 0
|
||||
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
writes++
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(r.URL.Path, "/containers/json") {
|
||||
items := []map[string]string{{"Id": id}}
|
||||
if mode == "duplicate" {
|
||||
items = append(items, items[0])
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(items)
|
||||
return
|
||||
}
|
||||
labels := map[string]string{sourceLabel: "test-source", environmentLabel: "test", roleLabel: "writer"}
|
||||
switch mode {
|
||||
case "production":
|
||||
labels[environmentLabel] = "production"
|
||||
case "wrong-source":
|
||||
labels[sourceLabel] = "different-source"
|
||||
case "storage":
|
||||
labels[roleLabel] = "database"
|
||||
}
|
||||
state := map[string]any{"Running": true, "Status": "running", "Health": map[string]string{"Status": "healthy"}}
|
||||
switch mode {
|
||||
case "paused":
|
||||
state["Paused"] = true
|
||||
case "restarting":
|
||||
state["Restarting"] = true
|
||||
case "dead":
|
||||
state["Dead"] = true
|
||||
case "no-health":
|
||||
delete(state, "Health")
|
||||
}
|
||||
actualID := id
|
||||
if mode == "wrong-response-id" {
|
||||
actualID = strings.Repeat("b", 64)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"Id": actualID, "Config": map[string]any{"Labels": labels}, "State": state})
|
||||
})}
|
||||
go server.Serve(listener)
|
||||
defer server.Close()
|
||||
d, err := NewDockerController(socket, "test-source", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
journalRoot := filepath.Join(root, "j")
|
||||
if err = os.Mkdir(journalRoot, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, err := Open(journalRoot, "test-source", d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer e.Close()
|
||||
_, err = e.Run(context.Background(), "blocked", func(context.Context) (string, error) { t.Fatal("unsafe capture"); return "", nil })
|
||||
if err == nil || writes != 0 {
|
||||
t.Fatalf("unsafe source changed: err=%v writes=%d", err, writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFreezeIsolatedDocker(t *testing.T) {
|
||||
if os.Getenv("KG_FREEZE_DOCKER_ISOLATED") != "1" {
|
||||
t.Skip("explicit opt-in required for disposable local Docker fixture")
|
||||
}
|
||||
if os.Getenv("KG_FREEZE_DOCKER_CHILD") == "1" {
|
||||
d, err := NewDockerController("/var/run/docker.sock", os.Getenv("KG_FREEZE_SOURCE"), 10*time.Second)
|
||||
if err != nil {
|
||||
os.Exit(31)
|
||||
}
|
||||
e, err := Open(os.Getenv("KG_FREEZE_ROOT"), os.Getenv("KG_FREEZE_SOURCE"), d)
|
||||
if err != nil {
|
||||
os.Exit(32)
|
||||
}
|
||||
_, _ = e.Run(context.Background(), "crashed-real", func(context.Context) (string, error) { os.Exit(37); return "", nil })
|
||||
os.Exit(33)
|
||||
}
|
||||
run := func(args ...string) string {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "docker", append([]string{"--host", "unix:///var/run/docker.sock"}, args...)...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("fixture Docker command failed: %v %s", err, out)
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
image := run("image", "inspect", "busybox:1.36", "--format", "{{.Id}}")
|
||||
var token [8]byte
|
||||
if _, err := rand.Read(token[:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := "kg-freeze-test-" + hex.EncodeToString(token[:])
|
||||
var ids []string
|
||||
defer func() {
|
||||
for _, id := range ids {
|
||||
run("rm", "-f", id)
|
||||
}
|
||||
if remaining := run("ps", "-aq", "--filter", "label="+sourceLabel+"="+source); remaining != "" {
|
||||
t.Error("disposable freeze containers remain")
|
||||
}
|
||||
}()
|
||||
for _, name := range []string{"running", "originally-off"} {
|
||||
id := run("create", "--name", source+"-"+name, "--network", "none", "--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=1m", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--memory", "32m", "--cpus", "0.1", "--restart", "unless-stopped", "--label", sourceLabel+"="+source, "--label", environmentLabel+"=test", "--label", roleLabel+"=writer", "--health-cmd", "test -f /tmp/ready", "--health-interval", "1s", "--health-timeout", "1s", "--health-retries", "3", image, "sh", "-c", "trap 'exit 0' TERM; touch /tmp/ready; while :; do sleep 1 & wait $!; done")
|
||||
ids = append(ids, id)
|
||||
}
|
||||
d, err := NewDockerController("/var/run/docker.sock", source, 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
if err = d.Start(context.Background(), ids[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, err := Open(root, source, d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer e.Close()
|
||||
assertRestored := func() {
|
||||
t.Helper()
|
||||
a, err := d.inspect(context.Background(), ids[0])
|
||||
if err != nil || !a.Running || !a.Healthy {
|
||||
t.Fatalf("original running fixture not healthy: %+v %v", a, err)
|
||||
}
|
||||
b, err := d.inspect(context.Background(), ids[1])
|
||||
if err != nil || b.Running {
|
||||
t.Fatal("originally-off fixture was started")
|
||||
}
|
||||
}
|
||||
started := time.Now()
|
||||
result, err := e.Run(context.Background(), "real-success", func(context.Context) (string, error) {
|
||||
items, err := d.Inventory(context.Background())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, s := range items {
|
||||
if s.Running {
|
||||
t.Fatal("real writer active during capture")
|
||||
}
|
||||
}
|
||||
return strings.Repeat("b", 64), nil
|
||||
})
|
||||
if err != nil || result.State != "succeeded" {
|
||||
t.Fatalf("real freeze=%+v %v", result, err)
|
||||
}
|
||||
assertRestored()
|
||||
t.Logf("disposable_container_freeze_and_health_restore=%s", time.Since(started))
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestFreezeIsolatedDocker$")
|
||||
cmd.Env = append(os.Environ(), "KG_FREEZE_DOCKER_CHILD=1", "KG_FREEZE_SOURCE="+source, "KG_FREEZE_ROOT="+root)
|
||||
err = cmd.Run()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != 37 {
|
||||
t.Fatalf("crash injection did not reach stopped window: %v", err)
|
||||
}
|
||||
stopped, err := d.inspect(context.Background(), ids[0])
|
||||
if err != nil || stopped.Running {
|
||||
t.Fatal("crashed fixture was not stopped")
|
||||
}
|
||||
if err = e.Recover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertRestored()
|
||||
j, err := e.load("crashed-real")
|
||||
if err != nil || j.State != "failed" || j.Code != "interrupted" {
|
||||
t.Fatalf("bad recovery journal: %+v %v", j, err)
|
||||
}
|
||||
t.Log("real process exit -> journal reload -> original container healthy; originally-off container remains off")
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDockerControllerUsesScopedIDsAndGracefulSignal(t *testing.T) {
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgf-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(root)
|
||||
socket := filepath.Join(root, "engine.sock")
|
||||
listener, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := strings.Repeat("a", 64)
|
||||
running := true
|
||||
var writes []string
|
||||
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
if !strings.Contains(r.URL.Query().Get("filters"), "test-source") {
|
||||
t.Error("missing scope filter")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode([]map[string]string{{"Id": id}})
|
||||
case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/json"):
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"Id": id, "Config": map[string]any{"Labels": map[string]string{sourceLabel: "test-source", environmentLabel: "test", roleLabel: "writer"}}, "State": map[string]any{"Running": running, "Status": map[bool]string{true: "running", false: "exited"}[running], "Health": map[string]string{"Status": "healthy"}}})
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/kill"):
|
||||
if r.URL.Query().Get("signal") != "SIGTERM" {
|
||||
t.Error("unsafe stop signal")
|
||||
}
|
||||
writes = append(writes, "stop")
|
||||
running = false
|
||||
w.WriteHeader(204)
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/start"):
|
||||
writes = append(writes, "start")
|
||||
running = true
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
})}
|
||||
go server.Serve(listener)
|
||||
defer server.Close()
|
||||
control, err := NewDockerController(socket, "test-source", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
journalRoot := filepath.Join(root, "journal")
|
||||
if err = os.Mkdir(journalRoot, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine, err := Open(journalRoot, "test-source", control)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Close()
|
||||
result, err := engine.Run(context.Background(), "fixture-job", func(context.Context) (string, error) {
|
||||
if running {
|
||||
t.Fatal("writer was not stopped")
|
||||
}
|
||||
return strings.Repeat("b", 64), nil
|
||||
})
|
||||
if err != nil || result.State != "succeeded" || strings.Join(writes, ",") != "stop,start" {
|
||||
t.Fatalf("result=%+v err=%v writes=%v", result, err, writes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFreezeRestoresDespiteCapturePanic(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
_, _ = e.Run(context.Background(), "panic-job", func(context.Context) (string, error) { panic("fixture panic") })
|
||||
}()
|
||||
if !c.services[0].Running || !c.services[0].Healthy {
|
||||
t.Fatal("capture panic left test service stopped")
|
||||
}
|
||||
j, err := e.load("panic-job")
|
||||
if err != nil || j.State != "failed" {
|
||||
t.Fatalf("journal=%+v err=%v", j, err)
|
||||
}
|
||||
}
|
||||
func TestFreezeRestoresEvenWhenJournalBecomesUnwritable(t *testing.T) {
|
||||
root, c, e := freezeFixture(t)
|
||||
_, err := e.Run(context.Background(), "disk-failure", func(context.Context) (string, error) {
|
||||
path := filepath.Join(root, "disk-failure.json")
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(path, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Repeat("a", 64), nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("lost journal must not report success")
|
||||
}
|
||||
if !c.services[0].Running || !c.services[0].Healthy {
|
||||
t.Fatal("journal failure prevented service restoration")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
// Package libraryfreeze coordinates a test-only maintenance window. It never
|
||||
// grants production authorization or starts services which were already stopped.
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
ID string `json:"id"`
|
||||
Running bool `json:"running"`
|
||||
Healthy bool `json:"healthy"`
|
||||
}
|
||||
|
||||
// Inventory must enumerate the complete, independently scoped test writer set,
|
||||
// using immutable instance IDs. Never implement it as only the currently running
|
||||
// subset. Start must wait for readiness; callers still read back the result.
|
||||
type Controller interface {
|
||||
Inventory(context.Context) ([]Service, error)
|
||||
Stop(context.Context, string) error
|
||||
Start(context.Context, string) error
|
||||
}
|
||||
type Result struct {
|
||||
State string `json:"state"`
|
||||
SnapshotID string `json:"snapshot_id,omitempty"`
|
||||
}
|
||||
type serviceRecord struct {
|
||||
Service
|
||||
StopRequested bool `json:"stop_requested"`
|
||||
StopVerified bool `json:"stop_verified"`
|
||||
Restored bool `json:"restored"`
|
||||
}
|
||||
type journal struct {
|
||||
Version int `json:"version"`
|
||||
Source string `json:"source"`
|
||||
Job string `json:"job"`
|
||||
Result
|
||||
Services []serviceRecord `json:"services"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
type Coordinator struct {
|
||||
root *os.Root
|
||||
source string
|
||||
control Controller
|
||||
}
|
||||
|
||||
func Open(root, source string, c Controller) (*Coordinator, error) {
|
||||
if !filepath.IsAbs(root) || !validID(source) || c == nil {
|
||||
return nil, errors.New("invalid freeze configuration")
|
||||
}
|
||||
info, err := os.Lstat(root)
|
||||
if err != nil || !info.IsDir() || info.Mode().Perm() != 0700 {
|
||||
return nil, errors.New("freeze directory must be private and real")
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(root)
|
||||
if err != nil || resolved != filepath.Clean(root) {
|
||||
return nil, errors.New("freeze directory contains symlink")
|
||||
}
|
||||
r, err := os.OpenRoot(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Coordinator{root: r, source: source, control: c}, nil
|
||||
}
|
||||
func (c *Coordinator) Close() error { return c.root.Close() }
|
||||
|
||||
func (c *Coordinator) Recover(ctx context.Context) error {
|
||||
lock, err := c.lock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlock(lock)
|
||||
dir, err := c.root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dir.Close()
|
||||
entries, err := dir.ReadDir(-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Validate every journal before issuing recovery writes. Corrupt records or
|
||||
// another source's directory must not turn into broad service startup.
|
||||
var pending []journal
|
||||
for _, entry := range entries {
|
||||
if !strings.HasSuffix(entry.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
job := strings.TrimSuffix(entry.Name(), ".json")
|
||||
if !validID(job) {
|
||||
return errors.New("invalid freeze journal name")
|
||||
}
|
||||
j, err := c.load(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !terminal(j.State) {
|
||||
pending = append(pending, j)
|
||||
}
|
||||
}
|
||||
if len(pending) > 1 {
|
||||
return errors.New("multiple interrupted freezes require operator reconciliation")
|
||||
}
|
||||
for _, j := range pending {
|
||||
if err = c.restore(ctx, &j); err != nil {
|
||||
return err
|
||||
}
|
||||
j.State = "failed"
|
||||
j.Code = "interrupted"
|
||||
ended := time.Now().UTC()
|
||||
j.FinishedAt = &ended
|
||||
if err = c.save(j); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func invokeCapture(ctx context.Context, capture func(context.Context) (string, error)) (id string, err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
id = ""
|
||||
err = errors.New("candidate capture panicked")
|
||||
}
|
||||
}()
|
||||
return capture(ctx)
|
||||
}
|
||||
|
||||
func validID(s string) bool {
|
||||
if len(s) == 0 || len(s) > 128 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func terminal(s string) bool { return s == "succeeded" || s == "failed" }
|
||||
|
||||
// A kernel lock serializes the whole test writer group, not individual KBs.
|
||||
// A crash releases the lock, but leaves the write-ahead journal for recovery.
|
||||
func (c *Coordinator) lock() (*os.File, error) {
|
||||
f, err := c.root.OpenFile("operation.lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
||||
f.Close()
|
||||
return nil, errors.New("test source freeze is busy")
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
func unlock(f *os.File) { _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN); _ = f.Close() }
|
||||
func (c *Coordinator) save(j journal) error {
|
||||
data, err := json.Marshal(j)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var token [16]byte
|
||||
if _, err = rand.Read(token[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
name := "write-" + hex.EncodeToString(token[:]) + ".tmp"
|
||||
f, err := c.root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.root.Remove(name)
|
||||
defer f.Close()
|
||||
if _, err = f.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = f.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = c.root.Rename(name, j.Job+".json"); err != nil {
|
||||
return err
|
||||
}
|
||||
dir, err := c.root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dir.Close()
|
||||
return dir.Sync()
|
||||
}
|
||||
func (c *Coordinator) load(job string) (journal, error) {
|
||||
f, err := c.root.OpenFile(job+".json", os.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return journal{}, err
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > 1024*1024 {
|
||||
return journal{}, errors.New("invalid freeze journal file")
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(f, 1024*1024+1))
|
||||
if err != nil {
|
||||
return journal{}, err
|
||||
}
|
||||
var j journal
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err = dec.Decode(&j); err != nil {
|
||||
return journal{}, errors.New("invalid freeze journal")
|
||||
}
|
||||
var extra any
|
||||
if dec.Decode(&extra) != io.EOF || j.Version != 1 || j.Source != c.source || j.Job != job || !validID(j.Job) {
|
||||
return journal{}, errors.New("freeze journal identity mismatch")
|
||||
}
|
||||
switch j.State {
|
||||
case "stopping", "capturing", "restoring", "succeeded", "failed":
|
||||
default:
|
||||
return journal{}, errors.New("invalid freeze journal state")
|
||||
}
|
||||
if len(j.Services) == 0 || len(j.Services) > 256 {
|
||||
return journal{}, errors.New("invalid freeze journal services")
|
||||
}
|
||||
for i, s := range j.Services {
|
||||
if !validID(s.ID) || (i > 0 && j.Services[i-1].ID >= s.ID) || s.StopRequested && !s.Running || s.Restored && (!s.StopRequested || !s.Running) {
|
||||
return journal{}, errors.New("invalid freeze service ownership")
|
||||
}
|
||||
}
|
||||
return j, nil
|
||||
}
|
||||
func (c *Coordinator) pending() error {
|
||||
dir, err := c.root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dir.Close()
|
||||
entries, err := dir.ReadDir(-1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if strings.HasSuffix(entry.Name(), ".json") {
|
||||
job := strings.TrimSuffix(entry.Name(), ".json")
|
||||
if !validID(job) {
|
||||
return errors.New("invalid freeze journal name")
|
||||
}
|
||||
j, err := c.load(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !terminal(j.State) {
|
||||
return errors.New("interrupted test freeze requires recovery")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func inventory(ctx context.Context, control Controller) ([]Service, error) {
|
||||
items, err := control.Inventory(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.New("test writer inventory unavailable")
|
||||
}
|
||||
if len(items) == 0 || len(items) > 256 {
|
||||
return nil, errors.New("invalid test writer inventory")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, s := range items {
|
||||
if !validID(s.ID) || seen[s.ID] {
|
||||
return nil, errors.New("invalid test writer identity")
|
||||
}
|
||||
seen[s.ID] = true
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].ID < items[j].ID })
|
||||
return items, nil
|
||||
}
|
||||
func (c *Coordinator) stopped(ctx context.Context, j journal) error {
|
||||
items, err := inventory(ctx, c.control)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(items) != len(j.Services) {
|
||||
return errors.New("test writer topology changed")
|
||||
}
|
||||
for i, s := range items {
|
||||
if s.ID != j.Services[i].ID || s.Running {
|
||||
return errors.New("test writers not isolated")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Coordinator) restore(ctx context.Context, j *journal) error {
|
||||
j.State = "restoring"
|
||||
// Restoring services is still necessary if the journal disk fails after a
|
||||
// persisted stop intent. Keep the error, but do not let it suppress recovery.
|
||||
var failures error = c.save(*j)
|
||||
for i := range j.Services {
|
||||
s := &j.Services[i]
|
||||
if !s.Running || !s.StopRequested {
|
||||
continue
|
||||
}
|
||||
items, err := inventory(ctx, c.control)
|
||||
if err != nil {
|
||||
failures = errors.Join(failures, err)
|
||||
continue
|
||||
}
|
||||
found := false
|
||||
for _, actual := range items {
|
||||
if actual.ID != s.ID {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if actual.Running && !s.StopVerified {
|
||||
failures = errors.Join(failures, errors.New("stop outcome remains uncertain; service may still stop later"))
|
||||
break
|
||||
}
|
||||
if !actual.Running {
|
||||
s.StopVerified = true
|
||||
if saveErr := c.save(*j); saveErr != nil {
|
||||
failures = errors.Join(failures, saveErr)
|
||||
}
|
||||
if err = c.control.Start(ctx, s.ID); err != nil {
|
||||
failures = errors.Join(failures, errors.New("test service restart failed"))
|
||||
break
|
||||
}
|
||||
}
|
||||
after, readErr := inventory(ctx, c.control)
|
||||
healthy := false
|
||||
if readErr == nil {
|
||||
for _, a := range after {
|
||||
if a.ID == s.ID && a.Running && a.Healthy {
|
||||
healthy = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !healthy {
|
||||
failures = errors.Join(failures, errors.New("test service health unverified"))
|
||||
break
|
||||
}
|
||||
s.Restored = true
|
||||
if err = c.save(*j); err != nil {
|
||||
failures = errors.Join(failures, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
if !found {
|
||||
failures = errors.Join(failures, errors.New("original test service missing; replacement not started"))
|
||||
}
|
||||
}
|
||||
return failures
|
||||
}
|
||||
func (c *Coordinator) Run(ctx context.Context, job string, capture func(context.Context) (string, error)) (Result, error) {
|
||||
return c.RunPrepared(ctx, job, func(context.Context) error { return nil }, capture)
|
||||
}
|
||||
|
||||
// RunPrepared runs readiness checks under the source lock, before any stop
|
||||
// intent. It does not repeat checks or capture for an already completed job.
|
||||
func (c *Coordinator) RunPrepared(ctx context.Context, job string, prepare func(context.Context) error, capture func(context.Context) (string, error)) (Result, error) {
|
||||
if !validID(job) || capture == nil || prepare == nil {
|
||||
return Result{}, errors.New("invalid freeze request")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
lock, err := c.lock()
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
defer unlock(lock)
|
||||
previous, err := c.load(job)
|
||||
if err == nil {
|
||||
if previous.State == "succeeded" {
|
||||
return previous.Result, nil
|
||||
}
|
||||
return previous.Result, errors.New("freeze request already exists; recovery or a new request is required")
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return Result{}, err
|
||||
}
|
||||
if err = c.pending(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if err = prepare(ctx); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
items, err := inventory(ctx, c.control)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
j := journal{Version: 1, Source: c.source, Job: job, Result: Result{State: "stopping"}, StartedAt: time.Now().UTC()}
|
||||
for _, s := range items {
|
||||
if s.Running && !s.Healthy {
|
||||
return Result{}, errors.New("test writer is not ready")
|
||||
}
|
||||
j.Services = append(j.Services, serviceRecord{Service: s})
|
||||
}
|
||||
if err = c.save(j); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
var workErr error
|
||||
for i := range j.Services {
|
||||
if !j.Services[i].Running {
|
||||
continue
|
||||
}
|
||||
j.Services[i].StopRequested = true
|
||||
if workErr = c.save(j); workErr != nil {
|
||||
break
|
||||
}
|
||||
if workErr = c.control.Stop(ctx, j.Services[i].ID); workErr != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if workErr == nil {
|
||||
workErr = c.stopped(ctx, j)
|
||||
}
|
||||
if workErr == nil {
|
||||
for i := range j.Services {
|
||||
if j.Services[i].StopRequested {
|
||||
j.Services[i].StopVerified = true
|
||||
}
|
||||
}
|
||||
j.State = "capturing"
|
||||
workErr = c.save(j)
|
||||
}
|
||||
if workErr == nil {
|
||||
j.SnapshotID, workErr = invokeCapture(ctx, capture)
|
||||
}
|
||||
if workErr == nil {
|
||||
workErr = ctx.Err()
|
||||
}
|
||||
if workErr == nil {
|
||||
decoded, decodeErr := hex.DecodeString(j.SnapshotID)
|
||||
if decodeErr != nil || len(decoded) != 32 || strings.ToLower(j.SnapshotID) != j.SnapshotID {
|
||||
workErr = errors.New("invalid candidate snapshot digest")
|
||||
}
|
||||
}
|
||||
if workErr == nil {
|
||||
workErr = c.stopped(ctx, j)
|
||||
}
|
||||
recoveryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute)
|
||||
defer cancel()
|
||||
recoveryErr := c.restore(recoveryCtx, &j)
|
||||
if recoveryErr != nil {
|
||||
return j.Result, errors.Join(workErr, recoveryErr)
|
||||
}
|
||||
if workErr != nil {
|
||||
j.State = "failed"
|
||||
j.Code = "capture_or_isolation_failed"
|
||||
} else {
|
||||
j.State = "succeeded"
|
||||
}
|
||||
ended := time.Now().UTC()
|
||||
j.FinishedAt = &ended
|
||||
if err = c.save(j); err != nil {
|
||||
return j.Result, err
|
||||
}
|
||||
return j.Result, workErr
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fixtureControl struct {
|
||||
services []Service
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (c *fixtureControl) Inventory(context.Context) ([]Service, error) {
|
||||
return append([]Service(nil), c.services...), nil
|
||||
}
|
||||
func (c *fixtureControl) Stop(_ context.Context, id string) error {
|
||||
c.calls = append(c.calls, "stop:"+id)
|
||||
for i := range c.services {
|
||||
if c.services[i].ID == id {
|
||||
c.services[i].Running = false
|
||||
c.services[i].Healthy = false
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *fixtureControl) Start(_ context.Context, id string) error {
|
||||
c.calls = append(c.calls, "start:"+id)
|
||||
for i := range c.services {
|
||||
if c.services[i].ID == id {
|
||||
c.services[i].Running = true
|
||||
c.services[i].Healthy = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func freezeFixture(t *testing.T) (string, *fixtureControl, *Coordinator) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
if err := os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := &fixtureControl{services: []Service{{ID: "app-a", Running: true, Healthy: true}, {ID: "app-b"}}}
|
||||
engine, err := Open(root, "test-source", c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { engine.Close() })
|
||||
return root, c, engine
|
||||
}
|
||||
func TestFreezeRestoresOnlyServicesOriginallyRunning(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
captures := 0
|
||||
result, err := e.Run(context.Background(), "job-a", func(ctx context.Context) (string, error) {
|
||||
captures++
|
||||
for _, s := range c.services {
|
||||
if s.Running {
|
||||
t.Fatal("capture started while writer running")
|
||||
}
|
||||
}
|
||||
return strings.Repeat("a", 64), nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.State != "succeeded" || result.SnapshotID != strings.Repeat("a", 64) || captures != 1 {
|
||||
t.Fatalf("result=%+v captures=%d", result, captures)
|
||||
}
|
||||
if strings.Join(c.calls, ",") != "stop:app-a,start:app-a" {
|
||||
t.Fatalf("calls=%v", c.calls)
|
||||
}
|
||||
replay, err := e.Run(context.Background(), "job-a", func(context.Context) (string, error) { t.Fatal("replay captured again"); return "", nil })
|
||||
if err != nil || replay.SnapshotID != result.SnapshotID {
|
||||
t.Fatalf("replay=%+v err=%v", replay, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFreezePreflightRejectsWithoutStoppingAndReplaySkipsIt(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
_, err := e.RunPrepared(context.Background(), "prepared", func(context.Context) error { return errors.New("tasks active") }, func(context.Context) (string, error) { t.Fatal("capture before ready"); return "", nil })
|
||||
if err == nil || len(c.calls) != 0 {
|
||||
t.Fatal("preflight did not protect services")
|
||||
}
|
||||
r, err := e.RunPrepared(context.Background(), "prepared", func(context.Context) error { return nil }, func(context.Context) (string, error) { return strings.Repeat("a", 64), nil })
|
||||
if err != nil || r.State != "succeeded" {
|
||||
t.Fatalf("ready capture: %+v %v", r, err)
|
||||
}
|
||||
_, err = e.RunPrepared(context.Background(), "prepared", func(context.Context) error { t.Fatal("completed job consulted changing source"); return nil }, func(context.Context) (string, error) { t.Fatal("completed job captured again"); return "", nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFreezeRecoveryAfterProcessExit(t *testing.T) {
|
||||
if os.Getenv("KG_FREEZE_CHILD") == "exit-after-stop" {
|
||||
c := &fixtureControl{services: []Service{{ID: "app-a", Running: true, Healthy: true}, {ID: "app-b"}}}
|
||||
e, err := Open(os.Getenv("KG_FREEZE_ROOT"), "test-source", c)
|
||||
if err != nil {
|
||||
os.Exit(25)
|
||||
}
|
||||
_, _ = e.Run(context.Background(), "crashed-job", func(context.Context) (string, error) { os.Exit(27); return "", nil })
|
||||
os.Exit(26)
|
||||
}
|
||||
root, c, e := freezeFixture(t)
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestFreezeRecoveryAfterProcessExit$")
|
||||
cmd.Env = append(os.Environ(), "KG_FREEZE_CHILD=exit-after-stop", "KG_FREEZE_ROOT="+root)
|
||||
err := cmd.Run()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != 27 {
|
||||
t.Fatalf("child did not exit during capture: %v", err)
|
||||
}
|
||||
c.services[0].Running = false
|
||||
c.services[0].Healthy = false
|
||||
if _, err = e.Run(context.Background(), "new-job", func(context.Context) (string, error) { t.Fatal("new capture before recovery"); return "", nil }); err == nil {
|
||||
t.Fatal("unfinished job did not block")
|
||||
}
|
||||
if err = e.Recover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j, err := e.load("crashed-job")
|
||||
if err != nil || j.State != "failed" || j.Code != "interrupted" {
|
||||
t.Fatalf("journal=%+v err=%v", j, err)
|
||||
}
|
||||
if strings.Join(c.calls, ",") != "start:app-a" {
|
||||
t.Fatalf("recovery calls=%v", c.calls)
|
||||
}
|
||||
if err = e.Recover(context.Background()); err != nil || len(c.calls) != 1 {
|
||||
t.Fatalf("recovery is not idempotent: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type pendingStopControl struct{ *fixtureControl }
|
||||
|
||||
func (c *pendingStopControl) Stop(context.Context, string) error {
|
||||
return errors.New("stop may complete later")
|
||||
}
|
||||
func TestFreezeUncertainStopCannotBecomeTerminalWhileStillRunning(t *testing.T) {
|
||||
_, c, e := freezeFixture(t)
|
||||
e.control = &pendingStopControl{c}
|
||||
_, err := e.Run(context.Background(), "uncertain", func(context.Context) (string, error) { t.Fatal("capture after uncertain stop"); return "", nil })
|
||||
if err == nil {
|
||||
t.Fatal("uncertain stop succeeded")
|
||||
}
|
||||
j, err := e.load("uncertain")
|
||||
if err != nil || terminal(j.State) {
|
||||
t.Fatal("running now was treated as proof that delayed stop cannot happen")
|
||||
}
|
||||
if err = e.Recover(context.Background()); err == nil {
|
||||
t.Fatal("uncertain running stop falsely recovered")
|
||||
}
|
||||
c.services[0].Running = false
|
||||
c.services[0].Healthy = false
|
||||
if err = e.Recover(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !c.services[0].Running {
|
||||
t.Fatal("delayed stop not restored")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
// Package librarysnapshot stores immutable, content-addressed library artifacts.
|
||||
// It does not authorize releases or imply cross-system snapshot consistency.
|
||||
package librarysnapshot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/releasebundle"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const Format = "weknora-library-snapshot/v1"
|
||||
const maxManifestBytes = 16 * 1024 * 1024
|
||||
|
||||
type Part struct {
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
type Compatibility struct {
|
||||
WeKnoraVersion string `json:"weknora_version"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
RetrieverEngine string `json:"retriever_engine"`
|
||||
EmbeddingModel string `json:"embedding_model"`
|
||||
EmbeddingDimension int `json:"embedding_dimension"`
|
||||
IndexMappingSHA256 string `json:"index_mapping_sha256"`
|
||||
}
|
||||
|
||||
type Manifest struct {
|
||||
Compatibility Compatibility `json:"compatibility"`
|
||||
Format string `json:"format"`
|
||||
Scope string `json:"scope"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Parts []Part `json:"parts"`
|
||||
}
|
||||
type Archive struct {
|
||||
root, blobs, versions *os.Root
|
||||
maxBlobBytes int64
|
||||
}
|
||||
|
||||
func Open(root string, maxBlobBytes int64) (*Archive, error) {
|
||||
if !filepath.IsAbs(root) || maxBlobBytes < 1 || maxBlobBytes == math.MaxInt64 {
|
||||
return nil, errors.New("invalid archive configuration")
|
||||
}
|
||||
info, err := os.Lstat(root)
|
||||
if err != nil || !info.IsDir() || info.Mode().Perm() != 0700 {
|
||||
return nil, errors.New("archive root must be a private real directory")
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(root)
|
||||
if err != nil || resolved != filepath.Clean(root) {
|
||||
return nil, errors.New("archive root contains symlinks")
|
||||
}
|
||||
r, err := os.OpenRoot(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a := &Archive{root: r, maxBlobBytes: maxBlobBytes}
|
||||
for _, dir := range []string{"blobs", "versions"} {
|
||||
if err := r.Mkdir(dir, 0700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
a.Close()
|
||||
return nil, err
|
||||
}
|
||||
info, err := r.Lstat(dir)
|
||||
if err != nil || !info.IsDir() || info.Mode().Perm() != 0700 {
|
||||
a.Close()
|
||||
return nil, errors.New("archive subdirectory must be private and real")
|
||||
}
|
||||
sub, err := r.OpenRoot(dir)
|
||||
if err != nil {
|
||||
a.Close()
|
||||
return nil, err
|
||||
}
|
||||
if dir == "blobs" {
|
||||
a.blobs = sub
|
||||
} else {
|
||||
a.versions = sub
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
func (a *Archive) Close() error {
|
||||
var err error
|
||||
for _, r := range []*os.Root{a.versions, a.blobs, a.root} {
|
||||
if r != nil {
|
||||
err = errors.Join(err, r.Close())
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Put streams bytes into an archive-owned file; it never keeps a source path or
|
||||
// signed URL as the recovery dependency. Publishing uses no-overwrite links.
|
||||
func (a *Archive) Put(r io.Reader) (Part, error) {
|
||||
if r == nil {
|
||||
return Part{}, errors.New("nil blob reader")
|
||||
}
|
||||
name, f, err := temporary(a.blobs)
|
||||
if err != nil {
|
||||
return Part{}, err
|
||||
}
|
||||
defer a.blobs.Remove(name)
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(r, a.maxBlobBytes+1))
|
||||
if err != nil {
|
||||
return Part{}, errors.New("read snapshot blob")
|
||||
}
|
||||
if n > a.maxBlobBytes {
|
||||
return Part{}, errors.New("snapshot blob exceeds configured limit")
|
||||
}
|
||||
if err = f.Sync(); err != nil {
|
||||
return Part{}, err
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
return Part{}, err
|
||||
}
|
||||
p := Part{SHA256: hex.EncodeToString(h.Sum(nil)), Bytes: n}
|
||||
if err = a.blobs.Link(name, p.SHA256); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return Part{}, err
|
||||
}
|
||||
if err = a.verify(p); err != nil {
|
||||
return Part{}, err
|
||||
}
|
||||
if err = syncRoot(a.blobs); err != nil {
|
||||
return Part{}, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Seal is the commit point: no version is visible until every dependency has
|
||||
// been read and hashed locally. Empty tables are explicit, not "leave old data".
|
||||
func (a *Archive) Seal(m Manifest) (string, error) {
|
||||
data, err := encodeManifest(m)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = a.verifyParts(m.Parts); err != nil {
|
||||
return "", err
|
||||
}
|
||||
id := digest(data)
|
||||
name, f, err := temporary(a.versions)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer a.versions.Remove(name)
|
||||
defer f.Close()
|
||||
if _, err = f.Write(data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = f.Sync(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = a.versions.Link(name, id+".json"); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return "", err
|
||||
}
|
||||
if _, err = a.Load(id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = syncRoot(a.versions); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Load revalidates bytes, not just the manifest's claim of recoverability.
|
||||
func (a *Archive) Load(id string) (Manifest, error) {
|
||||
if !validDigest(id) {
|
||||
return Manifest{}, errors.New("invalid snapshot ID")
|
||||
}
|
||||
f, err := regular(a.versions, id+".json", maxManifestBytes)
|
||||
if err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(f, maxManifestBytes+1))
|
||||
if err != nil || len(data) > maxManifestBytes || digest(data) != id {
|
||||
return Manifest{}, errors.New("snapshot manifest digest mismatch")
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
var m Manifest
|
||||
if err = dec.Decode(&m); err != nil {
|
||||
return Manifest{}, errors.New("invalid snapshot manifest")
|
||||
}
|
||||
var extra any
|
||||
if dec.Decode(&extra) != io.EOF {
|
||||
return Manifest{}, errors.New("trailing snapshot manifest data")
|
||||
}
|
||||
if _, err = encodeManifest(m); err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
if err = a.verifyParts(m.Parts); err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (a *Archive) verifyParts(parts []Part) error {
|
||||
seen := map[string]int64{}
|
||||
counts := map[string]int64{}
|
||||
resourceIDs := map[string]bool{}
|
||||
archivedResources := map[string]bool{}
|
||||
for _, p := range parts {
|
||||
if size, ok := seen[p.SHA256]; ok {
|
||||
if size != p.Bytes {
|
||||
return errors.New("conflicting blob sizes")
|
||||
}
|
||||
} else {
|
||||
if err := a.verify(p); err != nil {
|
||||
return err
|
||||
}
|
||||
seen[p.SHA256] = p.Bytes
|
||||
}
|
||||
if p.Kind == "resource" {
|
||||
archivedResources[p.Name] = true
|
||||
continue
|
||||
}
|
||||
count, known := counts[p.SHA256]
|
||||
if !known || p.Kind == "database" && p.Name == "resources" {
|
||||
var err error
|
||||
count, err = a.countRows(p, resourceIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
counts[p.SHA256] = count
|
||||
}
|
||||
if count != p.Count {
|
||||
return errors.New("snapshot count does not match archived rows")
|
||||
}
|
||||
}
|
||||
if len(resourceIDs) != len(archivedResources) {
|
||||
return errors.New("resource archive dependencies incomplete")
|
||||
}
|
||||
for id := range resourceIDs {
|
||||
if !archivedResources[id] {
|
||||
return errors.New("resource bytes not archived")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Archive) countRows(p Part, resources map[string]bool) (int64, error) {
|
||||
f, err := regular(a.blobs, p.SHA256, a.maxBlobBytes)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer f.Close()
|
||||
dec := json.NewDecoder(io.LimitReader(f, a.maxBlobBytes+1))
|
||||
token, err := dec.Token()
|
||||
if err != nil || token != json.Delim('[') {
|
||||
return 0, errors.New("snapshot component must be a JSON row array")
|
||||
}
|
||||
var n int64
|
||||
for dec.More() {
|
||||
var row map[string]json.RawMessage
|
||||
if err = dec.Decode(&row); err != nil || row == nil {
|
||||
return 0, errors.New("invalid archived row")
|
||||
}
|
||||
n++
|
||||
if p.Kind == "database" && p.Name == "resources" {
|
||||
var id string
|
||||
if json.Unmarshal(row["id"], &id) != nil || !identifier(id) || resources[id] {
|
||||
return 0, errors.New("invalid resource archive identity")
|
||||
}
|
||||
resources[id] = true
|
||||
}
|
||||
}
|
||||
if _, err = dec.Token(); err != nil {
|
||||
return 0, errors.New("incomplete archived row array")
|
||||
}
|
||||
var extra any
|
||||
if dec.Decode(&extra) != io.EOF {
|
||||
return 0, errors.New("trailing archived row data")
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
func (a *Archive) verify(p Part) error {
|
||||
if !validDigest(p.SHA256) || p.Bytes < 0 || p.Bytes > a.maxBlobBytes {
|
||||
return errors.New("invalid snapshot blob descriptor")
|
||||
}
|
||||
f, err := regular(a.blobs, p.SHA256, a.maxBlobBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(h, io.LimitReader(f, a.maxBlobBytes+1))
|
||||
if err != nil || n != p.Bytes || hex.EncodeToString(h.Sum(nil)) != p.SHA256 {
|
||||
return errors.New("snapshot blob integrity mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func regular(root *os.Root, name string, limit int64) (*os.File, error) {
|
||||
f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
return nil, errors.New("snapshot file unavailable")
|
||||
}
|
||||
st, err := f.Stat()
|
||||
if err != nil || !st.Mode().IsRegular() || st.Mode().Perm() != 0600 || st.Size() > limit {
|
||||
f.Close()
|
||||
return nil, errors.New("unsafe snapshot file")
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
func temporary(root *os.Root) (string, *os.File, error) {
|
||||
var random [16]byte
|
||||
if _, err := rand.Read(random[:]); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
name := ".pending-" + hex.EncodeToString(random[:])
|
||||
f, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
return name, f, err
|
||||
}
|
||||
func syncRoot(root *os.Root) error {
|
||||
f, err := root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
return f.Sync()
|
||||
}
|
||||
func digest(data []byte) string { h := sha256.Sum256(data); return hex.EncodeToString(h[:]) }
|
||||
func validDigest(s string) bool {
|
||||
if len(s) != 64 {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func identifier(s string) bool {
|
||||
if len(s) == 0 || len(s) > 128 {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '-' || c == '_' || c == '.') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return s != "." && s != ".."
|
||||
}
|
||||
|
||||
func encodeManifest(m Manifest) ([]byte, error) {
|
||||
c := m.Compatibility
|
||||
if c.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || c.SchemaVersion != releasebundle.WeKnoraMigrationV071 || c.RetrieverEngine != "elasticsearch_v8" || !identifier(c.EmbeddingModel) || c.EmbeddingDimension != releasebundle.EmbeddingDimensionV071 || !validDigest(c.IndexMappingSHA256) {
|
||||
return nil, errors.New("unsupported snapshot compatibility contract")
|
||||
}
|
||||
if m.Format != Format || (m.Scope != "internal" && m.Scope != "external") || m.TenantID == 0 || !identifier(m.KnowledgeBaseID) || m.CreatedAt.IsZero() {
|
||||
return nil, errors.New("invalid library manifest identity")
|
||||
}
|
||||
required := map[string]bool{}
|
||||
for _, n := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} {
|
||||
required["database/"+n] = true
|
||||
}
|
||||
for _, n := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} {
|
||||
required["wiki/"+n] = true
|
||||
}
|
||||
required["index/chunks"] = true
|
||||
seen := map[string]bool{}
|
||||
for _, p := range m.Parts {
|
||||
key := p.Kind + "/" + p.Name
|
||||
if (!required[key] && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 {
|
||||
return nil, errors.New("invalid or nonknowledge snapshot component")
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
for key := range required {
|
||||
if !seen[key] {
|
||||
return nil, errors.New("incomplete library snapshot")
|
||||
}
|
||||
}
|
||||
m.Parts = append([]Part(nil), m.Parts...)
|
||||
sort.Slice(m.Parts, func(i, j int) bool { return m.Parts[i].Kind+"/"+m.Parts[i].Name < m.Parts[j].Kind+"/"+m.Parts[j].Name })
|
||||
data, err := json.Marshal(m)
|
||||
if err != nil || len(data) > maxManifestBytes {
|
||||
return nil, errors.New("snapshot manifest too large")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package librarysnapshot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestArchiveSealsCompleteVersionAndLoadsAfterReopen(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, err := Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
part, err := a.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := testManifest(part)
|
||||
id, err := a.Seal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = a.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, err = Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
got, err := a.Load(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Parts) != 11 || got.KnowledgeBaseID != m.KnowledgeBaseID {
|
||||
t.Fatal("incomplete reopened manifest")
|
||||
}
|
||||
again, err := a.Seal(m)
|
||||
if err != nil || again != id {
|
||||
t.Fatal("retry changed immutable identity")
|
||||
}
|
||||
files, err := os.ReadDir(filepath.Join(root, "blobs"))
|
||||
if err != nil || len(files) != 1 {
|
||||
t.Fatal("identical bytes were not shared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveRejectsMissingCorruptAndNonknowledgeParts(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
_ = os.Chmod(root, 0700)
|
||||
a, err := Open(root, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
p, err := a.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
mutate func(*Manifest)
|
||||
}{
|
||||
{"unsupported schema", func(m *Manifest) { m.Compatibility.SchemaVersion = 75 }},
|
||||
{"missing mapping contract", func(m *Manifest) { m.Compatibility.IndexMappingSHA256 = "" }},
|
||||
{"missing Wiki", func(m *Manifest) { m.Parts = m.Parts[:6] }},
|
||||
{"duplicate table", func(m *Manifest) { m.Parts = append(m.Parts, m.Parts[0]) }},
|
||||
{"account table", func(m *Manifest) { m.Parts[0].Name = "users" }},
|
||||
{"bad scope", func(m *Manifest) { m.Scope = "both" }},
|
||||
{"wrong size", func(m *Manifest) { m.Parts[0].Bytes++ }},
|
||||
{"missing blob", func(m *Manifest) { m.Parts[0].SHA256 = string(bytes.Repeat([]byte("a"), 64)) }},
|
||||
{"path traversal", func(m *Manifest) { m.Parts[0].SHA256 = "../../escape" }},
|
||||
{"negative count", func(m *Manifest) { m.Parts[0].Count = -1 }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
m := testManifest(p)
|
||||
test.mutate(&m)
|
||||
if _, err := a.Seal(m); err == nil {
|
||||
t.Fatal("unsafe manifest sealed")
|
||||
}
|
||||
})
|
||||
}
|
||||
m := testManifest(p)
|
||||
id, err := a.Seal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "blobs", p.SHA256), []byte("xx"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.Load(id); err == nil {
|
||||
t.Fatal("corrupt blob accepted as recoverable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveRefusesInventedCountsAndMissingResourceBytes(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
_ = os.Chmod(root, 0700)
|
||||
a, err := Open(root, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
p, err := a.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := testManifest(p)
|
||||
m.Parts[0].Count = 2
|
||||
if _, err = a.Seal(m); err == nil {
|
||||
t.Fatal("manifest accepted invented progress total")
|
||||
}
|
||||
p, err = a.Put(bytes.NewBufferString(`[{"id":"res-safe"}]`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m = testManifest(p)
|
||||
for i := range m.Parts {
|
||||
m.Parts[i].Count = 1
|
||||
}
|
||||
if _, err = a.Seal(m); err == nil {
|
||||
t.Fatal("resource rows have no archived resource bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func testManifest(part Part) Manifest {
|
||||
m := Manifest{Compatibility: Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: digest([]byte("fixture-mapping"))}, Format: "weknora-library-snapshot/v1", Scope: "internal", TenantID: 10000, KnowledgeBaseID: "kb-safe", CreatedAt: time.Date(2026, 10, 27, 0, 0, 0, 0, time.UTC)}
|
||||
for _, name := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} {
|
||||
p := part
|
||||
p.Kind = "database"
|
||||
p.Name = name
|
||||
m.Parts = append(m.Parts, p)
|
||||
}
|
||||
for _, name := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} {
|
||||
p := part
|
||||
p.Kind = "wiki"
|
||||
p.Name = name
|
||||
m.Parts = append(m.Parts, p)
|
||||
}
|
||||
p := part
|
||||
p.Kind = "index"
|
||||
p.Name = "chunks"
|
||||
m.Parts = append(m.Parts, p)
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package librarysnapshot
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Usage struct {
|
||||
VersionID string `json:"version_id"`
|
||||
LogicalBytes int64 `json:"logical_bytes"`
|
||||
UniqueBytes int64 `json:"unique_bytes"`
|
||||
SharedBytes int64 `json:"shared_bytes"`
|
||||
ExclusiveBytes int64 `json:"exclusive_bytes"`
|
||||
}
|
||||
|
||||
// OpenPart provides archive-owned recovery bytes, never a source-side locator.
|
||||
// Verify and rewind the same descriptor, so path replacement cannot swap the
|
||||
// verified file for an unchecked dependency between these two operations.
|
||||
func (a *Archive) OpenPart(p Part) (io.ReadCloser, error) {
|
||||
if !validDigest(p.SHA256) || p.Bytes < 0 || p.Bytes > a.maxBlobBytes {
|
||||
return nil, errors.New("invalid recovery blob")
|
||||
}
|
||||
f, err := regular(a.blobs, p.SHA256, a.maxBlobBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(h, io.LimitReader(f, a.maxBlobBytes+1))
|
||||
if err != nil || n != p.Bytes || hex.EncodeToString(h.Sum(nil)) != p.SHA256 {
|
||||
f.Close()
|
||||
return nil, errors.New("corrupt recovery blob")
|
||||
}
|
||||
if _, err = f.Seek(0, io.SeekStart); err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Usage reports content bytes, not filesystem allocation or reclaimed space.
|
||||
// It is deliberately read-only: protection/retention and live-job references
|
||||
// must be acquired from the coordinator before any future cleanup operation.
|
||||
func (a *Archive) Usage() ([]Usage, error) {
|
||||
ids, err := a.versionIDs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type inventory struct {
|
||||
usage Usage
|
||||
blobs map[string]int64
|
||||
}
|
||||
inventories := make([]inventory, 0, len(ids))
|
||||
refs := map[string]int{}
|
||||
for _, id := range ids {
|
||||
m, err := a.Load(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := inventory{usage: Usage{VersionID: id}, blobs: map[string]int64{}}
|
||||
for _, p := range m.Parts {
|
||||
if v.usage.LogicalBytes > math.MaxInt64-p.Bytes {
|
||||
return nil, errors.New("snapshot usage overflow")
|
||||
}
|
||||
v.usage.LogicalBytes += p.Bytes
|
||||
v.blobs[p.SHA256] = p.Bytes
|
||||
}
|
||||
for sha := range v.blobs {
|
||||
refs[sha]++
|
||||
}
|
||||
inventories = append(inventories, v)
|
||||
}
|
||||
after, err := a.versionIDs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Equal(ids, after) {
|
||||
return nil, errors.New("snapshot inventory changed; retry usage read")
|
||||
}
|
||||
result := make([]Usage, 0, len(inventories))
|
||||
for _, v := range inventories {
|
||||
for sha, size := range v.blobs {
|
||||
v.usage.UniqueBytes += size
|
||||
if refs[sha] > 1 {
|
||||
v.usage.SharedBytes += size
|
||||
} else {
|
||||
v.usage.ExclusiveBytes += size
|
||||
}
|
||||
}
|
||||
result = append(result, v.usage)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *Archive) versionIDs() ([]string, error) {
|
||||
f, err := a.versions.Open(".")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
entries, err := f.ReadDir(-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if strings.HasPrefix(entry.Name(), ".pending-") {
|
||||
continue
|
||||
}
|
||||
name := entry.Name()
|
||||
id := strings.TrimSuffix(name, ".json")
|
||||
if !strings.HasSuffix(name, ".json") || !validDigest(id) || entry.IsDir() {
|
||||
return nil, errors.New("unexpected archive version entry")
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
return ids, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package librarysnapshot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestArchiveRecoveryIndependentOfSourceAndUsageByReferences(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
_ = os.Chmod(root, 0700)
|
||||
a, err := Open(root, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
source := filepath.Join(t.TempDir(), "source")
|
||||
if err := os.WriteFile(source, []byte("first"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blob, err := a.Put(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.Remove(source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := a.OpenPart(blob)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored, err := io.ReadAll(reader)
|
||||
reader.Close()
|
||||
if err != nil || string(restored) != "first" {
|
||||
t.Fatal("restore still depends on source")
|
||||
}
|
||||
empty, err := a.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := testManifest(empty)
|
||||
first, err := a.Seal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.Add(time.Second)
|
||||
second, err := a.Seal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := a.Usage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("versions=%d", len(got))
|
||||
}
|
||||
for _, u := range got {
|
||||
if u.VersionID != first && u.VersionID != second {
|
||||
t.Fatal("unexpected version")
|
||||
}
|
||||
if u.LogicalBytes != 22 || u.UniqueBytes != 2 || u.SharedBytes != 2 || u.ExclusiveBytes != 0 {
|
||||
t.Fatalf("bad shared accounting: %+v", u)
|
||||
}
|
||||
}
|
||||
// A digest with no manifest reference must not inflate either version.
|
||||
if len(restored) != 5 {
|
||||
t.Fatal("fixture unexpected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveConcurrentWritersAndReadSafety(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
_ = os.Chmod(root, 0700)
|
||||
a, err := Open(root, 16)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
b, err := Open(root, 16)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer b.Close()
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 12; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
archive := a
|
||||
if i%2 == 0 {
|
||||
archive = b
|
||||
}
|
||||
p, err := archive.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if _, err = archive.Seal(testManifest(p)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
got, err := a.Usage()
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("concurrent publication: err=%v versions=%d", err, len(got))
|
||||
}
|
||||
if _, err = a.Put(bytes.NewBufferString("this is more than sixteen bytes")); err == nil {
|
||||
t.Fatal("oversized blob accepted")
|
||||
}
|
||||
p, err := a.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := filepath.Join(root, "blobs", p.SHA256)
|
||||
if err = os.Remove(target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.Symlink(filepath.Join(t.TempDir(), "outside"), target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = a.OpenPart(p); err == nil {
|
||||
t.Fatal("symlink followed")
|
||||
}
|
||||
if _, err = a.Usage(); err == nil {
|
||||
t.Fatal("corrupt dependency reported as safe usage")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/workflows/artifactfetch"
|
||||
)
|
||||
|
||||
func TestArtifactManifestCurrentSourceIntegration(t *testing.T) {
|
||||
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err = ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO source_connections(id,source_type,name,base_url) VALUES('conn-live','dingtalk','Renamed KB','spaces/workspace1?space=workspace1');
|
||||
INSERT INTO catalog_import_intents(source_connection_id,node_id,visibility,decided_by,relative_path,name,locator_hash,fetch_state) VALUES('conn-live','sn-live','internal','tester','Folder/Manual.adoc','Manual.adoc',repeat('a',64),'pending')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := NewStore(pool).LoadArtifactFetchManifest(ctx, "conn-live", "sn-live")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
script := filepath.Join(dir, "manifest_probe.py")
|
||||
if err = os.WriteFile(script, []byte("import json,sys\nm=json.loads(sys.argv[1])\nprint(json.dumps({'ok':m.get('source_root')=='spaces/workspace1?space=workspace1' and m.get('connection_id')=='conn-live','node_id':m['node_id']}))\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner, err := artifactfetch.NewCommandRunner(python, script, dir, "", 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := runner.Run(ctx, manifest)
|
||||
if err != nil || !result.OK {
|
||||
t.Fatalf("current source coordinates lost across DB/Go/Python: %#v %v", result, err)
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,13 @@ func loadArtifactFetchManifest(ctx context.Context, db interface {
|
||||
var manifest artifactfetch.Manifest
|
||||
var fetchState string
|
||||
err := db.QueryRow(ctx, `SELECT connection.source_type,connection.name,intent.relative_path,intent.name,
|
||||
intent.size_bytes,intent.modified_at,intent.locator_hash,intent.fetch_state
|
||||
intent.size_bytes,intent.modified_at,intent.locator_hash,intent.fetch_state,
|
||||
CASE WHEN connection.source_type='dingtalk' THEN connection.base_url ELSE '' END
|
||||
FROM catalog_import_intents intent
|
||||
JOIN source_connections connection ON connection.id=intent.source_connection_id
|
||||
WHERE intent.source_connection_id=$1 AND intent.node_id=$2`, connectionID, nodeID).
|
||||
Scan(&manifest.SourceType, &manifest.SourceName, &manifest.RelativePath, &manifest.Name,
|
||||
&manifest.SizeBytes, &manifest.ModifiedAt, &manifest.LocatorHash, &fetchState)
|
||||
&manifest.SizeBytes, &manifest.ModifiedAt, &manifest.LocatorHash, &fetchState, &manifest.SourceRoot)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return artifactfetch.Manifest{}, artifactfetch.ErrManifestGone
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ type RegisterDingtalkSpaceInput struct {
|
||||
SpaceID string // alidocs space id from the URL
|
||||
RootID string // root dentry uuid
|
||||
Now time.Time
|
||||
Actor string
|
||||
}
|
||||
|
||||
func (in RegisterDingtalkSpaceInput) ConnectionID() string {
|
||||
@@ -59,6 +60,9 @@ func (in RegisterDingtalkSpaceInput) validate() error {
|
||||
}
|
||||
|
||||
func (s *Store) RegisterDingtalkSpace(ctx context.Context, in RegisterDingtalkSpaceInput) (string, error) {
|
||||
if strings.TrimSpace(in.Actor) == "" {
|
||||
in.Actor = "dingtalk-registration"
|
||||
}
|
||||
if err := in.validate(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -98,7 +102,7 @@ func (s *Store) RegisterDingtalkSpace(ctx context.Context, in RegisterDingtalkSp
|
||||
}
|
||||
if _, err := s.db.Exec(ctx, `
|
||||
UPDATE source_connections SET name = $2, updated_at = $3, updated_by = $4 WHERE id = $1`,
|
||||
nameHolderID, archivedConnectionName(in.Name, nameHolderID), in.Now.UTC(), "dingtalk-registration"); err != nil {
|
||||
nameHolderID, archivedConnectionName(in.Name, nameHolderID), in.Now.UTC(), in.Actor); err != nil {
|
||||
return "", fmt.Errorf("free archived dingtalk name: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -117,7 +121,7 @@ SET name = EXCLUDED.name, base_url = EXCLUDED.base_url,
|
||||
-- 目录快照与历史仍属于同一行。
|
||||
archived_at = NULL, archived_by = '',
|
||||
updated_at = EXCLUDED.updated_at, updated_by = EXCLUDED.updated_by`,
|
||||
connectionID, in.Name, locator, in.Now.UTC(), "dingtalk-registration")
|
||||
connectionID, in.Name, locator, in.Now.UTC(), in.Actor)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return "", fmt.Errorf("dingtalk space registration: name %q already used by another connection", in.Name)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE qa_ops_mirror_records;
|
||||
DROP TABLE qa_ops_mirror_state;
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE qa_ops_mirror_state (
|
||||
tenant_key TEXT PRIMARY KEY CHECK(length(tenant_key) BETWEEN 1 AND 128),
|
||||
ready BOOLEAN NOT NULL DEFAULT false, blocked BOOLEAN NOT NULL DEFAULT false,
|
||||
revision BIGINT NOT NULL DEFAULT 0 CHECK(revision>=0), record_count BIGINT NOT NULL DEFAULT 0 CHECK(record_count>=0),
|
||||
source_observed_at TIMESTAMPTZ, synced_at TIMESTAMPTZ, next_sync_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_error TEXT NOT NULL DEFAULT '', source_safety JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
);
|
||||
CREATE TABLE qa_ops_mirror_records (
|
||||
tenant_key TEXT NOT NULL REFERENCES qa_ops_mirror_state(tenant_key), id TEXT NOT NULL,
|
||||
fingerprint TEXT NOT NULL CHECK(fingerprint ~ '^[a-f0-9]{64}$'), asked_at TIMESTAMPTZ NOT NULL,
|
||||
question TEXT NOT NULL, status TEXT NOT NULL, identity JSONB NOT NULL, quality_hash TEXT NOT NULL CHECK(quality_hash ~ '^[a-f0-9]{64}$'),
|
||||
payload JSONB NOT NULL CHECK(jsonb_typeof(payload)='object'), PRIMARY KEY(tenant_key,id)
|
||||
);
|
||||
CREATE INDEX idx_qa_mirror_records_window ON qa_ops_mirror_records(tenant_key,asked_at DESC,id DESC);
|
||||
@@ -0,0 +1,6 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM qa_ops_region_revisions WHERE region_definitions <> '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb) THEN
|
||||
RAISE EXCEPTION 'custom region catalog exists; application rollback may keep migration 51, destructive catalog rollback refused';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE qa_ops_region_revisions DROP COLUMN region_definitions;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE qa_ops_region_revisions ADD COLUMN region_definitions JSONB NOT NULL DEFAULT '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb CHECK (jsonb_typeof(region_definitions)='array');
|
||||
@@ -0,0 +1,10 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots) THEN
|
||||
RAISE EXCEPTION 'frozen weekly quality history exists; keep additive schema during application rollback';
|
||||
END IF;
|
||||
END $$;
|
||||
DROP TABLE qa_ops_weekly_quality_snapshot_records;
|
||||
DROP TABLE qa_ops_weekly_quality_snapshots;
|
||||
DROP TABLE qa_ops_weekly_quality_tracking;
|
||||
DROP FUNCTION qa_ops_require_new_weekly_quality_header();
|
||||
DROP FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
@@ -0,0 +1,50 @@
|
||||
CREATE TABLE qa_ops_weekly_quality_tracking (
|
||||
tenant_key TEXT PRIMARY KEY CHECK(length(tenant_key) BETWEEN 1 AND 128),
|
||||
started_at TIMESTAMPTZ NOT NULL, first_data_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE TABLE qa_ops_weekly_quality_snapshots (
|
||||
tenant_key TEXT NOT NULL, week_start TIMESTAMPTZ NOT NULL, week_end TIMESTAMPTZ NOT NULL,
|
||||
frozen_at TIMESTAMPTZ NOT NULL, mirror_revision BIGINT NOT NULL CHECK(mirror_revision>=0),
|
||||
source_observed_at TIMESTAMPTZ NOT NULL, policy_version TEXT NOT NULL,
|
||||
record_count INTEGER NOT NULL CHECK(record_count>=0),
|
||||
coverage_numerator INTEGER NOT NULL CHECK(coverage_numerator>=0), coverage_denominator INTEGER NOT NULL CHECK(coverage_denominator>=coverage_numerator),
|
||||
correctness_numerator INTEGER NOT NULL CHECK(correctness_numerator>=0), correctness_denominator INTEGER NOT NULL CHECK(correctness_denominator>=correctness_numerator),
|
||||
PRIMARY KEY(tenant_key,week_start), CHECK(week_end=week_start+interval '7 days'),
|
||||
CHECK(date_trunc('day',week_start AT TIME ZONE 'Asia/Shanghai')=week_start AT TIME ZONE 'Asia/Shanghai'),
|
||||
CHECK(EXTRACT(ISODOW FROM week_start AT TIME ZONE 'Asia/Shanghai')=1),
|
||||
CHECK(frozen_at>=week_end), CHECK(source_observed_at>=week_end AND source_observed_at<=frozen_at),
|
||||
CHECK(coverage_denominator<=record_count AND correctness_denominator<=record_count)
|
||||
);
|
||||
-- Frozen scalar contributions preserve the original formula under future policy
|
||||
-- changes and allow literal keyword filtering without recalculating old reviews.
|
||||
-- No answers, staff IDs, names or organization memberships are duplicated here.
|
||||
CREATE TABLE qa_ops_weekly_quality_snapshot_records (
|
||||
tenant_key TEXT NOT NULL, week_start TIMESTAMPTZ NOT NULL, record_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
coverage_numerator SMALLINT NOT NULL CHECK(coverage_numerator BETWEEN 0 AND 1),
|
||||
coverage_denominator SMALLINT NOT NULL CHECK(coverage_denominator BETWEEN coverage_numerator AND 1),
|
||||
correctness_numerator SMALLINT NOT NULL CHECK(correctness_numerator BETWEEN 0 AND 1),
|
||||
correctness_denominator SMALLINT NOT NULL CHECK(correctness_denominator BETWEEN correctness_numerator AND 1),
|
||||
PRIMARY KEY(tenant_key,week_start,record_id),
|
||||
FOREIGN KEY(tenant_key,week_start) REFERENCES qa_ops_weekly_quality_snapshots(tenant_key,week_start) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE FUNCTION qa_ops_reject_frozen_quality_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'committed weekly quality snapshots are immutable' USING ERRCODE='55000';
|
||||
END $$;
|
||||
CREATE TRIGGER immutable_weekly_quality_header BEFORE UPDATE OR DELETE ON qa_ops_weekly_quality_snapshots FOR EACH ROW EXECUTE FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
CREATE TRIGGER immutable_weekly_quality_records BEFORE UPDATE OR DELETE ON qa_ops_weekly_quality_snapshot_records FOR EACH ROW EXECUTE FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
|
||||
-- Contributions may only be inserted in the SAME transaction as their header.
|
||||
-- This rejects a later append while allowing the initial atomic CopyFrom batch.
|
||||
CREATE FUNCTION qa_ops_require_new_weekly_quality_header() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent_xid bigint;
|
||||
BEGIN
|
||||
SELECT xmin::text::bigint INTO parent_xid FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=NEW.tenant_key AND week_start=NEW.week_start;
|
||||
IF parent_xid IS NULL OR parent_xid <> mod(pg_current_xact_id()::text::numeric,4294967296)::bigint THEN
|
||||
RAISE EXCEPTION 'cannot append to a committed weekly quality snapshot' USING ERRCODE='55000';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER append_only_new_weekly_quality BEFORE INSERT ON qa_ops_weekly_quality_snapshot_records FOR EACH ROW EXECUTE FUNCTION qa_ops_require_new_weekly_quality_header();
|
||||
@@ -0,0 +1,22 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_quality_reviews r JOIN qa_ops_master_records m ON r.tenant_key=m.tenant_key||'::master' AND r.record_id=m.id LEFT JOIN qa_ops_quality_reviews o ON o.tenant_key=m.tenant_key AND o.record_id=r.record_id AND o.revision=r.revision WHERE o.request_hash IS DISTINCT FROM r.request_hash) OR EXISTS(SELECT 1 FROM qa_ops_master_import_batches) OR EXISTS(SELECT 1 FROM qa_ops_master_records m LEFT JOIN qa_ops_mirror_records s ON s.tenant_key=m.tenant_key AND s.id=m.id WHERE m.origin<>'dobotai_2_0' OR s.id IS NULL OR m.payload IS DISTINCT FROM s.payload OR m.row_revision<>1) THEN
|
||||
RAISE EXCEPTION 'durable master/import/local edits exist; keep additive schema on application rollback';
|
||||
END IF;
|
||||
END $$;
|
||||
DROP TRIGGER qa_mirror_append_to_master ON qa_ops_mirror_records;
|
||||
DROP FUNCTION qa_ops_append_source_to_master();
|
||||
DELETE FROM qa_ops_quality_reviews q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DELETE FROM qa_ops_quality_checks q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DELETE FROM qa_ops_quality_inputs q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DELETE FROM qa_ops_quality_records q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DROP TABLE qa_ops_master_import_rows;
|
||||
DROP TABLE qa_ops_master_source_links;
|
||||
DROP TABLE qa_ops_master_records;
|
||||
DROP TABLE qa_ops_master_import_batches;
|
||||
DROP TABLE qa_ops_master_state;
|
||||
DROP FUNCTION qa_ops_master_protect_provenance();
|
||||
DROP FUNCTION qa_ops_master_revision();
|
||||
DROP FUNCTION qa_ops_master_observe_quality();
|
||||
DROP FUNCTION qa_ops_master_copy_source_quality(text,text);
|
||||
DROP FUNCTION qa_ops_master_event_key(timestamptz,text,text);
|
||||
DROP FUNCTION qa_ops_master_normalize(text);
|
||||
@@ -0,0 +1,119 @@
|
||||
-- A durable, locally-owned master is separate from the replaceable 2.0 mirror.
|
||||
LOCK TABLE qa_ops_mirror_records,qa_ops_quality_records,qa_ops_quality_inputs,qa_ops_quality_checks,qa_ops_quality_reviews IN SHARE ROW EXCLUSIVE MODE;
|
||||
CREATE TABLE qa_ops_master_state (
|
||||
tenant_key TEXT PRIMARY KEY, revision BIGINT NOT NULL DEFAULT 0 CHECK(revision>=0), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE qa_ops_master_import_batches (
|
||||
tenant_key TEXT NOT NULL, id TEXT NOT NULL, source_sha256 TEXT NOT NULL CHECK(source_sha256~'^[a-f0-9]{64}$'),
|
||||
source_name TEXT NOT NULL, sheet_name TEXT NOT NULL, total_rows INTEGER NOT NULL CHECK(total_rows>=0),
|
||||
imported_rows INTEGER NOT NULL CHECK(imported_rows>=0), skipped_rows INTEGER NOT NULL CHECK(skipped_rows>=0), held_rows INTEGER NOT NULL CHECK(held_rows>=0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY(tenant_key,id), UNIQUE(tenant_key,source_sha256,sheet_name),
|
||||
CHECK(total_rows=imported_rows+skipped_rows+held_rows)
|
||||
);
|
||||
CREATE TABLE qa_ops_master_records (
|
||||
tenant_key TEXT NOT NULL, id TEXT NOT NULL, event_key TEXT NOT NULL CHECK(event_key~'^[a-f0-9]{64}$'),
|
||||
origin TEXT NOT NULL CHECK(origin IN ('dobotai_2_0','historical_excel')),
|
||||
asked_at TIMESTAMPTZ NOT NULL, question TEXT NOT NULL, status TEXT NOT NULL, identity JSONB NOT NULL,
|
||||
quality_hash TEXT NOT NULL, payload JSONB NOT NULL CHECK(jsonb_typeof(payload)='object'),
|
||||
CHECK(payload?'id' AND jsonb_typeof(payload->'id')='string' AND payload->>'id'=id),
|
||||
original_fields JSONB NOT NULL DEFAULT '{}'::jsonb CHECK(jsonb_typeof(original_fields)='object'),
|
||||
batch_id TEXT, source_row INTEGER, row_revision BIGINT NOT NULL DEFAULT 1 CHECK(row_revision>0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY(tenant_key,id), FOREIGN KEY(tenant_key,batch_id) REFERENCES qa_ops_master_import_batches(tenant_key,id),
|
||||
CHECK((origin='historical_excel' AND batch_id IS NOT NULL AND source_row>1) OR (origin='dobotai_2_0' AND batch_id IS NULL AND source_row IS NULL))
|
||||
);
|
||||
CREATE INDEX idx_qa_master_window ON qa_ops_master_records(tenant_key,asked_at DESC,id DESC);
|
||||
CREATE INDEX idx_qa_master_original_event ON qa_ops_master_records(tenant_key,event_key);
|
||||
CREATE TABLE qa_ops_master_source_links (
|
||||
tenant_key TEXT NOT NULL, source_kind TEXT NOT NULL, source_id TEXT NOT NULL, master_id TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY(tenant_key,source_kind,source_id),
|
||||
FOREIGN KEY(tenant_key,master_id) REFERENCES qa_ops_master_records(tenant_key,id)
|
||||
);
|
||||
CREATE TABLE qa_ops_master_import_rows (
|
||||
tenant_key TEXT NOT NULL, batch_id TEXT NOT NULL, row_number INTEGER NOT NULL CHECK(row_number>1),
|
||||
disposition TEXT NOT NULL CHECK(disposition IN ('imported','skipped_duplicate','held_missing_key')),
|
||||
original_fields JSONB NOT NULL CHECK(jsonb_typeof(original_fields)='object'), master_id TEXT,
|
||||
PRIMARY KEY(tenant_key,batch_id,row_number), FOREIGN KEY(tenant_key,batch_id) REFERENCES qa_ops_master_import_batches(tenant_key,id),
|
||||
FOREIGN KEY(tenant_key,master_id) REFERENCES qa_ops_master_records(tenant_key,id)
|
||||
);
|
||||
CREATE FUNCTION qa_ops_master_normalize(value text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT btrim(replace(replace(COALESCE(value,''),E'\r\n',E'\n'),E'\r',E'\n'),chr(9)||chr(10)||chr(11)||chr(12)||chr(13)||chr(28)||chr(29)||chr(30)||chr(31)||chr(32)||chr(133)||chr(160)||chr(5760)||chr(8192)||chr(8193)||chr(8194)||chr(8195)||chr(8196)||chr(8197)||chr(8198)||chr(8199)||chr(8200)||chr(8201)||chr(8202)||chr(8232)||chr(8233)||chr(8239)||chr(8287)||chr(12288)) $$;
|
||||
CREATE FUNCTION qa_ops_master_event_key(at_time timestamptz,person text,original_question text) RETURNS text LANGUAGE sql STABLE AS $$
|
||||
SELECT encode(sha256(convert_to(jsonb_build_array(to_char(at_time AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD HH24:MI:SS'),qa_ops_master_normalize(person),qa_ops_master_normalize(original_question))::text,'UTF8')),'hex')
|
||||
$$;
|
||||
CREATE FUNCTION qa_ops_master_revision() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
INSERT INTO qa_ops_master_state(tenant_key,revision) VALUES(NEW.tenant_key,1) ON CONFLICT(tenant_key) DO UPDATE SET revision=qa_ops_master_state.revision+1,updated_at=clock_timestamp();
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER qa_master_revision AFTER INSERT OR UPDATE ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_revision();
|
||||
CREATE FUNCTION qa_ops_master_protect_provenance() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF ROW(NEW.tenant_key,NEW.id,NEW.event_key,NEW.origin,NEW.original_fields,NEW.batch_id,NEW.source_row) IS DISTINCT FROM ROW(OLD.tenant_key,OLD.id,OLD.event_key,OLD.origin,OLD.original_fields,OLD.batch_id,OLD.source_row) THEN
|
||||
RAISE EXCEPTION 'master provenance and original deduplication key are immutable' USING ERRCODE='55000';
|
||||
END IF;
|
||||
NEW.row_revision=OLD.row_revision+1;NEW.updated_at=clock_timestamp();
|
||||
IF jsonb_build_array(NEW.payload->'status',NEW.payload->'question',NEW.payload->'answer',NEW.payload->'references',NEW.payload->'media') IS DISTINCT FROM jsonb_build_array(OLD.payload->'status',OLD.payload->'question',OLD.payload->'answer',OLD.payload->'references',OLD.payload->'media') THEN
|
||||
NEW.quality_hash=encode(sha256(convert_to(jsonb_build_array(NEW.id,NEW.payload->'status',NEW.payload->'question',NEW.payload->'answer',NEW.payload->'references',NEW.payload->'media')::text,'UTF8')),'hex');
|
||||
NEW.payload=NEW.payload||jsonb_build_object('_quality_hash',NEW.quality_hash,'_quality_observed_at',NEW.updated_at);
|
||||
END IF;
|
||||
IF NEW.payload IS DISTINCT FROM OLD.payload THEN
|
||||
NEW.question=NEW.payload->>'question';NEW.asked_at=(NEW.payload->>'asked_at')::timestamptz;NEW.status=NEW.payload->>'status';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER qa_master_provenance BEFORE UPDATE ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_protect_provenance();
|
||||
-- Keep ALL existing 2.0 IDs, even pre-existing equal-key events; this is not an authorization to delete them.
|
||||
INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)
|
||||
SELECT tenant_key,id,qa_ops_master_event_key(asked_at,payload->>'asker',question),'dobotai_2_0',asked_at,question,status,identity,quality_hash,payload FROM qa_ops_mirror_records;
|
||||
INSERT INTO qa_ops_master_source_links(tenant_key,source_kind,source_id,master_id)
|
||||
SELECT tenant_key,'dobotai_2_0',id,id FROM qa_ops_mirror_records;
|
||||
-- Preserve copied audit identities/timestamps; the original namespace is never updated.
|
||||
CREATE FUNCTION qa_ops_master_copy_source_quality(source_tenant text,source_id text) RETURNS boolean LANGUAGE plpgsql AS $$
|
||||
DECLARE copied bigint;
|
||||
BEGIN
|
||||
INSERT INTO qa_ops_quality_records SELECT q.tenant_key||'::master',q.record_id,q.observed_at,q.input_hash,q.input_epoch,q.review_revision FROM qa_ops_quality_records q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id) ON CONFLICT DO NOTHING;
|
||||
GET DIAGNOSTICS copied=ROW_COUNT; IF copied=0 THEN RETURN false; END IF;
|
||||
INSERT INTO qa_ops_quality_inputs SELECT q.tenant_key||'::master',q.record_id,q.input_epoch,q.input_hash,q.payload,q.created_at FROM qa_ops_quality_inputs q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id);
|
||||
INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source,created_at) SELECT q.tenant_key||'::master',q.record_id,q.input_epoch,q.rule_version,q.result,q.source,q.created_at FROM qa_ops_quality_checks q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id);
|
||||
INSERT INTO qa_ops_quality_reviews SELECT q.tenant_key||'::master',q.record_id,q.revision,q.input_epoch,q.input_hash,q.fields,q.reason,q.reviewer,q.nonce,q.request_hash,q.created_at FROM qa_ops_quality_reviews q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id);
|
||||
RETURN true;
|
||||
END $$;
|
||||
SELECT qa_ops_master_copy_source_quality(tenant_key,NULL) FROM (SELECT DISTINCT tenant_key FROM qa_ops_master_records) tenants;
|
||||
CREATE FUNCTION qa_ops_master_observe_quality() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE quality_tenant text=NEW.tenant_key||'::master'; next_epoch bigint; assessment jsonb; evidence jsonb; observed timestamptz;
|
||||
BEGIN
|
||||
IF TG_OP='UPDATE' AND NEW.quality_hash=OLD.quality_hash THEN RETURN NEW; END IF;
|
||||
IF TG_OP='INSERT' AND NEW.origin='dobotai_2_0' THEN
|
||||
PERFORM qa_ops_master_copy_source_quality(NEW.tenant_key,NEW.id);
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_quality_records WHERE tenant_key=quality_tenant AND record_id=NEW.id AND input_hash=NEW.quality_hash) THEN RETURN NEW; END IF;
|
||||
END IF;
|
||||
observed=COALESCE((NEW.payload->>'_quality_observed_at')::timestamptz,NEW.updated_at);
|
||||
INSERT INTO qa_ops_quality_records(tenant_key,record_id) VALUES(quality_tenant,NEW.id) ON CONFLICT DO NOTHING;
|
||||
SELECT input_epoch+1 INTO next_epoch FROM qa_ops_quality_records WHERE tenant_key=quality_tenant AND record_id=NEW.id FOR UPDATE;
|
||||
evidence=jsonb_build_object('version','governance-master-quality-v1','id',NEW.id,'status',NEW.status,'question',NEW.question,'answer',COALESCE(NEW.payload->>'answer',''),'references',COALESCE(NEW.payload->'references','null'::jsonb),'media',COALESCE(NEW.payload->'media','null'::jsonb));
|
||||
assessment=jsonb_build_object('state','pending','rule_version','governance-answer-substring-v1');
|
||||
IF position('暂无已发布' IN COALESCE(NEW.payload->>'answer',''))>0 THEN assessment=assessment||jsonb_build_object('state','checked','verdict','uncovered','matched_text','暂无已发布'); END IF;
|
||||
INSERT INTO qa_ops_quality_inputs(tenant_key,record_id,input_epoch,input_hash,payload) VALUES(quality_tenant,NEW.id,next_epoch,NEW.quality_hash,evidence);
|
||||
INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source) VALUES(quality_tenant,NEW.id,next_epoch,'governance-answer-substring-v1',assessment,COALESCE(NEW.payload->'source_coverage',jsonb_build_object('verdict','','reason_code','','evaluator_version','')));
|
||||
UPDATE qa_ops_quality_records SET input_epoch=next_epoch,input_hash=NEW.quality_hash,observed_at=observed WHERE tenant_key=quality_tenant AND record_id=NEW.id;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER qa_master_quality AFTER INSERT OR UPDATE ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_observe_quality();
|
||||
CREATE FUNCTION qa_ops_append_source_to_master() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE key_value text; matched_id text; matches bigint;
|
||||
BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_master_source_links WHERE tenant_key=NEW.tenant_key AND source_kind='dobotai_2_0' AND source_id=NEW.id) THEN RETURN NEW; END IF;
|
||||
key_value=qa_ops_master_event_key(NEW.asked_at,NEW.payload->>'asker',NEW.question);
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended(NEW.tenant_key||key_value,254));
|
||||
SELECT count(*),min(id) INTO matches,matched_id FROM qa_ops_master_records WHERE tenant_key=NEW.tenant_key AND event_key=key_value;
|
||||
IF matches<>1 THEN
|
||||
matched_id=NEW.id;
|
||||
INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)
|
||||
VALUES(NEW.tenant_key,NEW.id,key_value,'dobotai_2_0',NEW.asked_at,NEW.question,NEW.status,NEW.identity,NEW.quality_hash,NEW.payload);
|
||||
END IF;
|
||||
INSERT INTO qa_ops_master_source_links(tenant_key,source_kind,source_id,master_id) VALUES(NEW.tenant_key,'dobotai_2_0',NEW.id,matched_id);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
-- UPDATE only admits an unlinked source. A linked row never rewrites the master;
|
||||
-- DELETE deliberately has NO corresponding master trigger or cascading FK.
|
||||
CREATE TRIGGER qa_mirror_append_to_master AFTER INSERT OR UPDATE ON qa_ops_mirror_records FOR EACH ROW EXECUTE FUNCTION qa_ops_append_source_to_master();
|
||||
@@ -0,0 +1,3 @@
|
||||
DROP TRIGGER qa_master_operational ON qa_ops_master_records;
|
||||
DROP FUNCTION qa_ops_master_operational_fields();
|
||||
ALTER TABLE qa_ops_master_records DROP COLUMN local_fields,DROP COLUMN coverage_result,DROP COLUMN chinese_question;
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Small read-model fields keep master dashboards independent of long answer payloads.
|
||||
ALTER TABLE qa_ops_master_records ADD COLUMN local_fields JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||
ALTER TABLE qa_ops_master_records ADD COLUMN coverage_result JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||
ALTER TABLE qa_ops_master_records ADD COLUMN chinese_question TEXT NOT NULL DEFAULT '';
|
||||
CREATE FUNCTION qa_ops_master_operational_fields() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE fields jsonb=COALESCE(NEW.payload->'master_fields','{}'::jsonb); answer text=COALESCE(NEW.payload->>'answer','');
|
||||
BEGIN
|
||||
NEW.local_fields=jsonb_build_object('coverage',COALESCE(fields->>'coverage',''),'is_correct',COALESCE(fields->>'is_correct',''),'product_category',COALESCE(fields->>'product_category',''),'problem_type',COALESCE(fields->>'problem_type',''),'root_cause',COALESCE(fields->>'root_cause',''),'language',COALESCE(fields->>'language',''),'trigger_person',COALESCE(fields->>'trigger_person',NEW.payload->>'trigger_person',''),'asker',COALESCE(NEW.payload->>'asker',''),'department',COALESCE(fields->>'department',NEW.payload->>'department',''),'region',COALESCE(fields->>'region',NEW.payload->>'region',''));
|
||||
NEW.chinese_question=COALESCE(fields->>'question_chinese','');
|
||||
NEW.coverage_result=jsonb_build_object('state',CASE WHEN qa_ops_master_normalize(answer)='' THEN 'pending' ELSE 'checked' END,'rule_version','master-answer-substring-v2','verdict',CASE WHEN qa_ops_master_normalize(answer)='' THEN '' WHEN position('暂无已发布' IN answer)>0 THEN 'uncovered' ELSE 'covered' END,'matched_text',CASE WHEN position('暂无已发布' IN answer)>0 THEN '暂无已发布' ELSE '' END);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
-- Run before the provenance trigger so its hash protections remain unchanged.
|
||||
CREATE TRIGGER qa_master_operational BEFORE INSERT OR UPDATE OF payload ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_operational_fields();
|
||||
UPDATE qa_ops_master_records SET payload=payload;
|
||||
@@ -0,0 +1,2 @@
|
||||
DO $$ BEGIN IF EXISTS(SELECT 1 FROM qa_ops_ai_settings) THEN RAISE EXCEPTION 'AI settings must be explicitly archived before removing secure configuration storage' USING ERRCODE='55000';END IF;END $$;
|
||||
DROP TABLE qa_ops_ai_config_history,qa_ops_ai_settings;
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE qa_ops_ai_settings (
|
||||
tenant_key TEXT PRIMARY KEY, revision BIGINT NOT NULL CHECK(revision>0), base_url TEXT NOT NULL,model TEXT NOT NULL,
|
||||
key_ciphertext BYTEA NOT NULL, verification TEXT NOT NULL CHECK(verification IN ('not_configured','verified','unverified','rejected')),
|
||||
checked_at TIMESTAMPTZ,automatic_evaluation BOOLEAN NOT NULL DEFAULT false,automatic_translation BOOLEAN NOT NULL DEFAULT false,
|
||||
evaluation_initialized BOOLEAN NOT NULL DEFAULT false,translation_initialized BOOLEAN NOT NULL DEFAULT false,
|
||||
updated_by TEXT NOT NULL,updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE qa_ops_ai_config_history (
|
||||
tenant_key TEXT NOT NULL,revision BIGINT NOT NULL,base_url TEXT NOT NULL,model TEXT NOT NULL,key_configured BOOLEAN NOT NULL,
|
||||
verification TEXT NOT NULL,actor TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,revision)
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
DO $$ BEGIN IF EXISTS(SELECT 1 FROM qa_ops_ai_work) OR EXISTS(SELECT 1 FROM qa_ops_ai_batches) THEN RAISE EXCEPTION 'AI job and evidence history must be archived before removing the durable queue' USING ERRCODE='55000';END IF;END $$;
|
||||
DROP VIEW qa_ops_master_read_model;
|
||||
DROP FUNCTION qa_ops_fill_empty_fields(jsonb,jsonb);
|
||||
DROP TABLE qa_ops_ai_batch_actions,qa_ops_ai_automatic_seen,qa_ops_ai_automation_events,qa_ops_ai_outputs,qa_ops_ai_batch_items,qa_ops_ai_work,qa_ops_ai_batches,qa_ops_ai_previews,qa_ops_ai_runtime;
|
||||
|
||||
CREATE OR REPLACE FUNCTION qa_ops_append_source_to_master() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE key_value text; matched_id text; matches bigint;
|
||||
BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_master_source_links WHERE tenant_key=NEW.tenant_key AND source_kind='dobotai_2_0' AND source_id=NEW.id) THEN RETURN NEW; END IF;
|
||||
key_value=qa_ops_master_event_key(NEW.asked_at,NEW.payload->>'asker',NEW.question);
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended(NEW.tenant_key||key_value,254));
|
||||
SELECT count(*),min(id) INTO matches,matched_id FROM qa_ops_master_records WHERE tenant_key=NEW.tenant_key AND event_key=key_value;
|
||||
IF matches<>1 THEN
|
||||
matched_id=NEW.id;
|
||||
INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)
|
||||
VALUES(NEW.tenant_key,NEW.id,key_value,'dobotai_2_0',NEW.asked_at,NEW.question,NEW.status,NEW.identity,NEW.quality_hash,NEW.payload);
|
||||
END IF;
|
||||
INSERT INTO qa_ops_master_source_links(tenant_key,source_kind,source_id,master_id) VALUES(NEW.tenant_key,'dobotai_2_0',NEW.id,matched_id);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user