feat(datasource): 完成 M03 数据源配置与熔断巡检

交付三种引擎登记、草稿/已保存连接测试、可逆启用、每源熔断与 Cron 巡检,以及控制台页面;用户确认收尾后标 DONE_LOCAL。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-18 12:50:46 +08:00
1 parent f17bf19709
commit e6d37d176d
98 files changed
+9097 -91

No files matched your search

@@ -0,0 +1,54 @@
# Task Context Pack
## Task Goal
M03 S8:控制台覆盖 D23 — 保存前草稿测、启用、表单校验、详情熔断参数与状态展示。
## Current Slice Or Group
**S8**(已批准编码);`gateClass: standard`,`risk_score: 3`
## Requirement Source
`.task/2026-11-17/m03-datasource/requirement.md`(D23 UI)
## Implementation Source
`.task/2026-11-17/m03-datasource/implementation-plan.md` Slice 8
## Allowed Modification Scope
- `web/apps/console/src/datasources/**`
- `web/apps/console/locales/**`(四语言)
- `web/apps/console/e2e/**` 数据源相关
- 必要时极薄改动:`router.ts` / `AppShell.vue`(仅若导航文案需要)
## Forbidden Modification Scope
- 后端协议重写/迁移动 S6/S7 语义;口令进 localStorage;企微 UI;巡检 Cron 前端配置页(后端 env 即可)
## Key Entrypoints
- `DatasourceEdit.vue`、`DatasourceList.vue`、`client.ts`、`types.ts`、`payload.ts`
- API:`POST /datasources/test-draft`、`POST .../enable`、PATCH circuit_* 字段、公开 JSON 含 circuit_*
- UI 规则:D22 页脚居中;`docs/current/frontend-ui.md`
- 规范:`standards://frontend/frontend-stack?version=2.1.0`、`standards://frontend/element-plus?version=1.0.2`
## Validation Commands
```
cd web/apps/console && pnpm test:unit && pnpm test:e2e && pnpm typecheck
```
(或 filter `@watchman/console` 从 web/)
## Assumptions
- 草稿测:新建密码必填;编辑密码留空可带 id 用已存密文
- host 仅必填;port 1–65535;熔断默认 300/3/600,详情可编辑
- 停用显示启用;开闸提示 + circuit_open_until
- 列表行:停用可启用;开闸不可已保存测试
## Stop Conditions
- S8 评审后进入模块验收门禁(最终确认前不标 DONE_LOCAL)
@@ -0,0 +1,485 @@
# M03 数据源配置 Implementation Plan
## Requirement Source
`.task/2026-11-17/m03-datasource/requirement.md`
## Scope Summary
第一阶段实现数据库数据源的登记、编辑、停用/启用、草稿与已保存连接测试、每源熔断参数、Cron 周期巡检和空引用占位,覆盖 PostgreSQL、MySQL、SQL Server。凭证加密落在平台库。S1–S5 已完成;本增补为 S6–S8(D23)。
## Involved Modules Or Areas
- 后端服务包 `services/watchman`:模型、迁移、加密、连接器、API、权限。
- 控制台 `web/apps/console`:仅在原型确认后的切片。
- 开发 Compose:仅为 SQL Server 测试追加本机服务,不改平台库定义。
- 不改登录、Casdoor、查询、报警。
## Loaded Rules
- `AGENTS.md` 项目本地段:凭证不入库;主 Agent 不代替实现子 Agent 写业务代码(编码阶段)。
- `.cursor/rules/sy-standards.mdc`:API 信封、错误、权限点、安全红线。
- Marionettist `gatePolicy.selected=autonomous`。`risk_score >= 4`、高风险/边界敏感、以及用户指定的原型确认仍然停。
## Loaded Docs
- `docs/tasks/INDEX.md` M03、交接稿 A-01、`docs/decisions.md` D14/D19、`docs/progress.md`。
- 现有权限:`services/watchman/src/watchman/auth/access.py`。
- 现有模型与信封:`models/platform.py`、`core/errors.py`、`core/response.py`。
## Global Forbidden Scope
- 口令、连接串、加密密钥写入仓库、文档、测试快照、审计 payload、日志。
- `.env.local`、`.cursor/mcp.json`。
- M02 登录流程、已有三枚权限点的语义。
- 查询执行、非数据库来源的可用实现。
- 在原型确认前修改 `web/apps/console` 的数据源页面。
- 生产库、真实 MES、`git reset --hard`、自动 commit。
## Execution Strategy
- Complexity: complex
- Default Execution: sequential
- Parallel Execution: not-needed
- Fallback Execution: sequential
- Merge Owner: 主 Agent
- Conflict Resolution Rule: 后一切片不得改前一切片已冻结的表身份列和权限点字符串;冲突时停下来问用户。
## Slice Dependency Graph
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
| --- | --- | --- | --- | --- | --- | --- |
| S1 模型与密文 | 分析确认 | 无 | 1 | 迁移、模型包 | 主 Agent | medium |
| S2 三种驱动与连接测试 | S1 | 无 | 2 | 连接器包、开发 Compose | 主 Agent | medium |
| S3 API 与权限 | S1、S2 | 无 | 3 | 路由、access.py | 主 Agent | high |
| S4 HTML 原型 | S3 的字段口径;可在 S3 评审通过后立刻做 | 无 | 4 | 仅原型目录 | 主 Agent | low |
| S5 Vue 页面 | S4 用户确认 | 无 | 5 | web/apps/console | 主 Agent | medium |
| S6 启用/草稿测/熔断模型 | S5 | 无 | 6 | 迁移、services、routes | 主 Agent | high |
| S7 Cron 巡检 | S6 | 无 | 7 | worker/beat、settings | 主 Agent | high |
| S8 控制台增补 | S6、S7 | 无 | 8 | web/apps/console | 主 Agent | medium |
## Implementation Slices
### Slice 1: 数据源模型、迁移与凭证密文
#### Goal
平台库能按租户保存数据源元数据和口令密文。种类与引擎可扩展,非数据库种类没有可用行。
#### Allowed Modification Scope
- `services/watchman/src/watchman/models/`
- `services/watchman/migrations/`
- `services/watchman/src/watchman/core/` 中新增的密钥读取与加解密
- `services/watchman/tests/` 中对应该切片的测试
- `.env.example` 只增加占位名,不写真实密钥
#### Forbidden Scope
- API 路由、前端、连接真实源库、Compose 中的 SQL Server。
- 任何真实口令。
#### Execution
- Mode: sequential
- Depends On: 分析到编码的用户确认
- Can Run With: 无
- Must Not Run With: S2、S3
- Fallback Order: 1
- Shared Files: `models/__init__.py`、迁移链
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: schema-migration, credential-storage
- Validation Level: slice
- Recommended Agent Strategy: 实现子 Agent 编码;审查用不同模型系列
#### Steps
1. 新增数据源表:租户、名称唯一、种类、引擎、连接字段、密文、启用状态、最近测试类别与时间。启用 RLS,租户来自服务端。
2. 种类枚举保留扩展点;写入约束本阶段只允许 database 加三种引擎。
3. 加解密密钥只从环境变量读取。测试用临时密钥。
4. 单元测试:加密往返、日志/序列化不含明文、错误种类不能入库。
#### Validation
- `uv run pytest` 中本切片新增测试,以及现有平台 RLS 测试仍通过。
- `alembic upgrade head` 在开发库可重复执行到新版本。
#### Done Criteria
- 迁移可升级。密文列不接受明文 API 形态(此切片尚无 API)。
- 测试不包含真实口令。
#### Rollback Notes
- 降级迁移只删除本切片新增表。不改 `audit_events` / `run_records`。
### Slice 2: PostgreSQL、MySQL、SQL Server 连接测试
#### Goal
对已保存的数据库目标做有超时的连接测试,并把结果分成成功、认证失败、超时、不可达、服务端拒绝(`rejected`)。只有有正面证据时才标认证失败。
#### Allowed Modification Scope
- `services/watchman` 内新建的数据源连接器与测试
- `services/watchman` 依赖清单中的三种数据库驱动
- `deploy/compose.dev.yml` 仅增加绑定 127.0.0.1 的 SQL Server 测试服务
- 测试脚本创建隔离库表。口令只进 `.env.local`
#### Forbidden Scope
- 对目标执行 DDL/DML。连通性只用驱动 ping 或 `SELECT 1`。
- 生产库。把容器口令写进 Compose 仓库文件。
- 前端。
#### Execution
- Mode: sequential
- Depends On: S1 评审通过后的用户确认(high-risk 停点)
- Can Run With: 无
- Must Not Run With: S3、S5
- Fallback Order: 2
- Shared Files: 依赖锁文件、compose
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: external-connection, new-dependencies, test-infrastructure
- Validation Level: slice
- Recommended Agent Strategy: 实现子 Agent;SQL Server 安装可委派子 Agent,口令不回写到对话摘要以外的仓库文件
#### Steps
1. 定义连接器接口。三种引擎各一实现。其他种类返回“未实现”,且本阶段没有这类数据行。
2. 统一超时和错误分类。日志只记类别和数据源 ID。
3. 用 `.env.local` 连接本地 Postgres、本地 MySQL,并创建专用测试库。
4. Docker 安装 SQL Server,同样创建专用测试库,跑同一组分类测试。
#### Validation
- 三种引擎:正确口令成功;错误口令为认证失败;不可路由或拒绝连接为不可达;超时上限内返回超时类别。
- 断言响应与日志夹具不含口令。
#### Done Criteria
- 三类失败与成功在测试中分开。
- SQL Server 只监听本机。若 Docker 不可用,该引擎标 BLOCKED,不能写成通过。
#### Rollback Notes
- 移除驱动依赖和 Compose 服务。不删除用户原有的本地 Postgres/MySQL 实例。只删除本切片创建的测试库。
### Slice 3: 数据源 API、权限与空引用
#### Goal
提供列表、详情、创建、更新、停用、连接测试和空引用。权限点按需求表强制。
#### Allowed Modification Scope
- `services/watchman/src/watchman/api/`
- `services/watchman/src/watchman/auth/access.py` 只新增三枚数据源权限点及角色判断
- 数据源服务层与 API 测试
- 审计写入处:payload 不含凭证
#### Forbidden Scope
- 改 ENTER / PLATFORM_WRITE / OBJECT_READ 的含义。
- 前端页面。
- 接受调用方传入的租户 ID 或任意连接 URL。
#### Execution
- Mode: sequential
- Depends On: S2 评审通过后的用户确认
- Can Run With: 无
- Must Not Run With: S5
- Fallback Order: 3
- Shared Files: `access.py`、`api/app.py`
- Merge Owner: 主 Agent
- Conflict Risk: high
- Gate Class: boundary-sensitive
- Risk Score: 4
- Gate Reasons: permission-nodes, credential-api, tenant-boundary
- Validation Level: slice
- Recommended Agent Strategy: 实现子 Agent;审查用不同模型系列
#### Steps
1. 按需求实现 API。创建只接受 database 与三种引擎。
2. 接入三角色。无会话 41000,无权限 42000 且带权限点。
3. 详情不返回密文。更新时口令字段缺省表示不替换。
4. 引用返回空 `items`。
5. 停用后测试返回冲突或参数错误中的稳定类别,记录仍可 GET。
#### Validation
- API 测试覆盖权限矩阵、脱敏、停用、非法种类、引用空列表。
- 现有 auth/platform 测试仍通过。
#### Done Criteria
- 验收标准 1、2、4、5、6 的后端部分有测试证据。
- 三枚新权限点字符串与需求表一致。
#### Rollback Notes
- 路由可从应用移除。权限函数删除不得影响原有三枚节点。
### Slice 4: HTML 原型
#### Goal
给出一份可在浏览器打开的静态原型,供用户确认信息架构和状态,然后再写 Vue。
#### Allowed Modification Scope
- `.task/2026-11-17/m03-datasource/prototype/` 下的 HTML/CSS/少量静态脚本
- 原型说明一份,放在同一目录
#### Forbidden Scope
- `web/`、后端、真实口令、真实 API 地址。
#### Execution
- Mode: sequential
- Depends On: S3 完成(字段与状态已稳定)
- Can Run With: 无
- Must Not Run With: S5
- Fallback Order: 4
- Shared Files: 无
- Merge Owner: 主 Agent
- Conflict Risk: low
- Gate Class: standard
- Risk Score: 2
- Gate Reasons: user-required-prototype-approval
- Validation Level: slice
- Recommended Agent Strategy: 委派 subagent 出原型;主 Agent 只检查是否越界
#### Steps
1. 委派 subagent 按需求的用户流程做单页或少量静态页。
2. 覆盖空列表、表单、测试中、成功、认证失败、超时、停用、空引用、查看者/处理者/管理者的按钮差异。
3. 主 Agent 把打开方式交给用户,停止等待确认。
#### Validation
- 本地用浏览器打开原型,核对上述状态都在页面上。不要求接 API。
#### Done Criteria
- 原型文件只在任务目录。
- 明确记录“未确认,禁止开始 S5”。
#### Rollback Notes
- 删除原型目录不影响运行中的服务。
### Slice 5: 控制台数据源页面
#### Goal
在用户确认原型后,把同等流程做到控制台,并接上 S3 的 API。
#### Allowed Modification Scope
- `web/apps/console/src/` 数据源功能、路由入口、i18n
- 对应 vitest 与 Playwright
#### Forbidden Scope
- 在用户确认原型之前开始本切片。
- 后端协议重写。页面不得保存口令到 localStorage。
- 非数据库来源的可用表单。
#### Execution
- Mode: sequential
- Depends On: 用户对 S4 原型的明确确认
- Can Run With: 无
- Must Not Run With: 无
- Fallback Order: 5
- Shared Files: `App.vue` 或现有壳层导航
- Merge Owner: 主 Agent
- Conflict Risk: medium
- Gate Class: standard
- Risk Score: 3
- Gate Reasons: ui-after-prototype
- Validation Level: final
- Recommended Agent Strategy: 实现子 Agent;浏览器验证用 Playwright
#### Steps
1. 按确认后的原型实现列表、表单、测试状态、停用和空引用。
2. 按钮按角色隐藏,同时依赖后端 42000。
3. Playwright 覆盖主路径和“口令不被回填”。
#### Validation
- `pnpm` 下现有前端测试加新用例。
- Playwright 跑通数据源主路径。浏览器里实际点选一遍。
#### Done Criteria
- 验收标准 7 的页面部分有断言和截图路径(截图默认 gitignore)。
- 与原型的差异已记在任务卡,未确认的差异不算完成。
#### Rollback Notes
- 前端改动可单独回退,不影响已发布的 API。
### Slice 6: 启用、草稿测试、熔断账本与 usable
#### Goal
后端支持启用、草稿测试、每源熔断参数与运行态、统一失败记账与 `assert_usable`;已保存测试在停用或开闸时拒绝。
#### Allowed Modification Scope
- `services/watchman` 模型、迁移、datasources 服务/probe、API 路由、settings 读取(探测超时/重试)
- 对应 pytest
#### Forbidden Scope
- 企微发送;场景页;手写 Cron 解析器;自动改 `enabled`;前端大改(留给 S8)
#### Execution
- Mode: sequential
- Depends On: 用户确认本增补进入编码
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: schema-migration, circuit-semantics
- Validation Level: slice
#### Steps
1. 迁移:熔断三参数、circuit_state、circuit_opened_at、窗口失败计数/窗口起点(或等价可测结构)。
2. `enable_datasource`;disable/enable 与熔断解耦。
3. `test-draft`:表单探测,不写 last_test,不记账。
4. 已保存测试:停用或开闸拒绝;否则探测并记账/成功清计数(未开闸时)。
5. `assert_usable(enabled && closed)`;导出供后续模块。
6. 更新校验:host 必填即可;熔断参数上下限。
#### Validation
- pytest:启用往返;草稿不落库;开闸拒绝测试;冷却后熄闸;参数持久化。
#### Done Criteria
- 验收 4、6、7、8 的后端部分有测试。
#### Rollback Notes
- 回滚迁移与服务改动;不碰前端。
### Slice 7: Cron 周期巡检
#### Goal
配置开关 + Cron 驱动的批量连通性巡检;失败写 last_test 与审计,不发企微。
#### Allowed Modification Scope
- Celery 任务/beat 调度注册、datasources 巡检服务、`.env.example` 占位、对应测试
- 复用成熟 Cron 库(如 croniter)与现有 Celery Beat,薄适配
#### Forbidden Scope
- 第二套调度引擎;企微;改熔断语义(只调用 S6 记账接口)
#### Execution
- Mode: sequential
- Depends On: S6
- Gate Class: high-risk
- Risk Score: 4
- Gate Reasons: scheduling, production-config
- Validation Level: slice
#### Steps
1. 配置项:`HEALTHCHECK_ENABLED`、`HEALTHCHECK_CRON`(及探测超时/重试若未在 S6 完成)。
2. 任务:枚举启用且未开闸源 → 探测 → 记账/更新 last_test → 失败审计。
3. enabled=false 或 Cron 无效则 no-op。
4. 单测用固定时钟/mock probe,不打真实外网。
#### Validation
- pytest:开关关闭不跑;开闸源跳过;失败写审计无密钥。
#### Done Criteria
- 验收 9 后端有证据。
#### Rollback Notes
- 去掉任务注册与配置项即可。
### Slice 8: 控制台增补(启用/草稿测/校验/熔断配置)
#### Goal
控制台覆盖 D23 交互:保存前测试、启用、表单校验、详情熔断参数与状态展示。
#### Allowed Modification Scope
- `web/apps/console` 数据源页面、client、i18n、vitest、Playwright
#### Forbidden Scope
- 后端协议重写;口令进 localStorage;企微 UI
#### Execution
- Mode: sequential
- Depends On: S6(API);S7 可不阻塞 UI,但巡检无前端配置页(仅后端配置)
- Gate Class: standard
- Risk Score: 3
- Validation Level: final
#### Steps
1. 新建/编辑:草稿测试按钮;保存前可用。
2. 停用行/详情:启用按钮。
3. 详情:熔断三参数表单项;开闸提示与恢复时间。
4. Element Plus 表单规则(host 仅必填)。
5. Playwright/单测覆盖主路径。
#### Validation
- 前端单测 + Playwright;与 S6 API 联调。
#### Done Criteria
- 验收 11;模块可进入整体 review。
#### Rollback Notes
- 前端可单独回退。
## Parallel Slice Groups
无。S6→S7→S8 顺序执行。
## Final Validation
- 后端:`uv run pytest` 全量;迁移到新 head。
- 前端:单测 + Playwright。
- 模块级独立 review 后,用户确认再 DONE_LOCAL。
## Documentation Update Requirement
- D21、D22、D23 已记入 `docs/decisions.md`。
- 熔断/usable 边界若稳定,实现后更新 `docs/current` 与知识地图。
- `docs/progress.md` 每片门禁更新。
## Risks
- S6、S7 为 risk_score 4,autonomous 下每片评审后仍停。
- S8 为 standard/3;S6 通过后可按 autonomous 继续,但仍保留最终验收。
- 熄闸后可能立刻再开闸——按需求接受。
+52
View File
@@ -0,0 +1,52 @@
# Task Intake Result
## Task Type
feature。Tier L(凭证保护、外部连接测试、可扩展数据源边界;跨后端 API/前端/迁移)。
## Current Understanding
- 用户要求推进 M03(数据源配置)。当前 `docs/progress.md`:M02 DONE_LOCAL,无进行中模块。
- 用户本轮范围收窄:第一阶段先做**数据库接入**,同时为其他数据来源(API/消息等)留扩展位;不把非 DB 来源做成首版可运行能力。
- 前端正式开发前,先委托 subagent 产出**可确认的原型 HTML**;用户确认后再写 Vue 页面。
- 冻结文档 A-01:新建/编辑/连接测试/停用/引用查看;凭证后端受控、界面不回显;首版只读数据库采集;源库类型不等于平台库;接口/MQ/视频等暂不强制。
- INDEX M03 完整边界:数据源 API+列表/编辑+连接测试、凭证保护及引用提示。本轮将按用户“分阶段”拆:先 DB 接入骨架与 API,UI 在原型确认后推进。
- O01–O07 与 M03 无硬阻塞;O08 跨系列委派仍开放。
## Gate Policy
- config/default: balanced
- allowTaskOverride: true
- recommended: balanced
- selected: autonomous
- reason or override reason: 用户在 2026-11-17 明确选择 autonomous。推荐 balanced 仅作建议(凭证/外连/迁移偏敏感),不覆盖该选择。
- effective: autonomous
- finalApprovalRequired: true
说明:autonomous 不取消分析→编码门禁、最终验收、`gateClass: high-risk|boundary-sensitive`、critic、显式停点、危险命令,以及 `risk_score >= 4` 的停顿。前端原型 HTML 确认视为编码前/UI 切片前的显式停点。
## Blocking Questions
已由用户在 2026-11-17 确认,并写入需求与 D21:
1. 第一阶段含后端,以及原型确认后的列表/编辑/测试 UI。
2. 现在支持 PostgreSQL、MySQL、SQL Server。SQL Server 用 Docker 测试。允许创建测试库表。口令不写入仓库。
3. 平台库加密字段,API 不回显,日志脱敏。
4. 引用用空列表/占位契约。
## Non-blocking Assumptions
- 源类型用可扩展枚举/策略接口;非 DB 类型 API 可返回“暂不支持”或只存元数据但不提供连接测试实现。
- 连接测试对真实外网/生产库默认 Mock/合成;真实外连另获准。
- 原型 HTML 为静态交互稿,不接真实 API,不作为后端事实。
- 权限点经 sy-standards 检索后落库,禁止编造编码;角色沿用 D19(admin/operator/viewer)。
- 行级数据范围若本模块需要,单独再确认;不默认复制平台 RLS 到外部源库。
- 分析完成并用户确认前不编码;不自动 commit/push。
## Recommended Next Step
用户答复阻塞问题后:写 `requirement.md` → module/workflow 轻量检查 → `implementation-plan.md`(含原型 HTML 独立切片/门禁)→ `context-pack.md`。之后停在分析→编码门禁。
## Suggested Prompt For Next Step
确认阶段边界、首版驱动集合、凭证存放与引用提示深度后,冻结 M03 需求并给出实现切片(DB 优先,前端前先做 HTML 原型)。
@@ -0,0 +1,37 @@
# M03 数据源 · 静态 HTML 原型(S4)
**状态:此原型尚未获批用于 Vue 实现。** 未经维护者确认信息架构与各状态前,不得据此编写 Vue 页面。
## 如何打开
直接用浏览器打开本目录的 `index.html`(双击即可)。单文件,无构建、无 CDN、无网络请求。
## 用途
让维护者确认「数据源」页面的信息架构、角色差异和各状态,之后再用 Vue 3 + Element Plus 实现。视觉按 Element Plus 能还原的克制后台风格设计,采用项目 token(主色 `#5e6ad2`、圆角 8px、基础字号 13.5px)。
## 控件说明
顶部黄色虚线条「原型切换」不属于未来产品,只用于评审。
- **角色**:管理者 / 处理者 / 查看者。
- 只有管理者能进入数据源界面,可以使用新建、保存、停用、测试。
- 处理者和查看者进入后只看到「无法进入数据源」,看不到列表和表单。
- **画面**(仅管理者):
- 空列表:说明还没有数据源,并提供「新建」。
- 列表:名称、引擎、主机、端口、库名、用户名、状态、最近测试、操作;不显示密码或密文。
- 新建:名称、用途说明、引擎(仅 PostgreSQL / MySQL / SQL Server)、主机、端口、库名、用户名、密码。没有「只读意图」。密码框可在输入后点击「查看」。
- 编辑:密码框用固定长度星号占位,不是已保存的密码;聚焦后清空,留空保存则不修改。含连接测试区与引用区。
- **开发注意**:
- 密码框用 Element Plus 的 `el-input`(`type="password"`、`show-password`),不要照着原型自绘。
- 列表页的「新建」放在表格上方。详情页的「返回列表」、保存、测试、停用放在页脚并居中;页脚不在纵向滚动区域内。表格行内操作留在该行。约定见 `docs/current/frontend-ui.md`。
- 测试中 / 测试成功 / 认证失败 / 超时 / 不可达 / 服务端拒绝:结果面板不显示密码。「服务端拒绝」示例为库不存在,不是密码错误。
- 已停用:该行保留在列表,状态「已停用」,「测试」置灰并说明「停用后不能测试」。
- 空引用:「引用」区显示「尚无引用」及空列表,不虚构场景或查询。
- **点「测试」后模拟结果**:选择点击「测试」后(先显示测试中约 1.4 秒)进入哪种结果。
- 列表和编辑页中的「测试」「保存」「停用」只切换本页状态,页面顶部有「原型本地模拟」提示。
## 约束
- 所有数据均为虚构,主机使用保留后缀 `.example.test`;不含真实口令、`.env.local` 中的主机或任何 API 调用。
- 只为信息架构评审;停用后的「启用」、列表分页/筛选、引用的具体内容等未在需求中确认,原型未做。
@@ -0,0 +1,457 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watchman M03 数据源 · 静态原型(S4)</title>
<style>
:root {
--primary: #5e6ad2;
--primary-soft: #eef0fb;
--text: #1f2328;
--text-2: #59636e;
--muted: #8b949e;
--surface: #ffffff;
--soft: #f6f8fa;
--border: #d0d7de;
--border-2: #eaeef2;
--ok: #1a7f37;
--ok-bg: #e9f6ec;
--warn: #9a6700;
--warn-bg: #fff8e1;
--err: #cf222e;
--err-bg: #fdecee;
--radius: 8px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
button, input, select, textarea { font: inherit; color: inherit; }
/* ---- prototype toolbar (not part of product) ---- */
.proto {
background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px;
display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: center; font-size: 12.5px;
}
.proto-title { font-weight: 600; color: #7a5b00; }
.proto-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.proto-group > .lbl { color: var(--text-2); margin-right: 2px; }
.proto-btn {
border: 1px solid var(--border); background: var(--surface); border-radius: 6px;
padding: 2px 9px; cursor: pointer; font-size: 12.5px;
}
.proto-btn:hover { border-color: var(--primary); color: var(--primary); }
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
.proto-note { flex-basis: 100%; color: #7a5b00; }
.proto select { border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; background: #fff; font-size: 12.5px; }
/* ---- shell ---- */
.shell { display: flex; height: calc(100vh - var(--proto-h, 96px)); min-height: 520px; }
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; }
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; letter-spacing: .3px; }
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.nav-item.off { color: var(--muted); }
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: space-between; padding: 0 20px; }
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2);
display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
.list-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
.crumb { color: var(--text-2); }
.crumb b { color: var(--text); font-weight: 600; }
.who { color: var(--text-2); display: flex; align-items: center; gap: 8px; }
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; background: var(--primary-soft); color: var(--primary); }
.content { flex: 1; overflow: auto; padding: 20px; }
.local-banner { background: var(--primary-soft); border: 1px solid #d5d9f5; color: #3f49a8; border-radius: var(--radius);
padding: 7px 12px; margin-bottom: 14px; font-size: 12.5px; }
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
.btn:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); }
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
.btn.primary:hover:not(:disabled) { background: #4f5bc4; color: #fff; }
.btn.danger { color: var(--err); }
.btn.danger:hover:not(:disabled) { border-color: var(--err); color: var(--err); }
.btn.sm { padding: 1px 8px; font-size: 12.5px; }
.btn:disabled { color: var(--muted); background: var(--soft); cursor: not-allowed; }
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
.btn.link.danger { color: var(--err); }
.btn.link:disabled { color: var(--muted); background: none; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); white-space: nowrap; }
td { padding: 10px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
tr.hl td { background: #fafbff; }
tr.off td { color: var(--muted); }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12.5px; }
.table-wrap { overflow-x: auto; border: 1px solid var(--border-2); border-radius: var(--radius); background: var(--surface); }
.table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 16px; }
.ops { white-space: nowrap; }
.ops-why { display: block; color: var(--muted); font-size: 12px; padding: 0 6px; }
.status { display: inline-flex; align-items: center; gap: 6px; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); }
.status.off .dot { background: var(--muted); }
.last-ok { color: var(--ok); } .last-bad { color: var(--err); } .last-none { color: var(--muted); }
.empty { text-align: center; padding: 56px 20px; background: var(--surface); border: 1px dashed var(--border); border-radius: var(--radius); }
.empty h3 { margin: 0 0 6px; font-size: 15px; }
.empty p { margin: 0 0 14px; color: var(--text-2); }
.empty.sm { padding: 22px 20px; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 24px; max-width: 760px; }
.field { display: flex; flex-direction: column; gap: 4px; }
.field.full { grid-column: 1 / -1; }
.field label { color: var(--text-2); font-size: 12.5px; }
.field input[type=text], .field input[type=password], .field input[type=number], .field select, .field textarea {
border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: var(--surface); width: 100%; outline: none; }
.field input:focus, .field select:focus, .field textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-soft); }
.field input:disabled, .field select:disabled, .field textarea:disabled { background: var(--soft); color: var(--text-2); cursor: not-allowed; }
.pwd { display: flex; gap: 8px; align-items: center; }
.pwd input { flex: 1; }
.hint { color: var(--muted); font-size: 12px; }
.drop-later { color: #7a5b00; }
.form-actions { margin-top: 18px; display: flex; gap: 10px; align-items: center; }
.check { display: flex; align-items: center; gap: 8px; }
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); }
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
.result .r-title { font-weight: 600; margin-bottom: 2px; }
.result .r-body { font-size: 13px; }
.result .r-meta { margin-top: 6px; font-size: 12px; opacity: .85; }
.result.ok { background: var(--ok-bg); border-color: #b7e0c2; color: #145c2a; }
.result.bad { background: var(--err-bg); border-color: #f4b8be; color: #8e1a23; }
.result.pend { background: var(--primary-soft); border-color: #d5d9f5; color: #3f49a8; }
.result.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid #c3c8f0; border-top-color: var(--primary); border-radius: 50%; animation: sp .8s linear infinite; vertical-align: -2px; margin-right: 6px; }
@keyframes sp { to { transform: rotate(360deg); } }
.refs.focus { outline: 2px solid var(--primary-soft); border-color: var(--primary); }
.kv { display: grid; grid-template-columns: 96px 1fr; gap: 4px 12px; font-size: 13px; }
.kv dt { color: var(--muted); } .kv dd { margin: 0; }
</style>
</head>
<body>
<div class="proto" id="proto">
<span class="proto-title">原型切换</span>
<div class="proto-group"><span class="lbl">角色</span><span id="p-roles"></span></div>
<div class="proto-group"><span class="lbl">画面</span><span id="p-screens"></span></div>
<div class="proto-group"><span class="lbl">点「测试」后模拟结果</span><select id="p-sim"></select></div>
<div class="proto-note">此条仅用于评审,不属于未来产品。所有数据均为虚构,页面不发送任何网络请求,不含真实密码或地址。正式版本进行删除</div>
</div>
<div class="shell" id="shell">
<aside class="side">
<div class="brand">Watchman</div>
<div class="nav-item cur" id="nav-ds">数据源</div>
</aside>
<div class="main">
<header class="top">
<div class="crumb" id="crumb">Watchman / <b>数据源</b></div>
<div class="who">当前角色 <span class="tag" id="who-role"></span></div>
</header>
<main class="content" id="view"></main>
<div class="pagefoot" id="pagefoot" hidden></div>
</div>
</div>
<script>
(function () {
'use strict';
var ROLES = { admin: '管理者', handler: '处理者', viewer: '查看者' };
var SCREENS = [
['empty', '空列表'], ['list', '列表'], ['create', '新建'], ['edit', '编辑'],
['testing', '测试中'], ['ok', '测试成功'], ['auth', '认证失败'], ['timeout', '超时'],
['unreachable', '不可达'], ['rejected', '服务端拒绝'], ['disabled', '已停用'], ['noref', '空引用']
];
var SIM = [['ok', '成功'], ['auth', '认证失败'], ['timeout', '超时'], ['unreachable', '不可达'], ['rejected', '服务端拒绝']];
var PORT = { PostgreSQL: 5432, MySQL: 3306, 'SQL Server': 1433 };
// All sample data below is fictional. Hosts use the reserved ".example.test" suffix.
var ROWS = [
{ id: 1, name: '产线工艺库', engine: 'PostgreSQL', host: 'db.example.test', port: 5432, db: 'process_demo', user: 'readonly_demo', on: true, last: ['ok', '2026-11-17 09:12 成功'], desc: '示例:工艺参数只读库(虚构)' },
{ id: 2, name: '设备台账库', engine: 'MySQL', host: 'mysql.example.test', port: 3306, db: 'asset_demo', user: 'readonly_demo', on: true, last: ['bad', '2026-11-16 17:40 认证失败'], desc: '示例:设备台账(虚构)' },
{ id: 3, name: '质检结果库', engine: 'SQL Server', host: 'mssql.example.test', port: 1433, db: 'quality_demo', user: 'readonly_demo', on: true, last: ['none', '尚未测试'], desc: '示例:质检结果(虚构)' },
{ id: 4, name: '历史归档库', engine: 'PostgreSQL', host: 'archive.example.test', port: 5432, db: 'archive_demo', user: 'readonly_demo', on: false, last: ['ok', '2026-11-10 14:03 成功'], desc: '示例:已停用的归档库(虚构)' }
];
var state = { role: 'admin', screen: 'list', sim: 'ok', timer: null, testTarget: 1, from: 'list' };
function $(id) { return document.getElementById(id); }
function isAdmin() { return state.role === 'admin'; }
function row(id) { for (var i = 0; i < ROWS.length; i++) if (ROWS[i].id === id) return ROWS[i]; return ROWS[0]; }
function later(text) { return text + ' <span class="drop-later">正式版本进行删除</span>'; }
/* ---------- prototype toolbar ---------- */
function renderProto() {
var r = '', s = '', k;
for (k in ROLES) r += '<button class="proto-btn' + (state.role === k ? ' on' : '') + '" data-role="' + k + '">' + ROLES[k] + '</button> ';
$('p-roles').innerHTML = r;
SCREENS.forEach(function (x) {
s += '<button class="proto-btn' + (state.screen === x[0] ? ' on' : '') + '" data-screen="' + x[0] + '">' + x[1] + '</button> ';
});
$('p-screens').innerHTML = s;
var o = '';
SIM.forEach(function (x) { o += '<option value="' + x[0] + '"' + (state.sim === x[0] ? ' selected' : '') + '>' + x[1] + '</option>'; });
$('p-sim').innerHTML = o;
$('who-role').textContent = ROLES[state.role];
$('nav-ds').className = 'nav-item' + (isAdmin() ? ' cur' : ' off');
}
/* ---------- pieces ---------- */
function banner() {
return '<div class="local-banner">' + later('原型本地模拟:此页面不会向任何服务发送请求,「测试」「保存」「停用」只会切换本页的演示状态。') + '</div>';
}
function statusCell(r) {
return r.on
? '<span class="status"><span class="dot"></span>启用</span>'
: '<span class="status off"><span class="dot"></span>已停用</span>';
}
function lastCell(r) {
var cls = r.last[0] === 'ok' ? 'last-ok' : r.last[0] === 'bad' ? 'last-bad' : 'last-none';
return '<span class="' + cls + '">' + r.last[1] + '</span>';
}
function opsCell(r) {
var h = '<button class="btn link" data-go="edit" data-id="' + r.id + '">编辑</button>';
if (r.on) h += '<button class="btn link" data-test="' + r.id + '">测试</button>';
else h += '<button class="btn link" disabled title="停用后不能测试">测试</button><span class="ops-why">停用后不能测试</span>';
if (r.on) h += '<button class="btn link danger" data-disable="' + r.id + '">停用</button>';
return h;
}
function listTable(rows, hlId) {
var h = '<div class="table-wrap"><table><thead><tr>' +
'<th>名称</th><th>引擎</th><th>主机</th><th>端口</th><th>库名</th><th>用户名</th><th>状态</th><th>最近测试</th><th>操作</th>' +
'</tr></thead><tbody>';
rows.forEach(function (r) {
h += '<tr class="' + (r.on ? '' : 'off ') + (r.id === hlId ? 'hl' : '') + '">' +
'<td>' + r.name + '</td><td>' + r.engine + '</td><td class="mono">' + r.host + '</td><td class="mono">' + r.port +
'</td><td class="mono">' + r.db + '</td><td class="mono">' + r.user + '</td><td>' + statusCell(r) + '</td><td>' + lastCell(r) +
'</td><td class="ops">' + opsCell(r) + '</td></tr>';
});
return h + '</tbody></table></div>';
}
function setCrumb(leaf) {
var html = 'Watchman / <b>数据源</b>';
if (leaf) html += ' / <b>' + leaf + '</b>';
$('crumb').innerHTML = html;
}
function setFoot(actions) {
var foot = $('pagefoot');
foot.hidden = !actions;
foot.innerHTML = actions || '';
}
/* ---------- screens ---------- */
function vEmpty() {
setCrumb('');
setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-go="create">新建</button></div>' +
'<div class="empty"><h3>还没有数据源</h3><p>管理者可以新建第一个数据源。</p></div>';
}
function vList() {
setCrumb('');
setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-go="create">新建</button></div>' + listTable(ROWS.slice(0, 3), 0);
}
function vDisabled() {
setCrumb('');
setFoot('');
return banner() + '<div class="list-actions"><button class="btn primary" data-go="create">新建</button></div>' + listTable(ROWS, 4) +
'<p class="hint" style="margin-top:10px">' + later('已停用的行保持可见,状态为「已停用」,「测试」按钮置灰,原因:停用后不能测试。') + '</p>';
}
function passwordField(mode) {
var edit = mode === 'edit';
return '<div class="field"><label>密码</label><div class="pwd">' +
'<input type="password" id="f-password" autocomplete="new-password" data-mode="' + mode + '"' +
(edit ? ' data-mask="1" value="••••••••"' : ' value="" placeholder="请输入密码"') + '>' +
'<button type="button" class="btn sm" id="f-reveal" data-reveal>查看</button></div>' +
'<span class="hint">' + later(edit
? '星号是固定占位,不是已保存的密码。聚焦后自动清空;留空保存则不修改。开发时改用 Element Plus 的 el-input,type=password 且 show-password,不要自绘这个框。'
: '开发时改用 Element Plus 的 el-input,type=password 且 show-password,不要自绘这个框。') + '</span></div>';
}
function fieldsHtml(r, mode) {
var v = r || { name: '', desc: '', engine: 'PostgreSQL', host: '', port: 5432, db: '', user: '' };
var eng = '';
['PostgreSQL', 'MySQL', 'SQL Server'].forEach(function (e) { eng += '<option' + (v.engine === e ? ' selected' : '') + '>' + e + '</option>'; });
return '<div class="form-grid">' +
'<div class="field"><label>名称</label><input type="text" value="' + v.name + '"></div>' +
'<div class="field"><label>引擎</label><select id="f-engine">' + eng + '</select>' +
'<span class="hint">' + later('非数据库来源暂不可用。') + '</span></div>' +
'<div class="field full"><label>用途说明</label><textarea rows="2">' + (v.desc || '') + '</textarea></div>' +
'<div class="field"><label>主机</label><input type="text" placeholder="例如 db.example.test" value="' + v.host + '"></div>' +
'<div class="field"><label>端口</label><input type="number" id="f-port" value="' + v.port + '"></div>' +
'<div class="field"><label>库名</label><input type="text" value="' + v.db + '"></div>' +
'<div class="field"><label>用户名</label><input type="text" value="' + v.user + '"></div>' +
passwordField(mode) +
'</div>';
}
function pageActions(r, mode) {
var h = '';
if (isAdmin()) h += '<button class="btn primary" data-save>保存</button>';
if (mode === 'edit') {
if (r.on) h += '<button class="btn" data-test="' + r.id + '">测试</button>';
else h += '<button class="btn" disabled title="停用后不能测试">测试</button>';
if (r.on) h += '<button class="btn danger" data-disable="' + r.id + '">停用</button>';
}
h += '<button class="btn" data-go="list">返回列表</button>';
return h;
}
function vCreate() {
setCrumb('新建');
setFoot(pageActions(null, 'create'));
return banner() + '<div class="card"><h3>连接信息</h3>' + fieldsHtml(null, 'create') + '</div>';
}
var RESULTS = {
ok: ['ok', '测试成功', '已连接并完成只读探测。', '耗时示意 0.4 秒(虚构)'],
auth: ['bad', '认证失败', '服务端不接受该用户名或密码。请核对用户名,并在密码框重新输入后保存。', '这是认证问题,不代表主机或库名有误'],
timeout: ['warn', '超时', '在允许的时间内没有收到服务端响应。可稍后重试,或检查网络与防火墙。', '超时不等于密码错误'],
unreachable: ['bad', '不可达', '无法与目标主机和端口建立连接。请核对主机、端口,以及网络是否放行。', '尚未到达认证步骤'],
rejected: ['bad', '服务端拒绝', '服务端已响应但拒绝了请求,例如库名不存在。这不是密码错误。', '请核对库名或该账号的访问授权']
};
function resultPanel(kind, r) {
if (kind === 'testing') {
return '<div class="result pend"><div class="r-title"><span class="spin"></span>测试中</div>' +
'<div class="r-body">' + later('正在测试「' + r.name + '」(本地模拟,未发出任何请求)…') + '</div></div>';
}
var x = RESULTS[kind];
if (!x) return '';
var cls = x[0];
return '<div class="result ' + cls + '"><div class="r-title">' + x[1] + '</div><div class="r-body">' + x[2] + '</div>' +
'<div class="r-meta">' + later(x[3] + ' · 目标 ' + r.host + ':' + r.port + ' / ' + r.db + ' · 结果面板不显示密码') + '</div></div>';
}
function refsSection(focus) {
return '<div class="card refs' + (focus ? ' focus' : '') + '"><h3>引用</h3>' +
'<div class="empty sm"><p style="margin:0">尚无引用</p></div>' +
'<p class="hint" style="margin:8px 0 0">' + later('此处将列出使用该数据源的对象;当前列表为空。') + '</p></div>';
}
function vEdit(kind) {
var r = row(state.testTarget);
setCrumb('详情');
setFoot(pageActions(r, 'edit'));
var h = banner();
if (!r.on) h += '<div class="note warn" style="margin-bottom:14px">该数据源已停用。停用后不能测试。</div>';
h += '<div class="card"><h3>连接信息</h3>' + fieldsHtml(r, 'edit') + '</div>';
h += '<div class="card"><h3>连接测试</h3>';
if (kind === 'testing' || RESULTS[kind]) h += resultPanel(kind, r);
else h += '<div class="note">' + later('尚未测试。点击上方「测试」可演示测试中与结果(本地模拟)。') + '</div>';
h += '</div>';
h += refsSection(kind === 'noref');
return h;
}
function vDenied() {
setCrumb('');
setFoot('');
return banner() + '<div class="empty"><h3>无法进入数据源</h3><p>只有管理者可以进入数据源界面。</p></div>';
}
function render() {
renderProto();
var s = state.screen, h;
if (!isAdmin()) h = vDenied();
else if (s === 'empty') h = vEmpty();
else if (s === 'list') h = vList();
else if (s === 'create') h = vCreate();
else if (s === 'edit') h = vEdit(null);
else if (s === 'disabled') h = vDisabled();
else if (s === 'noref') h = vEdit('noref');
else h = vEdit(s); // testing / ok / auth / timeout / unreachable / rejected
$('view').innerHTML = h;
sizeShell();
}
function sizeShell() {
var h = $('proto').offsetHeight;
$('shell').style.setProperty('height', 'calc(100vh - ' + h + 'px)');
}
function go(screen) {
if (state.timer) { clearTimeout(state.timer); state.timer = null; }
state.screen = screen;
render();
}
function runTest(id) {
state.testTarget = id;
go('testing');
state.timer = setTimeout(function () { state.timer = null; state.screen = state.sim; render(); }, 1400);
}
/* ---------- events ---------- */
document.addEventListener('click', function (e) {
var t = e.target.closest('button');
if (!t || t.disabled) return;
if (t.hasAttribute('data-reveal')) {
var input = $('f-password');
if (!input || input.getAttribute('data-mask') === '1' || input.value === '') return;
var show = input.type === 'password';
input.type = show ? 'text' : 'password';
t.textContent = show ? '隐藏' : '查看';
return;
}
if (t.hasAttribute('data-role')) { state.role = t.getAttribute('data-role'); render(); return; }
if (t.hasAttribute('data-screen')) { go(t.getAttribute('data-screen')); return; }
if (t.hasAttribute('data-go')) {
if (t.hasAttribute('data-id')) state.testTarget = +t.getAttribute('data-id');
go(t.getAttribute('data-go'));
return;
}
if (t.hasAttribute('data-test')) { runTest(+t.getAttribute('data-test')); return; }
if (t.hasAttribute('data-disable')) { go('disabled'); return; }
if (t.hasAttribute('data-save')) { go('list'); return; }
});
document.addEventListener('focusin', function (e) {
if (e.target.id !== 'f-password' || e.target.getAttribute('data-mask') !== '1') return;
e.target.value = '';
e.target.removeAttribute('data-mask');
});
document.addEventListener('focusout', function (e) {
if (e.target.id !== 'f-password' || e.target.getAttribute('data-mode') !== 'edit') return;
if (e.target.value !== '') return;
e.target.value = '••••••••';
e.target.type = 'password';
e.target.setAttribute('data-mask', '1');
var btn = $('f-reveal');
if (btn) { btn.textContent = '查看'; }
});
document.addEventListener('input', function (e) {
if (e.target.id !== 'f-password') return;
if (e.target.value === '') {
e.target.type = 'password';
var btn = $('f-reveal');
if (btn) btn.textContent = '查看';
}
});
document.addEventListener('change', function (e) {
if (e.target.id === 'p-sim') { state.sim = e.target.value; return; }
if (e.target.id === 'f-engine' && state.screen === 'create') {
$('f-port').value = PORT[e.target.value];
}
});
window.addEventListener('resize', sizeShell);
render();
})();
</script>
</body>
</html>
@@ -0,0 +1,175 @@
# M03 数据源配置(第一阶段)Requirement
## Goal
维护者能登记数据库数据源、编辑、停用与启用、在保存前/后做连接测试,并在详情中配置该源的熔断参数。平台对已保存且已启用的源做可开关的 Cron 周期巡检;连接失败(含认证失败)按该源配置累计,触发熔断后在冷却期内禁止测试与业务使用,冷却结束自动熄闸。凭证只在平台库中以密文保存。API 与日志不回显明文。
## Background
- 模块计划见 `docs/tasks/INDEX.md` 的 M03,需求见交接稿 A-01。
- M01、M02 已 DONE_LOCAL。平台库是 PostgreSQL,带租户 RLS。授权来自 Casdoor 角色(D19);数据源接口仅 `watchman-admin`。
- D21:第一阶段数据库来源 + 加密凭证 + 空引用 + 原型门禁。D22:列表/页脚按钮规则与密码框组件。
- 2026-11-18 用户实测反馈并确认增补:草稿测试、可逆启用、表单校验、Cron 巡检、与停用解耦的熔断、详情页配置熔断参数(D23)。
## In Scope
- 数据源元数据:名称、用途说明、启用状态、来源种类、数据库引擎、主机、端口、库名、最近一次连接测试结果与失败类别、熔断运行态与每源熔断参数。
- 来源种类可扩展。本阶段只接受并实现 `database`。引擎:`postgresql`、`mysql`、`sqlserver`。
- 新建、编辑、停用、启用、按租户列表与详情。停用后仍可查询与再启用;不可测试、不进周期巡检;后续场景配置不可选(本阶段提供稳定“可选源”筛选语义/接口约定)。
- 连接测试:
- **已保存测试**:测持久化配置,更新 `last_test_*`;失败计入该源熔断账。
- **草稿测试**:用当前表单探测,不写 `last_test_*`,不计入熔断;新建密码必填,编辑密码留空则用已存密文。
- 测试类别:成功、认证失败、超时、网络不可达、服务端拒绝。响应与日志不含口令、连接串、密文或驱动原始错误。
- 凭证:平台库加密字段。更新时整段替换。读取接口只返回“是否已配置”。
- 引用查询接口返回空列表和稳定占位结构。
- 周期巡检:后端配置开关 + Cron 表达式;只扫描已启用且未熔断的源;失败更新 `last_test_*`、写审计,本轮不发企微(C2=A)。
- 熔断:与 `enabled` 解耦;参数在数据源详情可配;默认窗口 5 分钟/阈值 3/冷却 10 分钟。
- 单次探测:可配超时;可重试类别仅 timeout/unreachable;auth_failed/rejected 不重试。
- 权限:仅 admin 的数据源读写与测试。
- 控制台页面:上述流程(原型已确认)。
## Out Of Scope
- 查询定义、SQL 执行、采集、映射、报警、企微真实发送、场景页本身。
- HTTP、消息队列、视频等非数据库来源的可用实现。
- 外部密钥管理系统、凭证轮换后台、配置导出、物理删除。
- 证明源库账号只读。
- 真实 MES 或生产库联调。
- 熔断自动改启用状态;半开试探探测(采用纯时间熄闸)。
## Current Behavior
S1–S5 已交付:可登记三种引擎、保存后按 id 测试、仅停用不可启用、无草稿测、无周期巡检、无熔断。本增补在其上扩展。
## Required Behavior
- 有权限用户可登记数据源;保存前可用草稿测试;保存后可用已保存测试。
- 列表和详情看不到口令。编辑留空表示不改凭证。
- 停用/启用可逆。停用:不可测、不巡检、不可被后续场景选中。启用不要求先测通。
- 详情可查看并保存该源熔断三参数;缺省为 300s/3/600s。
- 已保存源上的探测失败与(预留)业务查源失败写入统一失败账;窗口内达阈值则开闸;开闸期内禁止测试、业务使用与巡检;冷却结束自动熄闸。
- 草稿测试不入熔断账。
- 非 database/未知引擎创建失败。引用空数组。跨租户不可见。无会话 41000;非 admin 42000。
## User Flow
1. 管理者打开数据源列表。
2. 新建:填连接信息 → 可先草稿测试 → 保存(默认可为启用)。
3. 详情:编辑连接、配置熔断参数、已保存测试、停用或启用。
4. 停用后仍可打开详情再启用;测试按钮不可用。
5. 熔断中:界面标明状态与预计恢复时间;测试与业务使用被拒。
6. 引用区仍为空状态。
## Business Rules
- 租户内名称唯一。停用不是删除;本阶段无物理删除。
- 连接测试失败不自动改 `enabled`。
- 熔断不改 `enabled`;停用也不清熔断账(再启用后若仍在开闸冷却内则仍不可用,直到熄闸)。
- 周期巡检与手工/草稿测试均不得增加业务报警错误次数。
- 只读意图本阶段不展示、不据此拒绝连接(若列仍在库中可保留但不进表单)。
## Circuit Breaker Rules
| 项 | 口径 |
|---|---|
| 与停用 | 完全解耦。停用是人工配置;熔断是运行态 |
| 记失败 | 已保存源的探测(手工/巡检)及后续业务查源连接失败;类别含 success 以外全部(含 auth_failed) |
| 记成功 | 未开闸时成功清零窗口计数;已开闸时成功不提前熄闸 |
| 开闸 | 滑动窗口内失败次数 ≥ 阈值 |
| 开闸期 | 拒绝已保存测试、拒绝业务取连接、跳过巡检 |
| 熄闸 | `circuit_opened_at + cooldown` 到期后自动 `closed`,不先探测 |
| 参数 | 每源可配:`failure_window_seconds`、`failure_threshold`、`open_cooldown_seconds`;默认 300、3、600;在详情页编辑并随更新保存 |
| 草稿 | 无 id 或不落库的草稿测试不记账 |
后续查询模块必须通过本模块提供的 `assert_usable`/失败记账入口,不得绕过熔断。
## Healthcheck Rules
- 配置(环境/后端配置文件,非每源):`enabled` 布尔 + Cron 表达式。
- `enabled=false` 或非法 Cron:不注册/任务直接返回。
- 候选:`enabled=true` 且电路未开闸。
- 失败:更新 `last_test_*`、写审计;本轮不发企微。
## Data Rules
- 租户由服务端注入,RLS 不变。
- 口令密文列;密钥只来自环境变量。
- 主机、端口、库名、用户名、熔断参数与熔断状态可回显;口令/连接串/密文不可。
- 测试结果:类别、时间、短原因(无驱动原文)。
## API Contract
- 列表、详情、创建、更新、停用、**启用**。
- 已保存测试:`POST .../{id}/test`。
- 草稿测试:`POST .../test-draft`(body 为连接字段;编辑时可带 id 仅用于取已存密码,仍不写 last_test、不记账——若带 id 仅解密密码,熔断仍不记账)。
- 详情/列表返回:`enabled`、`circuit_state`(`closed`|`open`)、`circuit_opened_at`、`circuit_open_until`(可计算)、三熔断参数、`last_test_*`。
- 更新可改三熔断参数(校验:窗口/冷却为正整数合理上限;阈值为 ≥1 整数)。
- 开闸或停用时测试返回明确业务错误(非笼统 500)。
- 可选源列表或列表过滤约定:仅 `enabled && circuit closed`(或提供 `usable=true` 查询参数)供后续场景使用。
- 信封与错误码段不变。
## UI Requirements
- 沿用已确认原型与 D22;本增补在正式页上加:
- 新建/编辑:**测试连接**在保存前可用(草稿);保存后仍可已保存测试。
- 停用后显示**启用**。
- 详情:熔断三参数表单项;熔断中提示。
- 表单校验:名称/引擎/host(仅必填)/port(1–65535)/database/username 必填;密码新建必填、编辑可空;熔断参数数值校验。
- 仅 admin 进入。
## Compatibility Requirements
- 不改 M02 登录与既有三权限点含义。
- 不改审计表既有列语义;数据源变更与巡检失败可写审计,payload 无凭证。
- 查询/场景模块稍后接入 usable 与记账,不在本阶段实现场景页。
## Error Handling
- 类别分离;探测超时有上限。
- 日志脱敏。
- 前端按统一错误信封展示。
## Permissions And Security
| 权限点 | 动作 | 角色 |
|---|---|---|
| `perm:data:emp:watchman.datasource.read` | 列表与详情 | 仅 admin |
| `perm:data:emp:watchman.datasource.write` | 新建、编辑、停用、启用 | 仅 admin |
| `perm:data:emp:watchman.datasource.test` | 已保存测试与草稿测试 | 仅 admin |
- 后端强制。已保存测试只能打已保存主机端口;草稿测试使用提交的主机端口(仅 admin)。
## Assumptions
- 巡检 Cron 使用与平台一致的解析库(成熟库,不手写)。
- 单次探测超时/最大尝试次数可用全局配置;熔断三参数每源配置。
- 业务查源尚未实现时,提供可单测的记账与 `assert_usable` API,供后续模块调用。
## Risks
- 草稿测试扩大出站面:靠 admin 权限约束,无网段白名单。
- 纯时间熄闸后第一次业务调用可能再次失败并迅速重新开闸——可接受。
- Cron 与 Celery Beat 适配需薄封装,避免第二套调度器。
## Acceptance Criteria
1. admin 能创建三种引擎;错误引擎与非 database 被拒。
2. 列表/详情/审计/日志无口令与密文;编辑留空不改口令。
3. 三种隔离库:已保存测试成功;错口令 auth_failed;库不存在 rejected;超时类别正确。
4. 新建/编辑保存前草稿测试可用且不写 last_test、不入熔断账。
5. 仅 admin;非 admin 42000;无会话 41000。
6. 停用后不可测、不巡检;可再启用(无需先测通)。
7. 详情可改熔断三参数并持久化;默认 300/3/600。
8. 窗口内达阈值开闸:测试与 usable 被拒;冷却后自动熄闸。
9. 配置关闭或无效 Cron 时巡检不跑;开启后按 Cron 只扫启用且未熔断源;失败有 last_test 与审计,无企微。
10. 引用仍为空列表。
11. 控制台覆盖启用、草稿测、校验、熔断展示与参数编辑。
## Deferred Questions
- 源库只读探测;内网白名单;非数据库来源字段;引用项字段;企微通知巡检失败。
## Source Notes
- 用户 2026-11-17:D21;2026-11-18:D22;2026-11-18 实测六条反馈;Q1=A、Q2=A、Q3 host 仅必填、Q4 Cron、Q5 熔断与停用解耦且认证计入、Q6 全进本轮;C1 默认参数、C2=A、熔断参数在详情配置 → D23。
- 规范:`standards://api/api-envelope?version=1.1.0`、`standards://api/error-handling?version=1.1.1`、`standards://api/permission-nodes?version=1.0.0`、`standards://security/red-line?version=1.1.0`。
@@ -0,0 +1,11 @@
# M03 S1 Review
- Slice: S1 数据源模型、迁移与凭证密文
- Implementer: Claude Sonnet,[实现 S1](583d05d2-27ef-4bc9-9e40-cfe28866705e)
- Independent review: Gemini,[审查 S1](70b146aa-3bea-43f9-a853-6c5d2fa25448)
- Extra read-only pass: GPT,[代码审查](ef0eaf81-b33c-4e2e-907f-047854093f95)
- Verdict: PASS_WITH_WARNINGS
- Validation reported by implementer: `uv run pytest` in `services/watchman` → 84 passed, exit 0. Alembic upgrade, downgrade to `20261117_0003`, upgrade again, exit 0. Local database left at `20261117_0004`.
- Blockers: none
- Follow-up, not an S1 defect to fix now: `updated_at` does not auto-refresh on UPDATE. Handle in S3 when rows are edited. Do not rewrite the applied migration for this.
- Residual: empty plaintext is not rejected yet (S3). Do not `model_dump()` Settings. Key loss is unrecoverable. Cross-tenant UPDATE/DELETE is covered by the same RLS policy but not a separate test.
@@ -0,0 +1,11 @@
# M03 S2 Review
- Slice: S2 三种数据库连接测试
- Implementer: Claude Sonnet,[实现 S2](577db49f-ed40-4c5e-b538-1916ce389b51)
- First review: GPT,[审查 S2](82d483cc-7add-471f-941d-5991cf93e535),BLOCKED。缺库被标成认证失败。
- Repair and re-review: Gemini,[复审 S2](930b0683-26b7-4ae7-8d0e-63eccfb00f53),PASS_WITH_WARNINGS。
- Validation: `uv run pytest` in `services/watchman` → 134 passed, exit 0. Live wrong password is `auth_failed`. Live missing database is `rejected` for PostgreSQL, MySQL, and SQL Server.
- Blocker closed: `auth_failed` requires positive evidence. Other server rejections use `rejected`.
- Warning carried forward: S3 must expose `rejected` in the API. `updated_at` still does not auto-refresh.
- SQL Server test container: `watchman-dev-sqlserver`, published on 127.0.0.1 only.
- Fernet key and test passwords are in gitignored `.env.local` only.
@@ -0,0 +1,10 @@
# M03 S3 Review
- Slice: S3 数据源 API、权限与空引用
- Implementer: Claude Sonnet,[实现 S3](072e1cac-4f7f-409a-9672-6bd23edaa96c)
- First review: GPT,[审查 S3](b8304f13-65cd-4017-9723-95b0d016babb),BLOCKED。连接参数变更后仍保留旧测试结果。
- Repair and re-review: Gemini,[复审 S3](89b2c565-07c1-421b-b6c4-7f1925a39d6f),PASS_WITH_WARNINGS。
- Validation: `uv run pytest` in `services/watchman` → 175 passed, exit 0. Reviewer re-ran the suite.
- Closed: PATCH clears `last_test_*` when engine, host, port, database, username, or password actually changes.
- Not adopted: `@app_gate` / `permission_nodes` registry / `perm_diff`. This repository has no gateway scanner. Nodes stay as constants, the same way M02 did, and D19 does not add a second registry.
- Residual: a slow probe can write its result back if the row was edited or disabled during the probe. `password: null` keeps the stored secret.
@@ -0,0 +1,8 @@
# M03 S4 Prototype Check
- Slice: S4 static HTML prototype
- Implementer: Claude Sonnet, [原型](6ef382ff-78dc-4167-ae66-a8c204db0d61)
- Files: `.task/2026-11-17/m03-datasource/prototype/index.html` and `README.md`
- Scope: no Vue, no `web/`, no API
- Checked in a browser: list, viewer role (no save/test/disable), rejected state with an empty password field and the note that a missing database is not an authentication failure. The references section is on the detail screen as “尚无引用”.
- Not approved for Vue. S5 stays blocked until the user confirms this prototype.
@@ -0,0 +1,8 @@
# M03 S5 Review
- Slice: console datasource pages, and datasource API checks limited to watchman-admin
- Implementer: Claude Sonnet, [实现 S5](d8c04bbe-bdfe-4d10-b004-2406034e1841)
- Review: GPT, [审查 S5](0413a65a-8cd3-445b-9f42-9e5e2fffab72), PASS_WITH_WARNINGS
- Warning closed after review: principal.py docstrings now say admin-only, matching the checks
- Validation reported: backend pytest 182 passed; console unit 24; typecheck; build; Playwright 17 passed, including 10 datasource specs. APIs in Playwright were mocked.
- Not DONE_LOCAL. The user has not accepted the finished module.
@@ -0,0 +1,30 @@
# Review Result
## Recommendation
PASS_WITH_WARNINGS
## Review Scope
- Task: `2026-11-17/m03-datasource`, slice `S6`
- Routing: Tier L, `gateClass: high-risk`, `risk_score: 4`; two-stage bounded re-review performed after the P1 repair.
- Reviewed the caller-provided S6 repair paths and bounded task artifacts. No forbidden `web/**` or `services/watchman/src/watchman/jobs/**` changes were reviewed.
- Supplied validation evidence: `cd services/watchman && uv run pytest` reported `232 passed, 1 warning`. This reviewer did not rerun the suite.
## Stage 1: Boundary And Compliance Review
- **P1 fixed:** `get_datasource()` now calls `_close_if_cooled_down()` before serialization, and the detail route commits the normalized state. `list_datasources()` likewise normalizes every returned row and its route commits.
- The new regression tests advance past cooldown, verify detail and ordinary-list responses return `closed` with cleared open timestamps, and verify the persisted row is closed.
- The repair remains within allowed S6 service, route, and test scope. No scheduler, frontend, credential, or other forbidden-scope behavior was introduced.
## Stage 2: Implementation Quality Review
- No blocking implementation or regression finding was identified in the bounded re-review.
## Warning
- `services/watchman/src/watchman/services/datasources.py:116-122`: `to_public()` still says an elapsed `circuit_open_until` means “the next usability check closes it.” Detail and list reads now also normalize before serialization, so this wording is stale. It does not affect runtime behavior.
## Residual Risk
- Circuit state changes on reads are intentionally persisted by the detail/list route commits. The supplied full-suite result covers the repaired paths; migration-head verification was not supplied for this re-review.
@@ -0,0 +1,36 @@
# Review Result
## Slice
S7 — Cron periodic datasource health checks
Gate class: `high-risk`; risk score: `4`
## Stage 1: Boundary And Compliance Review
No blocking findings.
- The implementation stays within the approved S7 areas: Celery Beat registration, Cron validation, health-check orchestration, settings, dependency lock, environment example, and focused tests. No `web/**` or migration file was modified for this slice.
- It uses the existing Celery Beat application and `croniter`; no second scheduler was introduced.
- Disabled, invalid-Cron, disabled-source, and open-circuit paths all no-op or skip before probing. The per-source probe rechecks usability, preserving the S6 circuit boundary.
- Failed probes update persisted test outcomes and write a credential-free audit payload. No WeCom send path is present.
- Cron validation explicitly rejects simultaneous restricted DOM/DOW fields, avoiding the known croniter (OR) versus Celery (AND) semantic mismatch. A direct Celery compatibility check also confirmed that unsupported weekday `7` is rejected rather than silently scheduled.
## Stage 2: Implementation Quality Review
No blocking findings.
- The candidate IDs are collected before network I/O and each source is committed independently, avoiding a long database transaction during probes and preventing one source failure from aborting the batch.
- Tests cover switch and invalid-Cron no-ops, enabled-and-closed selection, mid-loop disable, outcome accounting, audit secret hygiene, circuit opening, Beat registration, configuration parsing, and task execution.
## Validation Evidence
- Supplied: `cd services/watchman && uv run pytest` — `262 passed`, including 30 new S7 tests.
- Reviewed runtime compatibility: Celery rejects an unsupported `day_of_week=7`; the adapter treats it as invalid and does not register a schedule.
## Residual Risk
This remains production scheduling/configuration work (`risk_score: 4`). The test evidence is mock-probe based, so an environment-level Beat/worker/RabbitMQ execution check is still appropriate during later integration validation.
## Recommendation
PASS
@@ -0,0 +1,35 @@
# Review Result
## Slice
S8 — 控制台增补(启用/草稿测/校验/熔断配置)
## Scope And Boundary Review
- 已审阅 `web/apps/console/src/datasources/**`、四个 locale 文件、`web/apps/console/e2e/datasources.spec.ts` 和 M03 UI 证据目录;未发现 `services/watchman/**` 的 S8 改动。
- 草稿测试走 `POST /datasources/test-draft`,保存前可用;已保存测试与草稿测试分离。
- 停用/开闸状态禁用已保存测试;停用记录可直接启用,且启用不要求预先测试。
- 详情页展示并提交三个熔断参数;host 仅做非空校验,端口和熔断参数做整数范围校验。
- 编辑密码使用固定掩码,空密码不会出现在更新或草稿测试 payload;页面不使用 localStorage 保存凭证。
- 四种 locale 的 datasource 键由单测比较,未发现键集遗漏。
## Findings
### Warning — S6 契约联调尚无独立证据
`pnpm test:e2e` 的 25 个用例均使用 mocked APIs。实现与当前 S6 路由的 `test-draft`、`enable`、熔断字段和错误详情契约一致,但实施计划要求与 S6 API 联调;现有证据不能证明真实前后端组合运行。模块整体验收前应补充一次针对运行中 S6 API 的最小端到端验证,或明确记录该环境不可用。
## Validation Evidence
- Reported: `pnpm test:unit` — 7 files / 39 tests passed.
- Reported: `pnpm typecheck` — exit 0.
- Reported: `pnpm test:e2e` — 25/25 passed with mocked APIs.
- Reviewer check: scoped frontend diff passes `git diff --check`.
## Knowledge Sync
无需在本切片额外更新知识文档。熔断/usable 边界的稳定性文档同步仍按实施计划在模块验收阶段处理。
## Recommendation
PASS_WITH_WARNINGS
@@ -0,0 +1,23 @@
{
"taskId": "2026-11-17/m03-datasource",
"module": "M03",
"title": "数据源配置模块",
"type": "feature",
"tier": "L",
"phase": "done",
"allowedToCode": false,
"currentSlice": "done",
"proposedNextSlice": null,
"lastGate": "done-local",
"status": "DONE_LOCAL",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"finalApprovalRequired": true
},
"notes": [
"User confirmed finish: commit, push, DONE_LOCAL",
"UI polish after S8 acceptance included"
],
"updatedAt": "2026-11-18T04:50:00Z"
}
+10 -4
View File
@@ -1,10 +1,16 @@
{
"taskId": "2026-11-17/m02-auth",
"taskId": "2026-11-17/m03-datasource",
"type": "feature",
"phase": "done",
"allowedToCode": false,
"currentSlice": "done",
"lastGate": "user-confirm-done-local",
"nextCommand": "wait for the next module",
"updatedAt": "2026-11-17T11:40:00Z"
"lastGate": "done-local",
"nextCommand": "none — M03 DONE_LOCAL; pick next module from docs/tasks/INDEX.md",
"gatePolicy": {
"selected": "autonomous",
"effective": "autonomous",
"finalApprovalRequired": true,
"allowTaskOverride": true
},
"updatedAt": "2026-11-18T04:50:00Z"
}