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

+30
View File
@@ -37,3 +37,33 @@ CASDOOR_AUDIENCE=CHANGE-ME
HXOPS_SSO_ISSUER=https://CHANGE-ME
HXOPS_SSO_AUDIENCE=CHANGE-ME
HXOPS_SSO_PUBLIC_KEY=CHANGE-ME
# Datasource password encryption (Fernet urlsafe base64 key). Generate your own; losing it makes stored passwords unrecoverable.
WATCHMAN_DATASOURCE_KEY=CHANGE-ME
# Datasource probe: per-attempt timeout (seconds, default 5) and attempt cap (1-2, default 2; only timeout/unreachable retry).
WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS=5
WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS=2
# Scheduled datasource health check (Celery Beat). Off by default. The cron is 5-field Unix
# (minute hour day-of-month month day-of-week), digits with * / , - only; setting both
# day-of-month and day-of-week is rejected. An invalid value means no schedule.
WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED=false
WATCHMAN_DATASOURCE_HEALTHCHECK_CRON="*/5 * * * *"
# M03 S2: isolated probe-test sources (engine connector tests). Real values in .env.local only.
WATCHMAN_TEST_PG_HOST=127.0.0.1
WATCHMAN_TEST_PG_PORT=5432
WATCHMAN_TEST_PG_USER=CHANGE-ME
WATCHMAN_TEST_PG_PASSWORD=CHANGE-ME
WATCHMAN_TEST_PG_DATABASE=CHANGE-ME
WATCHMAN_TEST_MYSQL_HOST=127.0.0.1
WATCHMAN_TEST_MYSQL_PORT=3306
WATCHMAN_TEST_MYSQL_USER=CHANGE-ME
WATCHMAN_TEST_MYSQL_PASSWORD=CHANGE-ME
WATCHMAN_TEST_MYSQL_DATABASE=CHANGE-ME
# SQL Server runs in compose profile source-sqlserver (127.0.0.1 only); user is sa.
# The password must satisfy SQL Server complexity rules.
WATCHMAN_TEST_SQLSERVER_HOST=127.0.0.1
WATCHMAN_TEST_SQLSERVER_PORT=1433
WATCHMAN_TEST_SQLSERVER_USER=sa
WATCHMAN_TEST_SQLSERVER_PASSWORD=CHANGE-ME
WATCHMAN_TEST_SQLSERVER_DATABASE=CHANGE-ME
@@ -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"
}
+24
View File
@@ -39,6 +39,29 @@ services:
volumes:
- watchman_dev_postgres:/var/lib/postgresql/data
# M03 S2: probe target for SQL Server connection tests only. Not the platform database.
# Starts only with --profile source-sqlserver. SA password and host port come from
# .env.local; there is deliberately no default password here.
sqlserver:
profiles: ["source-sqlserver"]
image: mcr.microsoft.com/mssql/server:2022-latest
container_name: watchman-dev-sqlserver
environment:
ACCEPT_EULA: "Y"
MSSQL_SA_PASSWORD: ${WATCHMAN_TEST_SQLSERVER_PASSWORD:?set WATCHMAN_TEST_SQLSERVER_PASSWORD in .env.local}
ports:
- "127.0.0.1:${WATCHMAN_TEST_SQLSERVER_PORT:-1433}:1433"
healthcheck:
test:
- "CMD-SHELL"
- "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -Q \"SELECT 1\" -b -o /dev/null"
interval: 5s
timeout: 5s
retries: 24
start_period: 20s
volumes:
- watchman_dev_sqlserver:/var/opt/mssql
api:
profiles: ["app"]
build:
@@ -114,3 +137,4 @@ services:
volumes:
watchman_dev_rabbitmq:
watchman_dev_postgres:
watchman_dev_sqlserver:
+25
View File
@@ -0,0 +1,25 @@
# 前端界面约定
写控制台页面时遵守。组件库是 Element Plus。
## 按钮位置
列表页的页面按钮放在表格上方,例如「新建」。不要放进页脚。表格每一行自己的操作留在该行。
详情页和表单页的页面按钮放在页脚,并居中。包括返回、保存、草稿测试、已保存测试、停用、启用。页脚在纵向滚动区域之外,正文滚动时按钮保持可见,不跟着滚走,也不要散落在表单中间或标题栏里。
列表页导航为「Watchman / 数据源」。详情页为「Watchman / 数据源 / 详情」,新建页为「Watchman / 数据源 / 新建」。不要在导航下方再放一块重复的页面标题。
## 数据源(D23)
- 新建/编辑页脚只有「测试连接」(草稿测);不更新最近测试记录。列表「测试」进入详情后测已保存连接。
- 列表「测试」在停用或熔断中禁用(不展示「停用后不能测试」说明文字)。
- 停用后可「启用」,不必先测通。
- host 校验只做必填。熔断三参数仅详情可编辑;开闸时展示恢复时间。
- 周期巡检开关与 Cron 只在后端配置,控制台不提供巡检配置页。
## 密码框
使用 Element Plus 的 `el-input`,`type="password"`,并打开 `show-password`。不要自绘密码框和查看按钮。
已保存的密码不回填。编辑时可以用固定长度占位,聚焦后清空;留空表示不修改。
+3
View File
@@ -26,6 +26,9 @@
| D18 | Compose 容器内 `API_HOST=0.0.0.0` 仅开发且必须行内标注;宿主发布端口仍绑 `127.0.0.1` | 2026-11-17 独立 review 顺带项 |
| D19 | M02 授权:Casdoor 分配 `watchman-admin`、`watchman-operator`、`watchman-viewer`。Watchman 只校验,不建角色表和授权管理页。登录用自有页面,后端向新建的 Watchman Application 校验密码,并接收 HXOPS 短时断言。不复用 HXOPS client。行级数据范围留到后续业务模块 | 2026-11-17 用户确认按此冻结 |
| D20 | 地址上的访问令牌只要在这套 Casdoor 上仍然有效就接受,不另核签发应用。没有 Watchman 角色的用户仍然进不了业务界面。密码登录继续使用 Watchman Application | 2026-11-17 用户在 O11 中选择接受该实例上任意仍然有效的访问令牌 |
| D21 | M03 第一阶段:交付后端和确认后的界面。只实现数据库来源,引擎为 PostgreSQL、MySQL、SQL Server,其他种类只留扩展位。凭证用平台库加密字段,API 不回显,日志脱敏。引用用空列表。允许为测试创建隔离库表;SQL Server 可用本机 Docker。正式 Vue 之前必须先确认 HTML 原型。源库口令不写入仓库 | 2026-11-17 用户确认阶段边界与四项口径 |
| D22 | 列表页的页面按钮放在表格上方。详情页和表单页的页面按钮放在页脚并居中,且位于纵向滚动区域之外,滚动正文时保持可见。表格行内操作留在该行。密码框使用 Element Plus `el-input` 的 `type="password"` 与 `show-password`,不自绘密码框 | 2026-11-18 用户确认:页脚只用于详情页,按钮居中 |
| D23 | M03 增补:保存前草稿连接测试(不写 last_test、不入熔断账);停用可逆启用且无需先测通;host 校验仅必填;周期巡检由后端配置开关 + Cron,失败只更新 last_test 与审计、本轮不发企微;熔断与停用解耦,认证失败计入,默认窗口 300s/阈值 3/冷却 600s,开闸期禁测试与业务使用,到期自动熄闸;熔断三参数在数据源详情配置;本轮全进 M03 | 2026-11-18 用户确认 Q1–Q6、C1、C2=A 及详情配置熔断 |
## 冻结前/相关模块实现前必须确认
Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+8 -8
View File
@@ -2,12 +2,11 @@
## 当前快照
- 当前阶段:M02 统一登录与权限已 DONE_LOCAL。
- 当前大任务:无进行中的模块。上一完成:M02。再之前:M01 基础框架(DONE_LOCAL)。
- 用户授权:地址携带 Casdoor 访问令牌。前端只提交该令牌,后端调用 Casdoor 校验。D20 接受该实例上任意仍然有效的访问令牌。用户已确认提交并完成 M02。
- Git:M02 候选 `f8e1c77` 已推送。计划表在 `8b65c4a`。当前 `master` 与 origin 一致。
- 下一步:等用户指定下一个模块。不自动开工。
- RabbitMQ 容器可能仍在运行:`watchman-dev-rabbitmq`。
- 当前阶段:M03 数据源配置 **DONE_LOCAL**(用户确认联调收尾并授权提交推送)。
- 当前大任务:无进行中模块大任务。上一完成:M03。再上一:M02。
- 用户授权:D21、D22、D23。数据源接口仅 `watchman-admin`。
- Git:本轮提交并推送后绑定候选 commit(见下方状态表)。
- 下一步:进入下一模块(按 `docs/tasks/INDEX.md`)前先读本台账与交接。
## 大任务状态
@@ -15,8 +14,9 @@
|---|---|---|---|---|---|---|
| M01 基础框架 | DONE_LOCAL | 实现 Composer;审查/复审异系列 | `8fb16f4` | PASS_WITH_WARNINGS(必改已关) | pytest 23;unit 8;e2e 3 | 已完成 |
| M02 统一登录与权限 | DONE_LOCAL | 主 Agent;复审 claude-opus | `f8e1c77` | 复审阻塞已由 D20 关闭 | pytest 58;unit 10;登录 Playwright 4 | 已完成 |
| M03 数据源配置 | DONE_LOCAL | 实现 Claude Sonnet;审查 GPT | 见本轮 push commit | S1–S8 片审通过;用户联调收尾 | pytest 262+;console unit 39;datasources e2e 18;证据 `docs/evidence/M03/ui/` | 已完成 |
## 当前阻塞
- O08:跨系列子 Agent 授权仍开放(本轮已实际用过异系列审查)。
- O01–O07:业务口径,不阻塞后续文档/基础模块开工;相关切片仍须确认。
- O08:跨系列子 Agent 授权仍开放。
- O01–O07:业务口径,不阻塞已完成的 M01–M03。
+18
View File
@@ -167,6 +167,24 @@ Copy this block for each major project area:
- Validation:
- 改动平台代码前能指出对应的 `standards://` 篇目和版本
### 控制台界面
- Areas: 管理台页面、页脚按钮、密码输入
- Tags: frontend, element-plus, detail, password
- Docs:
- Current: `docs/current/frontend-ui.md`
- Rules:
- `AGENTS.md` 项目本地段
- Read When:
- 写或改 `web/apps/console` 的页面,尤其是详情、表单和密码框
- Boundaries:
- 列表页按钮放在表格上方
- 详情页按钮放在页脚并居中,不放进纵向滚动区域
- 表格行内操作留在该行
- 密码框用 Element Plus 自带的 `show-password`
- Validation:
- 列表按钮在表格上方;详情页滚动时页脚按钮仍居中停在底部
## Mudball-Friendly Documentation Guidance
For codebases with unclear boundaries or mixed responsibilities:
+31
View File
@@ -0,0 +1,31 @@
# M03 数据源配置模块
一个会话聚焦本模块。第一阶段范围见 `.task/2026-11-17/m03-datasource/requirement.md`(含 D23)。
## 内部步骤(主 Agent 根据现有代码安排)
- [x] 明确边界、依赖和复用方案。
- [x] S1 数据模型、迁移与凭证密文。评审 PASS_WITH_WARNINGS。
- [x] S2 三种数据库驱动与连接测试。复审 PASS_WITH_WARNINGS。
- [x] S3 API、权限与空引用。复审 PASS_WITH_WARNINGS。
- [x] S4 HTML 原型已确认。
- [x] S5 前端与接口联调。审查 PASS_WITH_WARNINGS。
- [x] D23 需求冻结与 S6–S8 切片。
- [x] S6 启用、草稿测试、熔断模型与 usable。审查 PASS_WITH_WARNINGS。迁移 `20261118_0005`。
- [x] S7 Cron 周期巡检。审查 PASS。
- [x] S8 控制台:启用、草稿测、校验、详情熔断配置。审查 PASS_WITH_WARNINGS。
- [x] 验收期 UI 微调(列表文案/操作列宽/去掉详情「测试已保存连接」)。
- [x] 用户确认联调收尾;主 Agent 标 DONE_LOCAL 并提交推送。
## 目标与边界
- 已确认:D14、D19、D21、D22、D23。
- 已交付:三种引擎登记;草稿/列表已保存测;可逆启用;每源熔断;Cron 巡检(配置开关);凭证不回显;引用为空。
- 明确不做:查询执行;企微真发;场景页;非数据库可用接入;熔断自动停用。
## 证据与结论
- 任务产物:`.task/2026-11-17/m03-datasource/`
- 审查:`reviews/review-s1.md` … `review-s8.md`
- UI 证据:`docs/evidence/M03/ui/`
- 最终状态:**DONE_LOCAL**(2026-11-18)
+1 -1
View File
@@ -12,7 +12,7 @@ from sqlalchemy import engine_from_config, pool
from watchman.core.config import get_settings
from watchman.models.base import Base
from watchman.models import AuthSession, AuditEvent, RunRecord # noqa: F401
from watchman.models import AuthSession, AuditEvent, DataSource, RunRecord # noqa: F401
config = context.config
if config.config_file_name is not None:
@@ -0,0 +1,68 @@
"""Create data_sources with forced RLS.
Revision ID: 20261117_0004
Revises: 20261117_0003
Create Date: 2026-11-17
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "20261117_0004"
down_revision: Union[str, None] = "20261117_0003"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
TABLE = "data_sources"
def upgrade() -> None:
op.create_table(
TABLE,
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("kind", sa.String(length=32), nullable=False),
sa.Column("engine", sa.String(length=32), nullable=False),
sa.Column("host", sa.String(length=255), nullable=False),
sa.Column("port", sa.Integer(), nullable=False),
sa.Column("database_name", sa.String(length=128), nullable=False),
sa.Column("username", sa.String(length=128), nullable=False),
sa.Column("secret_ciphertext", sa.Text(), nullable=False),
sa.Column("read_only_intent", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("last_test_category", sa.String(length=32), nullable=True),
sa.Column("last_test_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_test_message", sa.String(length=255), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.UniqueConstraint("tenant_id", "name", name="uq_data_sources_tenant_name"),
sa.CheckConstraint("kind = 'database'", name="ck_data_sources_kind"),
sa.CheckConstraint("engine IN ('postgresql','mysql','sqlserver')", name="ck_data_sources_engine"),
sa.CheckConstraint("port BETWEEN 1 AND 65535", name="ck_data_sources_port"),
)
op.execute(f"ALTER TABLE {TABLE} ENABLE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {TABLE} FORCE ROW LEVEL SECURITY")
op.execute(
f"""
CREATE POLICY tenant_isolation ON {TABLE}
FOR ALL
TO {APP_ROLE}
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
"""
)
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {TABLE} TO {APP_ROLE}")
def downgrade() -> None:
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {TABLE}")
op.drop_table(TABLE)
@@ -0,0 +1,103 @@
"""Add per-datasource circuit breaker configuration and runtime state.
Revision ID: 20261118_0005
Revises: 20261117_0004
Create Date: 2026-11-18
The circuit is independent of data_sources.enabled: an open circuit never flips enabled.
Existing rows get the defaults (window 300s, threshold 3, cooldown 600s, closed).
The table keeps its RLS policy and grants from revision 20261117_0004.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20261118_0005"
down_revision: Union[str, None] = "20261117_0004"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
TABLE = "data_sources"
_CHECKS = (
("ck_data_sources_circuit_window", "circuit_failure_window_seconds BETWEEN 1 AND 86400"),
("ck_data_sources_circuit_threshold", "circuit_failure_threshold BETWEEN 1 AND 100"),
("ck_data_sources_circuit_cooldown", "circuit_open_cooldown_seconds BETWEEN 1 AND 86400"),
("ck_data_sources_circuit_state", "circuit_state IN ('closed','open')"),
("ck_data_sources_circuit_count", "circuit_failure_count >= 0"),
)
def upgrade() -> None:
op.add_column(
TABLE,
sa.Column(
"circuit_failure_window_seconds",
sa.Integer(),
server_default=sa.text("300"),
nullable=False,
),
)
op.add_column(
TABLE,
sa.Column(
"circuit_failure_threshold",
sa.Integer(),
server_default=sa.text("3"),
nullable=False,
),
)
op.add_column(
TABLE,
sa.Column(
"circuit_open_cooldown_seconds",
sa.Integer(),
server_default=sa.text("600"),
nullable=False,
),
)
op.add_column(
TABLE,
sa.Column(
"circuit_state",
sa.String(length=16),
server_default=sa.text("'closed'"),
nullable=False,
),
)
op.add_column(
TABLE, sa.Column("circuit_opened_at", sa.DateTime(timezone=True), nullable=True)
)
op.add_column(
TABLE,
sa.Column(
"circuit_failure_count",
sa.Integer(),
server_default=sa.text("0"),
nullable=False,
),
)
op.add_column(
TABLE, sa.Column("circuit_window_started_at", sa.DateTime(timezone=True), nullable=True)
)
for name, condition in _CHECKS:
op.create_check_constraint(name, TABLE, condition)
def downgrade() -> None:
for name, _condition in reversed(_CHECKS):
op.drop_constraint(name, TABLE, type_="check")
for column in (
"circuit_window_started_at",
"circuit_failure_count",
"circuit_opened_at",
"circuit_state",
"circuit_open_cooldown_seconds",
"circuit_failure_threshold",
"circuit_failure_window_seconds",
):
op.drop_column(TABLE, column)
+4
View File
@@ -14,6 +14,10 @@ dependencies = [
"celery>=5.4,<6",
"python-dotenv>=1.0,<2",
"pyjwt[crypto]>=2.10,<3",
"cryptography>=43,<51",
"pymysql>=1.1,<2",
"pymssql>=2.3,<3",
"croniter>=3,<7",
]
[build-system]
@@ -0,0 +1,129 @@
"""Create the isolated probe-test databases for PostgreSQL, MySQL and SQL Server.
Why: connector tests must never touch the platform database, so each engine gets its own
empty database plus one harmless table. This is the only place CREATE DATABASE runs; the
probe function itself stays read-only.
Boundary: creates a database only if missing and never drops anything. Prints engine names
and ok/failed words only -- no hosts, users, passwords or driver error text.
Depends on .env.local through watchman.core.config.merge_layered_env.
Usage (from services/watchman): uv run python scripts/setup_probe_test_sources.py [engine ...]
"""
from __future__ import annotations
import re
import sys
import psycopg
import pymssql
import pymysql
from psycopg import sql
from watchman.core.config import merge_layered_env
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_TIMEOUT = 10
def _env(prefix: str) -> dict[str, str]:
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
missing = [f"{prefix}_{k}" for k in keys if not env.get(f"{prefix}_{k}")]
if missing:
raise RuntimeError("missing env: " + ", ".join(missing))
values = {k.lower(): env[f"{prefix}_{k}"] for k in keys}
if not _IDENT.match(values["database"]):
# Identifier is interpolated into CREATE DATABASE; keep it to a safe charset.
raise RuntimeError(f"{prefix}_DATABASE is not a plain identifier")
return values
def _setup_postgresql() -> None:
cfg = _env("WATCHMAN_TEST_PG")
common = dict(
host=cfg["host"],
port=int(cfg["port"]),
user=cfg["user"],
password=cfg["password"],
connect_timeout=_TIMEOUT,
autocommit=True,
)
with psycopg.connect(dbname="postgres", **common) as conn:
exists = conn.execute(
"SELECT 1 FROM pg_database WHERE datname = %s", (cfg["database"],)
).fetchone()
if not exists:
conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(cfg["database"])))
with psycopg.connect(dbname=cfg["database"], **common) as conn:
conn.execute("CREATE TABLE IF NOT EXISTS probe (id int)")
def _setup_mysql() -> None:
cfg = _env("WATCHMAN_TEST_MYSQL")
conn = pymysql.connect(
host=cfg["host"],
port=int(cfg["port"]),
user=cfg["user"],
password=cfg["password"],
connect_timeout=_TIMEOUT,
autocommit=True,
)
try:
with conn.cursor() as cur:
cur.execute(f"CREATE DATABASE IF NOT EXISTS `{cfg['database']}`")
cur.execute(f"CREATE TABLE IF NOT EXISTS `{cfg['database']}`.probe (id int)")
finally:
conn.close()
def _setup_sqlserver() -> None:
cfg = _env("WATCHMAN_TEST_SQLSERVER")
conn = pymssql.connect(
server=cfg["host"],
port=cfg["port"],
user=cfg["user"],
password=cfg["password"],
database="master",
login_timeout=_TIMEOUT,
timeout=60,
autocommit=True,
)
try:
cur = conn.cursor()
db = cfg["database"]
cur.execute(f"IF DB_ID(N'{db}') IS NULL CREATE DATABASE [{db}]")
cur.execute(
f"USE [{db}]; IF OBJECT_ID(N'dbo.probe', N'U') IS NULL CREATE TABLE dbo.probe (id int)"
)
finally:
conn.close()
_ENGINES = {
"postgresql": _setup_postgresql,
"mysql": _setup_mysql,
"sqlserver": _setup_sqlserver,
}
def main(argv: list[str]) -> int:
wanted = argv or list(_ENGINES)
unknown = [e for e in wanted if e not in _ENGINES]
if unknown:
print("unknown engine name(s); choose from: " + ", ".join(_ENGINES))
return 2
failed = 0
for name in wanted:
try:
_ENGINES[name]()
print(f"{name}: ok")
except Exception as exc: # noqa: BLE001
# Class name only: driver messages can embed user, host or password hints.
print(f"{name}: failed ({type(exc).__name__})")
failed += 1
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+2 -1
View File
@@ -43,7 +43,8 @@ def main() -> None:
if role == "beat":
from watchman.jobs.celery_app import celery_app
# M01 registers no business schedules; beat must still be startable.
# beat_schedule comes from celery_app (empty unless the datasource health check is
# enabled with a valid cron), so beat stays startable with no business schedule.
celery_app.start(argv=["beat", "--loglevel=INFO"])
return
raise SystemExit(f"unknown role: {role}")
+10 -2
View File
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from watchman.api.routes import auth, health, platform
from watchman.api.routes import auth, datasources, health, platform
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
from watchman.core.errors import AppError, ValidationError
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
@@ -77,6 +77,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
app.include_router(health.router)
app.include_router(auth.router)
app.include_router(platform.router)
app.include_router(datasources.router)
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
@@ -97,7 +98,14 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
status_code=400,
code=40000,
message="Validation failed",
details={"errors": exc.errors()},
# GUARD: drop "input" and "ctx"; they can echo a submitted password or hold
# non-JSON exception objects. Location, type and message are enough.
details={
"errors": [
{key: err[key] for key in ("type", "loc", "msg") if key in err}
for err in exc.errors()
]
},
)
@app.exception_handler(Exception)
@@ -0,0 +1,244 @@
"""Datasource configuration routes under /datasources.
Why: lets the console list, save, disable and test source-database connections.
Boundary: request models forbid unknown fields, so a caller can never send tenant_id, a
connection URL or a test target; responses never carry a password or ciphertext. Business
rules live in watchman.services.datasources.
Depends on the datasource service and the three datasource permission dependencies.
"""
from __future__ import annotations
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
from sqlalchemy.orm import Session
from watchman.auth.principal import (
require_datasource_reader,
require_datasource_tester,
require_datasource_writer,
)
from watchman.core.db import get_db_session
from watchman.core.response import success_body
from watchman.datasources import ProbeCategory
from watchman.services import datasources as service
router = APIRouter(prefix="/datasources", tags=["datasources"])
Name = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=128)]
Text128 = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=128)]
# D23: host is only required (non-blank, bounded); no format check, the probe decides.
Host = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=255)]
Port = Annotated[int, Field(ge=1, le=65535)]
# Not stripped: a password may legitimately start or end with a space.
PasswordText = Annotated[str, StringConstraints(max_length=1024)]
CircuitSeconds = Annotated[int, Field(ge=1, le=86400, strict=True)]
CircuitThreshold = Annotated[int, Field(ge=1, le=100, strict=True)]
class DatasourceCreate(BaseModel):
"""Create body. Unknown fields such as tenant_id are rejected with 40000."""
model_config = ConfigDict(extra="forbid")
name: Name
description: Annotated[str, StringConstraints(max_length=2000)] | None = None
kind: str = "database"
engine: str
host: Host
port: Port
database_name: Text128
username: Text128
password: PasswordText = Field(repr=False)
read_only_intent: bool = True
class DatasourceUpdate(BaseModel):
"""Partial update body. Omit password, or send it blank, to keep the stored one."""
model_config = ConfigDict(extra="forbid")
name: Name | None = None
description: Annotated[str, StringConstraints(max_length=2000)] | None = None
kind: str | None = None
engine: str | None = None
host: Host | None = None
port: Port | None = None
database_name: Text128 | None = None
username: Text128 | None = None
password: PasswordText | None = Field(default=None, repr=False)
read_only_intent: bool | None = None
circuit_failure_window_seconds: CircuitSeconds | None = None
circuit_failure_threshold: CircuitThreshold | None = None
circuit_open_cooldown_seconds: CircuitSeconds | None = None
class DraftTestBody(BaseModel):
"""Form values to probe without saving. Blank password + datasource_id = stored secret."""
model_config = ConfigDict(extra="forbid")
datasource_id: str | None = None
kind: str = "database"
engine: str
host: Host
port: Port
database_name: Text128
username: Text128
password: PasswordText | None = Field(default=None, repr=False)
class EmptyBody(BaseModel):
"""Optional body for disable and test; it has no fields, so no target can be sent."""
model_config = ConfigDict(extra="forbid")
def _ok(request: Request, data: Any) -> JSONResponse:
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
@router.get("")
def list_datasources(
request: Request,
usable: bool = False,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""List the server tenant's datasources; usable=true keeps enabled, circuit-closed ones."""
rows = service.list_datasources(session, usable_only=usable)
data = {"items": [service.to_public(row) for row in rows]}
# An elapsed cooldown closes the circuit while listing; persist that.
session.commit()
return _ok(request, data)
@router.post("/test-draft")
def test_draft_connection(
request: Request,
body: DraftTestBody,
_: None = Depends(require_datasource_tester),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Probe the form's values. Writes no last_test and does not count toward the circuit.
Declared before the /{datasource_id} routes so the static path always wins.
"""
fields = body.model_dump(exclude={"datasource_id"})
result = service.run_draft_connection_test(session, fields, datasource_id=body.datasource_id)
session.commit()
if result.category is not ProbeCategory.SUCCESS:
raise service.ConnectionTestFailedError(result)
return _ok(request, {"category": result.category.value, "message": result.message})
@router.post("")
def create_datasource(
request: Request,
body: DatasourceCreate,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Create a datasource; the password is encrypted and never returned."""
row = service.create_datasource(session, **body.model_dump())
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.get("/{datasource_id}")
def get_datasource(
request: Request,
datasource_id: str,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return one datasource."""
data = service.to_public(service.get_datasource(session, datasource_id))
# An elapsed cooldown closes the circuit while reading; persist that.
session.commit()
return _ok(request, data)
@router.patch("/{datasource_id}")
def update_datasource(
request: Request,
datasource_id: str,
body: DatasourceUpdate,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Update the fields that were sent; a blank or missing password keeps the old one."""
row = service.update_datasource(session, datasource_id, body.model_dump(exclude_unset=True))
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{datasource_id}/disable")
def disable_datasource(
request: Request,
datasource_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Disable a datasource. The record stays readable and is never deleted."""
row = service.disable_datasource(session, datasource_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{datasource_id}/enable")
def enable_datasource(
request: Request,
datasource_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_datasource_writer),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Enable a datasource again. Does not touch the circuit state."""
row = service.enable_datasource(session, datasource_id)
data = service.to_public(row)
session.commit()
return _ok(request, data)
@router.post("/{datasource_id}/test")
def test_datasource_connection(
request: Request,
datasource_id: str,
body: EmptyBody | None = None,
_: None = Depends(require_datasource_tester),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Probe the saved connection. The body cannot name a different target."""
row, result = service.run_connection_test(session, datasource_id)
# The outcome is stored for success and failure alike, so commit before replying.
session.commit()
if result.category is not ProbeCategory.SUCCESS:
raise service.ConnectionTestFailedError(result)
return _ok(
request,
{
"id": str(row.id),
"category": result.category.value,
"message": result.message,
"last_test_at": row.last_test_at.isoformat() if row.last_test_at else None,
},
)
@router.get("/{datasource_id}/references")
def get_datasource_references(
request: Request,
datasource_id: str,
_: None = Depends(require_datasource_reader),
session: Session = Depends(get_db_session),
) -> JSONResponse:
"""Return what references this datasource. Nothing does yet, so items is empty."""
return _ok(request, service.list_references(session, datasource_id))
+29 -2
View File
@@ -1,6 +1,7 @@
"""Role checks for the three Watchman permission nodes.
"""Role checks for the Watchman permission nodes.
Decides enter, platform write, and object read from Casdoor role names.
Decides enter, platform write, object read, and the three datasource nodes (read,
write, test) from Casdoor role names.
Depends on semantic errors only; it does not call Casdoor or open a session.
"""
@@ -12,6 +13,10 @@ ENTER_NODE = "perm:app:emp:watchman.enter"
PLATFORM_WRITE_NODE = "perm:data:emp:watchman.platform.write"
OBJECT_READ_NODE = "perm:data:emp:watchman.object.read"
DATASOURCE_READ_NODE = "perm:data:emp:watchman.datasource.read"
DATASOURCE_WRITE_NODE = "perm:data:emp:watchman.datasource.write"
DATASOURCE_TEST_NODE = "perm:data:emp:watchman.datasource.test"
ROLE_ADMIN = "watchman-admin"
ROLE_OPERATOR = "watchman-operator"
ROLE_VIEWER = "watchman-viewer"
@@ -38,6 +43,28 @@ def require_platform_write(role_names: list[str]) -> None:
raise ForbiddenError(permission_node=PLATFORM_WRITE_NODE)
def require_datasource_read(role_names: list[str]) -> None:
"""Allow datasource list, detail and references only for watchman-admin.
Operator, viewer, and an empty or unknown role list are denied with the
datasource read node.
"""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=DATASOURCE_READ_NODE)
def require_datasource_write(role_names: list[str]) -> None:
"""Allow datasource create, update and disable only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=DATASOURCE_WRITE_NODE)
def require_datasource_test(role_names: list[str]) -> None:
"""Allow a datasource connection test only for watchman-admin."""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=DATASOURCE_TEST_NODE)
def require_object_access(role_names: list[str], object_id: str) -> None:
"""Reject every object id until a later module grants row access.
@@ -14,7 +14,12 @@ from urllib.parse import quote
from fastapi import Cookie, Depends, Request
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
from watchman.auth.access import require_platform_write
from watchman.auth.access import (
require_datasource_read,
require_datasource_test,
require_datasource_write,
require_platform_write,
)
from watchman.auth.sessions import (
SESSION_COOKIE_NAME,
SessionStore,
@@ -117,3 +122,58 @@ def require_platform_writer(
roles = directory.lookup_roles(login_name=row.login_name)
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
require_platform_write(roles)
def _load_session_roles(
request: Request,
session_token: str | None,
sessions: SessionStore,
directory: RoleDirectory,
) -> list[str]:
"""Return fresh role names for the caller's session, or raise 41000 / 503.
Same session and freshness rules as require_platform_writer: a stale snapshot is
reloaded from Casdoor and, if that fails, the old roles are not used.
"""
token = read_session_token(request, session_token)
if token is None:
raise UnauthorizedError()
now = utc_now()
row = sessions.get(token_hash=hash_cookie_token(token), now=now)
if row is None:
raise UnauthorizedError()
roles = list(row.role_snapshot)
if now - row.role_checked_at >= ROLE_FRESHNESS:
roles = directory.lookup_roles(login_name=row.login_name)
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
return roles
def require_datasource_reader(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject datasource reads unless the session is watchman-admin."""
require_datasource_read(_load_session_roles(request, session_token, sessions, directory))
def require_datasource_writer(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject datasource create, update and disable unless the session is watchman-admin."""
require_datasource_write(_load_session_roles(request, session_token, sessions, directory))
def require_datasource_tester(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject a connection test unless the session is watchman-admin."""
require_datasource_test(_load_session_roles(request, session_token, sessions, directory))
@@ -111,6 +111,37 @@ class Settings(BaseSettings):
hxops_sso_issuer: str = Field(default="", alias="HXOPS_SSO_ISSUER")
hxops_sso_audience: str = Field(default="", alias="HXOPS_SSO_AUDIENCE")
hxops_sso_public_key: str = Field(default="", alias="HXOPS_SSO_PUBLIC_KEY")
# Fernet key for datasource passwords. Deliberately not in REQUIRED_RUNTIME_KEYS:
# only datasource code needs it, so a missing key must not stop unrelated boot.
datasource_key: str = Field(default="", alias="WATCHMAN_DATASOURCE_KEY", repr=False)
# Per-attempt connect timeout and attempt cap for datasource probes. Only timeout and
# unreachable outcomes are retried; the cap keeps a dead source from stalling a request.
datasource_probe_timeout_seconds: float = Field(
default=5.0, gt=0, le=60, alias="WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS"
)
datasource_probe_max_attempts: int = Field(
default=2, ge=1, le=2, alias="WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS"
)
# Scheduled datasource health check (M03 S7). Off by default; the cron string is a
# 5-field Unix expression validated by jobs/ and services/ (invalid means no schedule).
datasource_healthcheck_enabled: bool = Field(
default=False, alias="WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED"
)
datasource_healthcheck_cron: str = Field(
default="", alias="WATCHMAN_DATASOURCE_HEALTHCHECK_CRON"
)
def _env_bool(value: str | None, default: bool = False) -> bool:
"""Parse a boolean env value; unknown text falls back to the (safe) default."""
if value is None or not value.strip():
return default
text = value.strip().lower()
if text in {"1", "true", "yes", "on"}:
return True
if text in {"0", "false", "no", "off"}:
return False
return default
def _settings_from_env_map(env: dict[str, str]) -> Settings:
@@ -141,6 +172,17 @@ def _settings_from_env_map(env: dict[str, str]) -> Settings:
hxops_sso_issuer=env.get("HXOPS_SSO_ISSUER", ""),
hxops_sso_audience=env.get("HXOPS_SSO_AUDIENCE", ""),
hxops_sso_public_key=env.get("HXOPS_SSO_PUBLIC_KEY", ""),
datasource_key=env.get("WATCHMAN_DATASOURCE_KEY", ""),
datasource_probe_timeout_seconds=float(
env.get("WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS", "5") or "5"
),
datasource_probe_max_attempts=int(
env.get("WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS", "2") or "2"
),
datasource_healthcheck_enabled=_env_bool(
env.get("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED")
),
datasource_healthcheck_cron=env.get("WATCHMAN_DATASOURCE_HEALTHCHECK_CRON", "").strip(),
)
@@ -0,0 +1,47 @@
"""Symmetric encryption for datasource passwords stored in platform Postgres.
Boundary: only turns plaintext into an opaque token and back; it never logs, caches or
persists either side. Callers decide when decryption is allowed (connection test only).
Depends on the cryptography Fernet recipe and WATCHMAN_DATASOURCE_KEY from Settings.
"""
from __future__ import annotations
from cryptography.fernet import Fernet, InvalidToken
from watchman.core.config import get_settings
KEY_ENV_NAME = "WATCHMAN_DATASOURCE_KEY"
class SecretKeyError(RuntimeError):
"""The datasource key is missing or malformed. Message never carries key material."""
class SecretDecryptError(RuntimeError):
"""Ciphertext cannot be decrypted with the configured key."""
def _load_cipher() -> Fernet:
raw = get_settings().datasource_key.strip()
if not raw or "CHANGE-ME" in raw:
raise SecretKeyError(f"{KEY_ENV_NAME} is not configured")
try:
return Fernet(raw.encode("ascii"))
except (ValueError, UnicodeEncodeError):
# Do not chain: the original error text may echo part of the key.
raise SecretKeyError(f"{KEY_ENV_NAME} is not a valid Fernet key") from None
def encrypt_secret(plaintext: str) -> str:
"""Encrypt a password into a urlsafe-base64 Fernet token."""
return _load_cipher().encrypt(plaintext.encode("utf-8")).decode("ascii")
def decrypt_secret(ciphertext: str) -> str:
"""Decrypt a token produced by encrypt_secret with the current key."""
cipher = _load_cipher()
try:
return cipher.decrypt(ciphertext.encode("ascii")).decode("utf-8")
except (InvalidToken, ValueError):
raise SecretDecryptError("datasource secret cannot be decrypted with the configured key") from None
@@ -0,0 +1,22 @@
"""Datasource connectors: connectivity probes against external source databases.
Boundary: probing only (SELECT 1 / driver ping, bounded by a connect timeout); no
persistence, no API, no query execution. Callers pass a decrypted password in memory.
Depends on the psycopg, PyMySQL and pymssql drivers.
"""
from watchman.datasources.probe import (
ProbeCategory,
ProbeResult,
ProbeTarget,
UnsupportedDataSourceError,
probe_datasource,
)
__all__ = [
"ProbeCategory",
"ProbeResult",
"ProbeTarget",
"UnsupportedDataSourceError",
"probe_datasource",
]
@@ -0,0 +1,307 @@
"""Connectivity probe for PostgreSQL, MySQL and SQL Server source databases.
Why: users need to know whether a saved datasource works, and why not, without the
platform ever running DDL/DML on a customer database or leaking credentials through
driver error text. Every outcome collapses into five categories with fixed messages.
Boundary: opens one short-lived connection and runs only SELECT 1; it does not decrypt
secrets, persist results, or run user queries. Unknown kind/engine raises before any
socket is opened.
Depends on psycopg, PyMySQL and pymssql; the timeout is the drivers' own connect timeout.
"""
from __future__ import annotations
import logging
import math
import socket
from dataclasses import dataclass, field
from enum import StrEnum
from typing import Callable
import psycopg
import pymssql
import pymysql
logger = logging.getLogger("watchman.datasources.probe")
DEFAULT_TIMEOUT_SECONDS = 5.0
# MySQL: only 1044/1045 (access denied) are positive auth evidence. Other server-side
# errors (<2000, e.g. 1049 unknown database, 1130 host not allowed) are "rejected";
# 2xxx are client/network errors.
_MYSQL_AUTH_CODES = frozenset({1044, 1045})
_MYSQL_SERVER_ERROR_LIMIT = 2000
# Positive auth evidence for PostgreSQL. The Chinese phrase is the server's own message
# when lc_messages is zh_CN; it only survives decoding with a GB-family client_encoding.
_PG_AUTH_KEYWORDS = ("password authentication failed", "authentication failed", "认证失败", "no pg_hba.conf entry")
_PG_MISSING_KEYWORDS = ("does not exist", "不存在")
_REPLACEMENT_CHAR = "\ufffd"
class ProbeCategory(StrEnum):
SUCCESS = "success"
AUTH_FAILED = "auth_failed"
TIMEOUT = "timeout"
UNREACHABLE = "unreachable"
# Server reached and answered, but not with evidence of a credential problem
# (e.g. database missing): never report this as auth_failed.
REJECTED = "rejected"
# Fixed texts: driver messages often embed host, user or parts of the connection string.
_MESSAGES: dict[ProbeCategory, str] = {
ProbeCategory.SUCCESS: "connection succeeded",
ProbeCategory.AUTH_FAILED: "authentication failed",
ProbeCategory.TIMEOUT: "connection timed out",
ProbeCategory.UNREACHABLE: "data source unreachable",
ProbeCategory.REJECTED: "data source rejected the connection",
}
@dataclass(frozen=True)
class ProbeResult:
category: ProbeCategory
message: str
class UnsupportedDataSourceError(ValueError):
"""Kind or engine has no connector. The message is fixed and carries no input values."""
def __init__(self) -> None:
super().__init__("unsupported datasource kind or engine")
@dataclass(frozen=True)
class ProbeTarget:
"""Connection parameters for one probe. The password is excluded from repr."""
engine: str
host: str
port: int
database: str
username: str
password: str = field(repr=False)
kind: str = "database"
def _result(category: ProbeCategory) -> ProbeResult:
return ProbeResult(category=category, message=_MESSAGES[category])
def _whole_seconds(timeout: float) -> int:
# libpq and FreeTDS only take whole seconds; round up so the bound is never exceeded
# in the shorter direction, and never pass 0 (which means "wait forever").
return max(1, math.ceil(timeout))
def _chain_has_timeout(exc: BaseException) -> bool:
"""True if the exception or any chained cause is a socket-level timeout."""
seen: set[int] = set()
current: BaseException | None = exc
while current is not None and id(current) not in seen:
seen.add(id(current))
if isinstance(current, TimeoutError):
return True
current = current.__cause__ or current.__context__
return False
def _tcp_reachability(host: str, port: int, timeout: float) -> str:
"""Return "open", "refused" or "timeout" for a bare TCP connect; sends no payload."""
try:
with socket.create_connection((host, port), timeout=timeout):
return "open"
except TimeoutError:
return "timeout"
except OSError:
# Refused, no route, DNS failure: all mean nothing is listening there for us.
return "refused"
def _classify_after_failure(
target: ProbeTarget,
timeout: float,
driver_timed_out: bool,
is_auth_failure: Callable[[], bool],
) -> ProbeCategory:
"""Classify a driver connect failure that carries no trustworthy error code.
libpq and FreeTDS (pymssql) both lose the distinction between refused, blackholed and
rejected-login: PG has no SQLSTATE on connect failures and localizes the server text,
pymssql reuses the previous call's error number, and on Windows both wait out the whole
connect timeout on a refused port. A bare TCP connect with the same bound is
language-independent, so it decides reachability; a failed probe costs at most 2x timeout.
"""
reach = _tcp_reachability(target.host, target.port, timeout)
if reach == "refused":
return ProbeCategory.UNREACHABLE
if reach == "timeout":
return ProbeCategory.TIMEOUT
# Port is open: a driver-level stall is a genuine timeout. Otherwise the server answered;
# call it auth_failed only on positive evidence, else rejected (never guess).
if driver_timed_out:
return ProbeCategory.TIMEOUT
return ProbeCategory.AUTH_FAILED if is_auth_failure() else ProbeCategory.REJECTED
def _pg_connect(target: ProbeTarget, timeout: float, client_encoding: str):
return psycopg.connect(
host=target.host,
port=target.port,
dbname=target.database,
user=target.username,
password=target.password,
connect_timeout=_whole_seconds(timeout),
client_encoding=client_encoding,
autocommit=True,
)
def _pg_is_auth_failure(exc: psycopg.Error, target: ProbeTarget, timeout: float) -> bool:
"""Decide from the server's failure text; the text is inspected, never stored or logged.
A UTF8 client turns a non-UTF8 server message (here GB18030 Chinese) into U+FFFD, which
hides every keyword. When UTF8 text is undecided, reconnect once with GB18030 purely to
read it. Absence of positive evidence means "not auth".
"""
text = str(exc).lower()
if any(k in text for k in _PG_AUTH_KEYWORDS):
return True
if _REPLACEMENT_CHAR not in text and any(k in text for k in _PG_MISSING_KEYWORDS):
return False
try:
_pg_connect(target, timeout, "GB18030").close()
return False
except psycopg.Error as retry_exc:
retry_text = str(retry_exc).lower()
return any(k in retry_text for k in _PG_AUTH_KEYWORDS)
except Exception: # noqa: BLE001
return False
def _probe_postgresql(target: ProbeTarget, timeout: float) -> ProbeCategory:
try:
with _pg_connect(target, timeout, "UTF8") as conn:
conn.execute("SELECT 1")
return ProbeCategory.SUCCESS
except psycopg.Error as exc:
sqlstate = getattr(exc, "sqlstate", None) or ""
if sqlstate.startswith("28"):
return ProbeCategory.AUTH_FAILED
timed_out = isinstance(exc, psycopg.errors.ConnectionTimeout) or _chain_has_timeout(exc)
return _classify_after_failure(
target, timeout, timed_out, lambda: _pg_is_auth_failure(exc, target, timeout)
)
def _probe_mysql(target: ProbeTarget, timeout: float) -> ProbeCategory:
try:
conn = pymysql.connect(
host=target.host,
port=target.port,
user=target.username,
password=target.password,
database=target.database,
connect_timeout=timeout,
read_timeout=timeout,
write_timeout=timeout,
)
try:
with conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
finally:
conn.close()
return ProbeCategory.SUCCESS
except pymysql.err.MySQLError as exc:
code = exc.args[0] if exc.args and isinstance(exc.args[0], int) else None
if code in _MYSQL_AUTH_CODES:
return ProbeCategory.AUTH_FAILED
if _chain_has_timeout(exc):
return ProbeCategory.TIMEOUT
if code is not None and code < _MYSQL_SERVER_ERROR_LIMIT:
# The server answered (e.g. 1049 unknown database): reachable, not an auth problem.
return ProbeCategory.REJECTED
return ProbeCategory.UNREACHABLE
except OSError as exc:
return ProbeCategory.TIMEOUT if _chain_has_timeout(exc) else ProbeCategory.UNREACHABLE
def _probe_sqlserver(target: ProbeTarget, timeout: float) -> ProbeCategory:
seconds = _whole_seconds(timeout)
try:
conn = pymssql.connect(
server=target.host,
port=str(target.port),
user=target.username,
password=target.password,
database=target.database,
login_timeout=seconds,
timeout=seconds,
)
try:
cur = conn.cursor()
cur.execute("SELECT 1")
cur.fetchone()
finally:
conn.close()
return ProbeCategory.SUCCESS
except pymssql.Error as exc:
# DB-Lib 20009 = cannot reach server, 20003 = connection timed out. The numeric
# error code is deliberately ignored: pymssql can report a stale one.
parts = exc.args[0] if len(exc.args) == 1 and isinstance(exc.args[0], tuple) else exc.args
text = " ".join(
a.decode("utf-8", "replace") if isinstance(a, bytes) else str(a) for a in parts
).lower()
stalled = "timed out" in text or "unable to connect" in text or _chain_has_timeout(exc)
# 4060 ("Cannot open database ... The login failed.") means the database is missing
# or inaccessible, not that the credentials were wrong, so it is not auth evidence.
is_auth = "login failed" in text and "cannot open database" not in text
return _classify_after_failure(target, timeout, stalled, lambda: is_auth)
_RETRYABLE = frozenset({ProbeCategory.TIMEOUT, ProbeCategory.UNREACHABLE})
_CONNECTORS: dict[str, Callable[[ProbeTarget, float], ProbeCategory]] = {
"postgresql": _probe_postgresql,
"mysql": _probe_mysql,
"sqlserver": _probe_sqlserver,
}
def probe_datasource(
target: ProbeTarget,
*,
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
max_attempts: int = 1,
) -> ProbeResult:
"""Probe one database target and classify the outcome.
Raises UnsupportedDataSourceError for a non-database kind or unknown engine, without
opening a socket. Never raises for connection failures. With max_attempts > 1 only
timeout and unreachable outcomes are retried; auth_failed and rejected need a config
change, so they return at once.
"""
connector = _CONNECTORS.get(target.engine) if target.kind == "database" else None
if connector is None:
raise UnsupportedDataSourceError()
category = ProbeCategory.UNREACHABLE
for _attempt in range(max(1, max_attempts)):
try:
category = connector(target, timeout_seconds)
except Exception: # noqa: BLE001
# Unexpected driver failure: do not surface its text (may include user or host).
category = ProbeCategory.UNREACHABLE
if category not in _RETRYABLE:
break
# Log only non-secret identifiers; username is omitted because it can be ambiguous.
logger.info(
"datasource probe engine=%s host=%s port=%s database=%s category=%s",
target.engine,
target.host,
target.port,
target.database,
category.value,
)
return _result(category)
@@ -6,9 +6,14 @@ Probe tasks must not write platform audit or business occurrence facts.
from __future__ import annotations
from typing import Any
from celery import Celery
from watchman.core.config import get_settings
from watchman.core.db import session_scope
from watchman.jobs.schedule import DATASOURCE_HEALTHCHECK_TASK, build_beat_schedule
from watchman.services.datasource_healthcheck import run_datasource_healthcheck
def create_celery_app() -> Celery:
@@ -25,6 +30,8 @@ def create_celery_app() -> Celery:
timezone="UTC",
enable_utc=True,
worker_hijack_root_logger=False,
# Empty unless the health check is enabled with a valid cron.
beat_schedule=build_beat_schedule(settings),
)
return app
@@ -32,6 +39,16 @@ def create_celery_app() -> Celery:
celery_app = create_celery_app()
@celery_app.task(name=DATASOURCE_HEALTHCHECK_TASK)
def datasource_healthcheck() -> dict[str, Any]:
"""Run the scheduled datasource health check for the server tenant.
The body re-checks the enabled flag and cron, so a stale schedule is a no-op.
"""
with session_scope() as session:
return run_datasource_healthcheck(session).as_dict()
@celery_app.task(name="watchman.probe.ping")
def probe_ping() -> dict[str, str]:
"""Return a static probe payload with no database side effects."""
@@ -0,0 +1,31 @@
"""Beat schedule entries for business jobs (thin adapter over Celery Beat).
Why: the health check must be scheduled only when it is switched on and its cron is
valid, and bad configuration must leave beat startable with no entry.
Boundary: no scheduler of our own; this only builds the beat_schedule dict. Cron
validation and the crontab mapping live in services.cron.
Depends on core.config and services.cron.
"""
from __future__ import annotations
from typing import Any
from watchman.core.config import Settings
from watchman.services.cron import parse_unix_cron, to_celery_crontab
DATASOURCE_HEALTHCHECK_TASK = "watchman.datasources.healthcheck"
DATASOURCE_HEALTHCHECK_ENTRY = "datasource-healthcheck"
def build_beat_schedule(settings: Settings) -> dict[str, dict[str, Any]]:
"""Return beat entries for the given settings; empty when nothing should run."""
schedule: dict[str, dict[str, Any]] = {}
if settings.datasource_healthcheck_enabled:
fields = parse_unix_cron(settings.datasource_healthcheck_cron)
if fields is not None:
schedule[DATASOURCE_HEALTHCHECK_ENTRY] = {
"task": DATASOURCE_HEALTHCHECK_TASK,
"schedule": to_celery_crontab(fields),
}
return schedule
@@ -1,6 +1,7 @@
"""SQLAlchemy models for the Watchman service package."""
from watchman.models.auth_session import AuthSession
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent, RunRecord
__all__ = ["AuthSession", "AuditEvent", "RunRecord"]
__all__ = ["AuthSession", "AuditEvent", "DataSource", "RunRecord"]
@@ -0,0 +1,135 @@
"""Tenant-scoped datasource metadata with an encrypted password.
Boundary: persistence and the kind/engine whitelist only; no connection logic and no
plaintext secrets. Kind and engine stay free-form strings in the table so later phases
can widen them by relaxing the CHECK constraints instead of changing the column type.
Depends on SQLAlchemy and the shared Watchman declarative base.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
Integer,
String,
Text,
UniqueConstraint,
func,
text,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from watchman.models.base import Base
ALLOWED_KINDS = frozenset({"database"})
ALLOWED_ENGINES = frozenset({"postgresql", "mysql", "sqlserver"})
def validate_kind_engine(kind: str, engine: str) -> None:
"""Reject unsupported kind or engine before touching the database.
The CHECK constraints remain the backstop; this gives callers a readable error first.
"""
if kind not in ALLOWED_KINDS:
raise ValueError(f"unsupported datasource kind: {kind!r}")
if engine not in ALLOWED_ENGINES:
raise ValueError(f"unsupported datasource engine: {engine!r}")
class DataSource(Base):
"""A configured source database; the password is stored only as Fernet ciphertext."""
__tablename__ = "data_sources"
__table_args__ = (
UniqueConstraint("tenant_id", "name", name="uq_data_sources_tenant_name"),
CheckConstraint("kind = 'database'", name="ck_data_sources_kind"),
CheckConstraint(
"engine IN ('postgresql','mysql','sqlserver')",
name="ck_data_sources_engine",
),
CheckConstraint("port BETWEEN 1 AND 65535", name="ck_data_sources_port"),
CheckConstraint(
"circuit_failure_window_seconds BETWEEN 1 AND 86400",
name="ck_data_sources_circuit_window",
),
CheckConstraint(
"circuit_failure_threshold BETWEEN 1 AND 100",
name="ck_data_sources_circuit_threshold",
),
CheckConstraint(
"circuit_open_cooldown_seconds BETWEEN 1 AND 86400",
name="ck_data_sources_circuit_cooldown",
),
CheckConstraint(
"circuit_state IN ('closed','open')", name="ck_data_sources_circuit_state"
),
CheckConstraint("circuit_failure_count >= 0", name="ck_data_sources_circuit_count"),
)
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
kind: Mapped[str] = mapped_column(String(32), nullable=False)
engine: Mapped[str] = mapped_column(String(32), nullable=False)
host: Mapped[str] = mapped_column(String(255), nullable=False)
port: Mapped[int] = mapped_column(Integer, nullable=False)
database_name: Mapped[str] = mapped_column(String(128), nullable=False)
username: Mapped[str] = mapped_column(String(128), nullable=False)
secret_ciphertext: Mapped[str] = mapped_column(Text, nullable=False)
read_only_intent: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("true")
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
last_test_category: Mapped[str | None] = mapped_column(String(32), nullable=True)
last_test_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_test_message: Mapped[str | None] = mapped_column(String(255), nullable=True)
# Circuit breaker: independent of `enabled`; an open circuit never flips it.
circuit_failure_window_seconds: Mapped[int] = mapped_column(
Integer, nullable=False, default=300, server_default=text("300")
)
circuit_failure_threshold: Mapped[int] = mapped_column(
Integer, nullable=False, default=3, server_default=text("3")
)
circuit_open_cooldown_seconds: Mapped[int] = mapped_column(
Integer, nullable=False, default=600, server_default=text("600")
)
circuit_state: Mapped[str] = mapped_column(
String(16), nullable=False, default="closed", server_default=text("'closed'")
)
circuit_opened_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
circuit_failure_count: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default=text("0")
)
circuit_window_started_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
)
def __repr__(self) -> str:
# GUARD: never include secret_ciphertext, even though it is encrypted.
return (
f"DataSource(id={self.id!s}, tenant_id={self.tenant_id!r}, name={self.name!r}, "
f"engine={self.engine!r})"
)
@@ -0,0 +1,70 @@
"""Thin Cron validation shared by the scheduler adapter and job bodies.
Why: a configured schedule string must mean the same thing to the validator and to
Celery Beat, and a bad string must degrade to "no schedule" instead of breaking boot.
Boundary: croniter validates and Celery's crontab executes; nothing here parses cron
itself. Only a conservative subset is accepted (5 fields, digits and * / , - only) and
day-of-month plus day-of-week may not both be restricted, because croniter ORs them while
Celery ANDs them (docs/cron-reuse.md section 5).
Depends on croniter and celery.schedules.
"""
from __future__ import annotations
import re
from typing import NamedTuple
from celery.schedules import crontab
from croniter import croniter
_FIELD_PATTERN = re.compile(r"^[0-9*/,\-]+$")
_MAX_LENGTH = 100
class CronFields(NamedTuple):
"""The five validated Unix cron fields."""
minute: str
hour: str
day_of_month: str
month_of_year: str
day_of_week: str
def parse_unix_cron(expression: str | None) -> CronFields | None:
"""Return the cron fields, or None when the expression is not an accepted 5-field cron."""
if not isinstance(expression, str):
return None
text = expression.strip()
if not text or len(text) > _MAX_LENGTH:
return None
parts = text.split()
if len(parts) != 5 or not all(_FIELD_PATTERN.match(part) for part in parts):
return None
fields = CronFields(*parts)
# Semantics differ when both day fields are restricted (OR vs AND): refuse, not guess.
if fields.day_of_month != "*" and fields.day_of_week != "*":
return None
try:
if not croniter.is_valid(" ".join(parts)):
return None
# The executing side must accept the same fields.
to_celery_crontab(fields)
except Exception: # noqa: BLE001 - any library rejection means "invalid"
return None
return fields
def is_valid_unix_cron(expression: str | None) -> bool:
return parse_unix_cron(expression) is not None
def to_celery_crontab(fields: CronFields) -> crontab:
"""Map validated fields onto a Celery crontab schedule."""
return crontab(
minute=fields.minute,
hour=fields.hour,
day_of_month=fields.day_of_month,
month_of_year=fields.month_of_year,
day_of_week=fields.day_of_week,
)
@@ -0,0 +1,94 @@
"""Scheduled datasource health check orchestration (M03 S7, D23).
Why: a source that quietly broke should show a failed last_test (and open its circuit
after repeated failures) before someone runs a query against it.
Boundary: only enabled, circuit-closed sources of the server tenant are probed, one at a
time, through the same probe path as the saved connection test; enabled is never
changed and nothing is sent to WeCom. Each source commits on its own so no transaction
stays open during a network probe. Callers (the Celery task) own the session.
Depends on services.datasources, services.cron and core.config.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any
from sqlalchemy.orm import Session
from watchman.core.config import Settings, get_settings
from watchman.core.errors import AppError
from watchman.datasources import ProbeCategory
from watchman.services.cron import is_valid_unix_cron
from watchman.services.datasources import list_datasources, run_healthcheck_probe
logger = logging.getLogger(__name__)
SKIP_DISABLED = "healthcheck_disabled"
SKIP_INVALID_CRON = "invalid_cron"
@dataclass
class HealthcheckSummary:
"""Counts only; never hosts, names or error text."""
skipped_reason: str | None = None
checked: int = 0
succeeded: int = 0
failed: int = 0
skipped: int = 0
errors: int = 0
categories: dict[str, int] = field(default_factory=dict)
def as_dict(self) -> dict[str, Any]:
return {
"skipped_reason": self.skipped_reason,
"checked": self.checked,
"succeeded": self.succeeded,
"failed": self.failed,
"skipped": self.skipped,
"errors": self.errors,
"categories": dict(self.categories),
}
def run_datasource_healthcheck(
session: Session, *, settings: Settings | None = None
) -> HealthcheckSummary:
"""Probe every enabled, circuit-closed datasource and record the outcomes."""
current = settings or get_settings()
summary = HealthcheckSummary()
if not current.datasource_healthcheck_enabled:
summary.skipped_reason = SKIP_DISABLED
return summary
if not is_valid_unix_cron(current.datasource_healthcheck_cron):
summary.skipped_reason = SKIP_INVALID_CRON
return summary
# Listing closes elapsed cooldowns; commit persists that and ends the read transaction.
candidate_ids = [str(row.id) for row in list_datasources(session, usable_only=True)]
session.commit()
for datasource_id in candidate_ids:
try:
result = run_healthcheck_probe(session, datasource_id)
session.commit()
except AppError:
# One broken source (unsupported engine, unusable secret) must not stop the rest.
session.rollback()
summary.errors += 1
logger.warning("datasource healthcheck error id=%s", datasource_id)
continue
if result is None:
summary.skipped += 1
continue
summary.checked += 1
summary.categories[result.category.value] = (
summary.categories.get(result.category.value, 0) + 1
)
if result.category is ProbeCategory.SUCCESS:
summary.succeeded += 1
else:
summary.failed += 1
return summary
@@ -0,0 +1,600 @@
"""Datasource configuration service: CRUD, disable, connection test and audit.
Why: the console needs to save source-database connections without the API layer ever
touching plaintext passwords or deciding tenant scope.
Boundary: tenant comes only from server settings; the password is encrypted on write and
decrypted only inside test_datasource; no public dict carries a password, ciphertext or
connection string. Callers (routes) own the final commit, except test_datasource, which
commits once before the network call so no transaction stays open during the probe.
Depends on the DataSource model, core.secrets, datasources.probe and create_audit_event.
"""
from __future__ import annotations
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from watchman.core.config import get_settings
from watchman.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from watchman.core.secrets import SecretDecryptError, SecretKeyError, decrypt_secret, encrypt_secret
from watchman.datasources import (
ProbeCategory,
ProbeResult,
ProbeTarget,
UnsupportedDataSourceError,
probe_datasource,
)
from watchman.models.datasource import DataSource, validate_kind_engine
from watchman.services.platform_records import create_audit_event
# Only these probe categories are worth retrying; the others need a config change.
RETRYABLE_CATEGORIES = frozenset({ProbeCategory.TIMEOUT, ProbeCategory.UNREACHABLE})
CIRCUIT_CLOSED = "closed"
CIRCUIT_OPEN = "open"
# Allowed ranges for the per-source circuit parameters (mirrored by CHECK constraints).
_CIRCUIT_RANGES: dict[str, tuple[int, int]] = {
"circuit_failure_window_seconds": (1, 86400),
"circuit_failure_threshold": (1, 100),
"circuit_open_cooldown_seconds": (1, 86400),
}
# Plain columns a PATCH may change. The password is handled separately and enabled is
# only changed by enable_datasource / disable_datasource.
_UPDATABLE_FIELDS = (
"name",
"description",
"kind",
"engine",
"host",
"port",
"database_name",
"username",
"read_only_intent",
"circuit_failure_window_seconds",
"circuit_failure_threshold",
"circuit_open_cooldown_seconds",
)
# Fields (besides the password) whose change invalidates the stored test result.
_CONNECTION_FIELDS = ("engine", "host", "port", "database_name", "username")
class DatasourceSecretUnavailableError(AppError):
"""The stored password cannot be used (key missing or changed). Message is fixed."""
def __init__(self) -> None:
super().__init__(
"Datasource secret is unavailable",
code=50000,
http_status=500,
details={"reason": "secret_unavailable"},
)
class ConnectionTestFailedError(AppError):
"""A connection test ran and did not succeed.
The message is the fixed probe text; details carry only the category, never driver text.
"""
def __init__(self, result: ProbeResult) -> None:
super().__init__(
result.message,
code=40000,
http_status=400,
details={"category": result.category.value},
retryable=result.category in RETRYABLE_CATEGORIES,
)
def _now() -> datetime:
return datetime.now(timezone.utc)
def _tenant_id() -> str:
# GUARD: tenant is never taken from a request.
return get_settings().tenant_id
def _isoformat(value: datetime | None) -> str | None:
return value.isoformat() if value is not None else None
def _circuit_open_until(row: DataSource) -> datetime | None:
if row.circuit_state != CIRCUIT_OPEN or row.circuit_opened_at is None:
return None
return row.circuit_opened_at + timedelta(seconds=row.circuit_open_cooldown_seconds)
def to_public(row: DataSource) -> dict[str, Any]:
"""Serialize a datasource for API responses.
Exposes only whether a password is stored; the ciphertext and any connection
string are never included. circuit_state is the stored state; circuit_open_until is
set only while it is open (an elapsed value means the next usability check closes it).
"""
return {
"id": str(row.id),
"name": row.name,
"description": row.description,
"kind": row.kind,
"engine": row.engine,
"host": row.host,
"port": row.port,
"database_name": row.database_name,
"username": row.username,
"secret_configured": bool(row.secret_ciphertext),
"read_only_intent": row.read_only_intent,
"enabled": row.enabled,
"last_test_category": row.last_test_category,
"last_test_at": _isoformat(row.last_test_at),
"last_test_message": row.last_test_message,
"circuit_state": row.circuit_state,
"circuit_opened_at": _isoformat(row.circuit_opened_at),
"circuit_open_until": _isoformat(_circuit_open_until(row)),
"circuit_failure_window_seconds": row.circuit_failure_window_seconds,
"circuit_failure_threshold": row.circuit_failure_threshold,
"circuit_open_cooldown_seconds": row.circuit_open_cooldown_seconds,
"created_at": _isoformat(row.created_at),
"updated_at": _isoformat(row.updated_at),
}
def _parse_id(datasource_id: str) -> uuid.UUID:
try:
return uuid.UUID(datasource_id)
except ValueError:
# An id that cannot exist is the same as an unknown id.
raise NotFoundError("Datasource not found") from None
def _get_row(
session: Session, datasource_id: str, *, refresh: bool = False, lock: bool = False
) -> DataSource:
"""Load one datasource of the server tenant or raise 404 (also for other tenants).
lock=True takes a row lock (and refreshes) so circuit counters are not lost to a race.
"""
statement = select(DataSource).where(
DataSource.id == _parse_id(datasource_id),
DataSource.tenant_id == _tenant_id(),
)
if refresh or lock:
statement = statement.execution_options(populate_existing=True)
if lock:
statement = statement.with_for_update()
row = session.scalar(statement)
if row is None:
raise NotFoundError("Datasource not found")
return row
def _check_kind_engine(kind: str, engine: str) -> None:
try:
validate_kind_engine(kind, engine)
except ValueError:
# Fixed text: do not echo the caller's value.
raise ValidationError(
"Unsupported datasource kind or engine",
details={"fields": ["kind", "engine"]},
) from None
def _check_circuit_params(values: dict[str, Any]) -> None:
bad = [
field
for field, (low, high) in _CIRCUIT_RANGES.items()
if values.get(field) is not None
and (
isinstance(values[field], bool)
or not isinstance(values[field], int)
or not low <= values[field] <= high
)
]
if bad:
raise ValidationError("Circuit parameter out of range", details={"fields": bad})
def _ensure_name_free(session: Session, name: str, *, exclude_id: uuid.UUID | None = None) -> None:
statement = select(DataSource.id).where(
DataSource.tenant_id == _tenant_id(),
DataSource.name == name,
)
if exclude_id is not None:
statement = statement.where(DataSource.id != exclude_id)
if session.scalar(statement) is not None:
raise ConflictError("Datasource name already exists", details={"reason": "duplicate_name"})
def _flush_unique(session: Session) -> None:
"""Flush, turning a racing duplicate-name insert or update into the same 409."""
try:
with session.begin_nested():
session.flush()
except IntegrityError:
raise ConflictError(
"Datasource name already exists", details={"reason": "duplicate_name"}
) from None
def _audit(session: Session, action: str, row: DataSource, **extra: Any) -> None:
"""Write an audit event with a server-generated key and a credential-free payload."""
payload = {"id": str(row.id), "name": row.name, "engine": row.engine, **extra}
create_audit_event(
session,
action=action,
payload=payload,
idempotency_key=f"{action}:{uuid.uuid4().hex}",
)
def list_datasources(session: Session, *, usable_only: bool = False) -> list[DataSource]:
"""Return datasources of the server tenant, oldest first.
Every returned row first has an elapsed circuit cooldown closed (time only, no probe),
so the exposed circuit state is never stale; the caller commits to persist that.
usable_only then keeps rows that are enabled and whose circuit is closed.
"""
rows = list(
session.scalars(
select(DataSource)
.where(DataSource.tenant_id == _tenant_id())
.order_by(DataSource.created_at, DataSource.name)
)
)
now = _now()
for row in rows:
_close_if_cooled_down(row, now)
if not usable_only:
return rows
return [row for row in rows if row.enabled and row.circuit_state != CIRCUIT_OPEN]
def get_datasource(session: Session, datasource_id: str) -> DataSource:
"""Return one datasource or raise 404.
An elapsed circuit cooldown is closed first (the caller commits to persist it), so
the exposed circuit state matches what assert_usable would decide.
"""
row = _get_row(session, datasource_id)
_close_if_cooled_down(row, _now())
return row
def create_datasource(
session: Session,
*,
name: str,
description: str | None,
kind: str,
engine: str,
host: str,
port: int,
database_name: str,
username: str,
password: str,
read_only_intent: bool,
) -> DataSource:
"""Create an enabled datasource with an encrypted password and write the audit event."""
_check_kind_engine(kind, engine)
if not password.strip():
raise ValidationError("Password is required", details={"fields": ["password"]})
_ensure_name_free(session, name)
now = _now()
row = DataSource(
tenant_id=_tenant_id(),
name=name,
description=description,
kind=kind,
engine=engine,
host=host,
port=port,
database_name=database_name,
username=username,
secret_ciphertext=encrypt_secret(password),
read_only_intent=read_only_intent,
enabled=True,
circuit_failure_window_seconds=300,
circuit_failure_threshold=3,
circuit_open_cooldown_seconds=600,
circuit_state=CIRCUIT_CLOSED,
circuit_failure_count=0,
created_at=now,
updated_at=now,
)
session.add(row)
_flush_unique(session)
_audit(session, "datasource.create", row)
return row
def update_datasource(session: Session, datasource_id: str, changes: dict[str, Any]) -> DataSource:
"""Apply a partial update. A missing or blank password keeps the stored ciphertext."""
row = _get_row(session, datasource_id)
# Only description may be cleared; an explicit null elsewhere is a caller mistake.
nulled = [f for f in _UPDATABLE_FIELDS if f != "description" and f in changes and changes[f] is None]
if nulled:
raise ValidationError("Fields cannot be null", details={"fields": nulled})
_check_circuit_params(changes)
password = changes.get("password")
new_kind = changes.get("kind", row.kind)
new_engine = changes.get("engine", row.engine)
_check_kind_engine(new_kind, new_engine)
if "name" in changes and changes["name"] != row.name:
_ensure_name_free(session, changes["name"], exclude_id=row.id)
# A changed connection target or credential makes the last test result describe an
# old configuration, so it is cleared; name or description edits keep it.
connection_changed = any(
field in changes and changes[field] != getattr(row, field) for field in _CONNECTION_FIELDS
)
for field in _UPDATABLE_FIELDS:
if field in changes:
setattr(row, field, changes[field])
if isinstance(password, str) and password.strip():
row.secret_ciphertext = encrypt_secret(password)
connection_changed = True
if connection_changed:
row.last_test_category = None
row.last_test_at = None
row.last_test_message = None
row.updated_at = _now()
_flush_unique(session)
_audit(session, "datasource.update", row)
return row
def disable_datasource(session: Session, datasource_id: str) -> DataSource:
"""Mark a datasource disabled. The row stays readable; it is never deleted."""
row = _get_row(session, datasource_id)
row.enabled = False
row.updated_at = _now()
session.flush()
_audit(session, "datasource.disable", row)
return row
def enable_datasource(session: Session, datasource_id: str) -> DataSource:
"""Mark a datasource enabled again. The circuit state is left untouched."""
row = _get_row(session, datasource_id)
row.enabled = True
row.updated_at = _now()
session.flush()
_audit(session, "datasource.enable", row)
return row
def _close_circuit(row: DataSource) -> None:
row.circuit_state = CIRCUIT_CLOSED
row.circuit_opened_at = None
row.circuit_failure_count = 0
row.circuit_window_started_at = None
def _close_if_cooled_down(row: DataSource, now: datetime) -> bool:
"""Close an open circuit whose cooldown has elapsed (time only, no probe). True if closed."""
until = _circuit_open_until(row)
if row.circuit_state == CIRCUIT_OPEN and (until is None or now >= until):
_close_circuit(row)
return True
return False
def assert_usable(session: Session, target: DataSource | str) -> DataSource:
"""Raise 409 unless the datasource is enabled and its circuit lets traffic through.
reason=disabled for a disabled source, reason=circuit_open while the cooldown runs.
An elapsed cooldown closes the circuit (the caller commits) and the call passes.
"""
row = _get_row(session, target) if isinstance(target, str) else target
if not row.enabled:
raise ConflictError("Datasource is disabled", details={"reason": "disabled"})
now = _now()
_close_if_cooled_down(row, now)
if row.circuit_state == CIRCUIT_OPEN:
until = _circuit_open_until(row)
raise ConflictError(
"Datasource circuit is open",
details={"reason": "circuit_open", "circuit_open_until": _isoformat(until)},
)
return row
def record_probe_outcome(
session: Session,
row: DataSource,
result: ProbeResult,
*,
update_last_test: bool = True,
) -> bool:
"""Account one persisted probe against the circuit. Returns True if it opened it.
Only saved-connection tests and health checks call this; draft tests never do. Any
non-success category (auth_failed included) is a failure. Failures are counted from
the start of a window of circuit_failure_window_seconds; a success while closed
resets the count. The caller holds a locked, fresh row and commits.
"""
now = _now()
if update_last_test:
row.last_test_category = result.category.value
row.last_test_at = now
row.last_test_message = result.message
row.updated_at = now
opened = False
if row.circuit_state == CIRCUIT_CLOSED:
if result.category is ProbeCategory.SUCCESS:
row.circuit_failure_count = 0
row.circuit_window_started_at = None
else:
started = row.circuit_window_started_at
window = timedelta(seconds=row.circuit_failure_window_seconds)
if started is None or now - started > window:
started = now
row.circuit_failure_count = 0
row.circuit_window_started_at = started
row.circuit_failure_count += 1
if row.circuit_failure_count >= row.circuit_failure_threshold:
row.circuit_state = CIRCUIT_OPEN
row.circuit_opened_at = now
opened = True
session.flush()
if opened:
_audit(
session,
"datasource.circuit_open",
row,
category=result.category.value,
failure_count=row.circuit_failure_count,
)
return opened
def list_references(session: Session, datasource_id: str) -> dict[str, Any]:
"""Return the references to a datasource. No module references datasources yet."""
row = _get_row(session, datasource_id)
return {"id": str(row.id), "items": []}
def _probe(target: ProbeTarget) -> ProbeResult:
"""Run one probe with the configured timeout and attempt cap."""
settings = get_settings()
try:
return probe_datasource(
target,
timeout_seconds=settings.datasource_probe_timeout_seconds,
max_attempts=settings.datasource_probe_max_attempts,
)
except UnsupportedDataSourceError:
raise ValidationError(
"Unsupported datasource kind or engine",
details={"fields": ["kind", "engine"]},
) from None
def _decrypt_stored(row: DataSource) -> str:
try:
return decrypt_secret(row.secret_ciphertext)
except (SecretKeyError, SecretDecryptError):
raise DatasourceSecretUnavailableError() from None
def run_connection_test(session: Session, datasource_id: str) -> tuple[DataSource, ProbeResult]:
"""Probe the saved connection, record last_test and circuit accounting; the caller commits.
The target is built only from the stored row and its decrypted password. A disabled
or circuit-open datasource is refused with 409 before the password is decrypted or any
socket opens. The outcome (including a circuit that opens because of it) is persisted
for success and failure alike.
"""
row = assert_usable(session, _get_row(session, datasource_id))
password = _decrypt_stored(row)
target = ProbeTarget(
engine=row.engine,
kind=row.kind,
host=row.host,
port=row.port,
database=row.database_name,
username=row.username,
password=password,
)
# End the read transaction first (this also persists an auto-closed circuit) so no
# connection is held open during the probe.
session.commit()
result = _probe(target)
row = _get_row(session, datasource_id, lock=True)
record_probe_outcome(session, row, result)
_audit(session, "datasource.test", row, category=result.category.value)
return row, result
def run_healthcheck_probe(session: Session, datasource_id: str) -> ProbeResult | None:
"""Probe one saved datasource for the scheduled health check; the caller commits.
Returns None (no probe, nothing recorded) when the source is gone, disabled or its
circuit is open. Otherwise the target is built from the stored row exactly like
run_connection_test, the outcome feeds last_test and the circuit, and a non-success
writes a credential-free audit event (id, name, engine, category). enabled is never
changed. No transaction stays open during the probe.
"""
try:
row = _get_row(session, datasource_id, refresh=True)
assert_usable(session, row)
except (NotFoundError, ConflictError):
# Persist an auto-closed circuit, then release the read transaction.
session.commit()
return None
password = _decrypt_stored(row)
target = ProbeTarget(
engine=row.engine,
kind=row.kind,
host=row.host,
port=row.port,
database=row.database_name,
username=row.username,
password=password,
)
session.commit()
result = _probe(target)
try:
row = _get_row(session, datasource_id, lock=True)
except NotFoundError:
session.rollback()
return None
record_probe_outcome(session, row, result)
if result.category is not ProbeCategory.SUCCESS:
_audit(session, "datasource.healthcheck_failed", row, category=result.category.value)
return result
def run_draft_connection_test(
session: Session,
fields: dict[str, Any],
*,
datasource_id: str | None = None,
) -> ProbeResult:
"""Probe a form-only target. Never writes last_test_* and never feeds the circuit.
A blank password falls back to the stored secret of datasource_id (same tenant); with
no datasource_id a password is required. The saved row's enabled flag and circuit are
deliberately ignored: a draft is only a check of what the form holds. The caller commits.
"""
kind = fields.get("kind") or "database"
engine = fields.get("engine") or ""
_check_kind_engine(kind, engine)
password = fields.get("password")
stored: DataSource | None = None
if datasource_id is not None:
stored = _get_row(session, datasource_id)
if not isinstance(password, str) or not password.strip():
if stored is None:
raise ValidationError("Password is required", details={"fields": ["password"]})
password = _decrypt_stored(stored)
target = ProbeTarget(
engine=engine,
kind=kind,
host=fields["host"],
port=fields["port"],
database=fields["database_name"],
username=fields["username"],
password=password,
)
audit_id = str(stored.id) if stored is not None else None
# No transaction may stay open during the network call.
session.commit()
result = _probe(target)
# GUARD: payload has no host, user or password; the target is not recorded.
create_audit_event(
session,
action="datasource.test_draft",
payload={"engine": engine, "category": result.category.value, "id": audit_id},
idempotency_key=f"datasource.test_draft:{uuid.uuid4().hex}",
)
return result
@@ -0,0 +1,686 @@
"""Datasource API tests: permission matrix, secret hygiene, disable, test endpoint, audit.
Why: the datasource routes are the only place a password enters and the only place a
saved connection can be probed, so roles, redaction and the no-target rule need proof.
Boundary: uses the local platform Postgres and seeded sessions like test_platform_access;
probes are replaced by fakes except one live PostgreSQL test taken from WATCHMAN_TEST_PG_*.
All rows created here are removed afterwards (audit events are append-only and kept).
Depends on watchman.api.app, the session store and the datasource service.
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from cryptography.fernet import Fernet
from fastapi.testclient import TestClient
from sqlalchemy import delete, select
from watchman.api.app import create_app
from watchman.auth.access import (
DATASOURCE_READ_NODE,
DATASOURCE_TEST_NODE,
DATASOURCE_WRITE_NODE,
require_datasource_read,
require_datasource_test,
require_datasource_write,
)
from watchman.auth.principal import get_role_directory
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
from watchman.core.config import get_settings, merge_layered_env, reload_settings
from watchman.core.db import get_session_factory, reset_engine, set_tenant
from watchman.core.errors import ForbiddenError
from watchman.core.secrets import KEY_ENV_NAME, decrypt_secret
from watchman.datasources import ProbeCategory, ProbeResult, ProbeTarget, probe_datasource
from watchman.models.auth_session import AuthSession
from watchman.models.datasource import DataSource
from watchman.models.platform import AuditEvent
from watchman.services import datasources as service
# Unique marker: any appearance in a response or audit payload is a leak. Not a credential.
SENTINEL = "Zq9-api-sentinel-pw-4c1e7a"
OTHER_SENTINEL = "Zq9-api-replacement-pw-8d2b6f"
NAME_PREFIX = f"apitest-{uuid.uuid4().hex[:8]}-"
ADMIN = ["watchman-admin"]
OPERATOR = ["watchman-operator"]
VIEWER = ["watchman-viewer"]
@pytest.fixture(autouse=True)
def datasource_key(monkeypatch: pytest.MonkeyPatch):
"""Use a throwaway Fernet key so these tests never depend on the real one."""
monkeypatch.setenv(KEY_ENV_NAME, Fernet.generate_key().decode("ascii"))
reload_settings()
yield
monkeypatch.undo()
reload_settings()
@pytest.fixture(autouse=True)
def cleanup():
"""Delete seeded sessions and every datasource whose name carries this run's prefix."""
tokens: list[str] = []
yield tokens
reload_settings()
reset_engine()
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
session.execute(delete(DataSource).where(DataSource.name.like(f"{NAME_PREFIX}%")))
if tokens:
session.execute(
delete(AuthSession).where(
AuthSession.token_hash.in_([hash_cookie_token(t) for t in tokens])
)
)
session.commit()
finally:
session.close()
reset_engine()
def _seed(tokens: list[str], roles: list[str]) -> str:
token = issue_cookie_token()
now = datetime.now(timezone.utc)
settings = get_settings()
session = get_session_factory()()
try:
set_tenant(session, settings.tenant_id)
session.add(
AuthSession(
token_hash=hash_cookie_token(token),
subject=f"subject-{uuid.uuid4().hex}",
issuer="https://casdoor.test",
display_name="Worker",
login_name="worker",
role_snapshot=list(roles),
role_checked_at=now,
expires_at=now + timedelta(hours=1),
tenant_id=settings.tenant_id,
)
)
session.commit()
finally:
session.close()
tokens.append(token)
return token
def _client(cleanup: list[str], roles: list[str] | None) -> TestClient:
"""A client with a fresh seeded session; roles=None means no cookie at all."""
reload_settings()
reset_engine()
app = create_app()
class _NoDirectory:
def lookup_roles(self, *, login_name: str) -> list[str]:
raise AssertionError("a fresh session must not trigger a role reload")
app.dependency_overrides[get_role_directory] = lambda: _NoDirectory()
client = TestClient(app)
if roles is not None:
client.cookies.set(SESSION_COOKIE_NAME, _seed(cleanup, roles))
return client
def _body(**overrides) -> dict:
values = {
"name": f"{NAME_PREFIX}{uuid.uuid4().hex[:8]}",
"description": "synthetic",
"kind": "database",
"engine": "postgresql",
"host": "db.synthetic.invalid",
"port": 5432,
"database_name": "synthetic_db",
"username": "synthetic_user",
"password": SENTINEL,
}
values.update(overrides)
return values
def _create(client: TestClient, **overrides) -> dict:
response = client.post("/datasources", json=_body(**overrides))
assert response.status_code == 200, response.text
return response.json()["data"]
def _stored(datasource_id: str) -> DataSource:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
row = session.scalar(select(DataSource).where(DataSource.id == uuid.UUID(datasource_id)))
assert row is not None
return row
finally:
session.close()
def _audit_events(datasource_id: str, action: str) -> list[AuditEvent]:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
return list(
session.scalars(
select(AuditEvent).where(
AuditEvent.tenant_id == get_settings().tenant_id,
AuditEvent.action == action,
AuditEvent.payload["id"].as_string() == datasource_id,
)
)
)
finally:
session.close()
@pytest.fixture
def no_network(monkeypatch: pytest.MonkeyPatch):
"""Fail loudly if any code path tries to probe or open a socket."""
def _boom(*_args, **_kwargs):
raise AssertionError("network must not be used")
monkeypatch.setattr(service, "probe_datasource", _boom)
monkeypatch.setattr("watchman.datasources.probe.probe_datasource", _boom)
monkeypatch.setattr("socket.create_connection", _boom)
# --- permission nodes and role rules ---------------------------------------------------
def test_node_strings_and_role_rules() -> None:
assert DATASOURCE_READ_NODE == "perm:data:emp:watchman.datasource.read"
assert DATASOURCE_WRITE_NODE == "perm:data:emp:watchman.datasource.write"
assert DATASOURCE_TEST_NODE == "perm:data:emp:watchman.datasource.test"
# The confirmed console allows only watchman-admin into datasources.
require_datasource_read(ADMIN)
require_datasource_write(ADMIN)
require_datasource_test(ADMIN)
cases = [
(require_datasource_read, OPERATOR, DATASOURCE_READ_NODE),
(require_datasource_read, VIEWER, DATASOURCE_READ_NODE),
(require_datasource_read, [], DATASOURCE_READ_NODE),
(require_datasource_read, ["someone-else"], DATASOURCE_READ_NODE),
(require_datasource_write, OPERATOR, DATASOURCE_WRITE_NODE),
(require_datasource_write, VIEWER, DATASOURCE_WRITE_NODE),
(require_datasource_write, [], DATASOURCE_WRITE_NODE),
(require_datasource_test, OPERATOR, DATASOURCE_TEST_NODE),
(require_datasource_test, VIEWER, DATASOURCE_TEST_NODE),
(require_datasource_test, [], DATASOURCE_TEST_NODE),
]
for check, roles, node in cases:
with pytest.raises(ForbiddenError) as raised:
check(roles)
assert raised.value.permission_node == node
ANY_ID = str(uuid.uuid4())
ROUTES = [
("GET", "/datasources", None),
("POST", "/datasources", _body()),
("GET", f"/datasources/{ANY_ID}", None),
("PATCH", f"/datasources/{ANY_ID}", {"description": "x"}),
("POST", f"/datasources/{ANY_ID}/disable", None),
("POST", f"/datasources/{ANY_ID}/enable", None),
("POST", "/datasources/test-draft", {"engine": "postgresql", "host": "h", "port": 5432, "database_name": "d", "username": "u", "password": "x"}),
("POST", f"/datasources/{ANY_ID}/test", None),
("GET", f"/datasources/{ANY_ID}/references", None),
]
@pytest.mark.parametrize(("method", "path", "payload"), ROUTES)
def test_anonymous_is_41000_without_permission_node(cleanup, method, path, payload) -> None:
response = _client(cleanup, None).request(method, path, json=payload)
assert response.status_code == 401
error = response.json()["error"]
assert error["code"] == 41000
assert "permission_node" not in error
@pytest.mark.parametrize(
("roles", "method", "path_kind", "node"),
[
(VIEWER, "POST", "create", DATASOURCE_WRITE_NODE),
(VIEWER, "PATCH", "item", DATASOURCE_WRITE_NODE),
(VIEWER, "POST", "disable", DATASOURCE_WRITE_NODE),
(VIEWER, "POST", "test", DATASOURCE_TEST_NODE),
(VIEWER, "POST", "enable", DATASOURCE_WRITE_NODE),
(VIEWER, "POST", "draft", DATASOURCE_TEST_NODE),
(OPERATOR, "POST", "enable", DATASOURCE_WRITE_NODE),
(OPERATOR, "POST", "draft", DATASOURCE_TEST_NODE),
(VIEWER, "GET", "list", DATASOURCE_READ_NODE),
(VIEWER, "GET", "item", DATASOURCE_READ_NODE),
(VIEWER, "GET", "references", DATASOURCE_READ_NODE),
(OPERATOR, "POST", "create", DATASOURCE_WRITE_NODE),
(OPERATOR, "PATCH", "item", DATASOURCE_WRITE_NODE),
(OPERATOR, "POST", "disable", DATASOURCE_WRITE_NODE),
(OPERATOR, "POST", "test", DATASOURCE_TEST_NODE),
(OPERATOR, "GET", "list", DATASOURCE_READ_NODE),
(OPERATOR, "GET", "item", DATASOURCE_READ_NODE),
(OPERATOR, "GET", "references", DATASOURCE_READ_NODE),
([], "GET", "list", DATASOURCE_READ_NODE),
([], "GET", "references", DATASOURCE_READ_NODE),
([], "GET", "item", DATASOURCE_READ_NODE),
],
)
def test_wrong_role_is_42000_with_node(cleanup, no_network, roles, method, path_kind, node) -> None:
created = _create(_client(cleanup, ADMIN))
ds_id = created["id"]
paths = {
"create": "/datasources",
"list": "/datasources",
"item": f"/datasources/{ds_id}",
"disable": f"/datasources/{ds_id}/disable",
"test": f"/datasources/{ds_id}/test",
"enable": f"/datasources/{ds_id}/enable",
"draft": "/datasources/test-draft",
"references": f"/datasources/{ds_id}/references",
}
payload = _body() if path_kind in ("create", "draft") else ({"description": "x"} if method == "PATCH" else None)
response = _client(cleanup, roles).request(method, paths[path_kind], json=payload)
assert response.status_code == 403
error = response.json()["error"]
assert error["code"] == 42000
assert error["permission_node"] == node
# A denied write must not have changed anything.
assert _stored(ds_id).enabled is True and _stored(ds_id).description == "synthetic"
def test_admin_can_read(cleanup) -> None:
created = _create(_client(cleanup, ADMIN))
client = _client(cleanup, ADMIN)
listing = client.get("/datasources")
assert listing.status_code == 200
assert created["id"] in [item["id"] for item in listing.json()["data"]["items"]]
assert client.get(f"/datasources/{created['id']}").status_code == 200
# --- create, redaction, audit --------------------------------------------------------------
def test_admin_create_redacts_secret_and_audits_cleanly(cleanup) -> None:
client = _client(cleanup, ADMIN)
response = client.post("/datasources", json=_body())
assert response.status_code == 200
data = response.json()["data"]
row = _stored(data["id"])
ciphertext = row.secret_ciphertext
assert SENTINEL not in ciphertext and decrypt_secret(ciphertext) == SENTINEL
assert data["secret_configured"] is True
assert set(data) == {
"id", "name", "description", "kind", "engine", "host", "port", "database_name",
"username", "secret_configured", "read_only_intent", "enabled", "last_test_category",
"last_test_at", "last_test_message", "created_at", "updated_at", "circuit_state",
"circuit_opened_at", "circuit_open_until", "circuit_failure_window_seconds",
"circuit_failure_threshold", "circuit_open_cooldown_seconds",
} # fmt: skip
assert data["enabled"] is True and data["read_only_intent"] is True
for surface in (response.text, client.get(f"/datasources/{data['id']}").text, client.get("/datasources").text):
assert SENTINEL not in surface
assert ciphertext not in surface
assert "secret_ciphertext" not in surface and "password" not in surface
events = _audit_events(data["id"], "datasource.create")
assert len(events) == 1
payload = events[0].payload
assert payload == {"id": data["id"], "name": data["name"], "engine": "postgresql"}
dumped = json.dumps(payload) + events[0].idempotency_key
assert SENTINEL not in dumped and ciphertext not in dumped and "synthetic_user" not in dumped
def test_create_validation(cleanup) -> None:
client = _client(cleanup, ADMIN)
bad_bodies = [
_body(kind="api"),
_body(engine="oracle"),
_body(password=""),
_body(password=" "),
_body(port=0),
_body(port=70000),
_body(host=" "),
_body(host=""),
_body(tenant_id="other-tenant"),
_body(enabled=False),
{k: v for k, v in _body().items() if k != "password"},
]
for body in bad_bodies:
response = client.post("/datasources", json=body)
assert response.status_code == 400, body.get("name")
assert response.json()["error"]["code"] == 40000
assert SENTINEL not in response.text
listing = client.get("/datasources").json()["data"]["items"]
assert not [i for i in listing if i["name"].startswith(NAME_PREFIX)]
def test_duplicate_name_is_409(cleanup) -> None:
client = _client(cleanup, ADMIN)
first = _create(client)
response = client.post("/datasources", json=_body(name=first["name"]))
assert response.status_code == 409
assert response.json()["error"]["details"]["reason"] == "duplicate_name"
def test_unknown_and_foreign_tenant_ids_are_404(cleanup) -> None:
client = _client(cleanup, ADMIN)
foreign_name = f"{NAME_PREFIX}foreign"
session = get_session_factory()()
try:
set_tenant(session, "other-tenant-api-test")
row = DataSource(
tenant_id="other-tenant-api-test",
name=foreign_name,
kind="database",
engine="postgresql",
host="h.invalid",
port=5432,
database_name="d",
username="u",
secret_ciphertext="opaque",
)
session.add(row)
session.commit()
foreign_id = str(row.id)
finally:
session.close()
try:
for path in (
f"/datasources/{uuid.uuid4()}",
f"/datasources/{foreign_id}",
f"/datasources/{foreign_id}/references",
"/datasources/not-a-uuid",
):
response = client.get(path)
assert response.status_code == 404, path
assert client.patch(f"/datasources/{foreign_id}", json={"description": "x"}).status_code == 404
assert client.post(f"/datasources/{foreign_id}/disable").status_code == 404
assert client.post(f"/datasources/{foreign_id}/test").status_code == 404
assert foreign_id not in [i["id"] for i in client.get("/datasources").json()["data"]["items"]]
finally:
cleaner = get_session_factory()()
try:
set_tenant(cleaner, "other-tenant-api-test")
cleaner.execute(delete(DataSource).where(DataSource.name == foreign_name))
cleaner.commit()
finally:
cleaner.close()
# --- update ------------------------------------------------------------------------------
def test_patch_keeps_or_replaces_password(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
before = _stored(ds_id)
kept = client.patch(f"/datasources/{ds_id}", json={"description": "changed", "port": 5433})
assert kept.status_code == 200
assert kept.json()["data"]["description"] == "changed"
after = _stored(ds_id)
assert after.secret_ciphertext == before.secret_ciphertext
assert after.updated_at > before.updated_at
blank = client.patch(f"/datasources/{ds_id}", json={"password": "", "host": "other.invalid"})
assert blank.status_code == 200
assert _stored(ds_id).secret_ciphertext == before.secret_ciphertext
replaced = client.patch(f"/datasources/{ds_id}", json={"password": OTHER_SENTINEL})
assert replaced.status_code == 200
new_cipher = _stored(ds_id).secret_ciphertext
assert new_cipher != before.secret_ciphertext
assert decrypt_secret(new_cipher) == OTHER_SENTINEL
for surface in (kept.text, blank.text, replaced.text):
assert SENTINEL not in surface and OTHER_SENTINEL not in surface and new_cipher not in surface
events = _audit_events(ds_id, "datasource.update")
assert len(events) == 3
dumped = json.dumps([e.payload for e in events])
assert OTHER_SENTINEL not in dumped and new_cipher not in dumped and "synthetic_user" not in dumped
@pytest.mark.parametrize(
"change",
[
{"host": "changed.invalid"},
{"port": 5439},
{"database_name": "other_db"},
{"username": "other_user"},
{"engine": "mysql"},
{"password": OTHER_SENTINEL},
],
)
def test_patch_connection_change_clears_last_test(cleanup, monkeypatch, change) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
_fake_probe(monkeypatch, ProbeCategory.AUTH_FAILED)
client.post(f"/datasources/{ds_id}/test")
tested = _stored(ds_id)
assert tested.last_test_category == "auth_failed" and tested.last_test_at is not None
response = client.patch(f"/datasources/{ds_id}", json=change)
assert response.status_code == 200
data = response.json()["data"]
assert data["last_test_category"] is None
assert data["last_test_at"] is None
assert data["last_test_message"] is None
stored = _stored(ds_id)
assert stored.last_test_category is None
assert stored.last_test_at is None
assert stored.last_test_message is None
assert stored.updated_at > tested.updated_at
def test_patch_without_connection_change_keeps_last_test(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
_fake_probe(monkeypatch, ProbeCategory.AUTH_FAILED)
client.post(f"/datasources/{ds_id}/test")
tested = _stored(ds_id)
new_name = f"{NAME_PREFIX}renamed"
for body in (
{"name": new_name},
{"description": "edited", "read_only_intent": False},
{"password": " "}, # blank keeps the stored password and the test result
{"host": created["host"], "port": created["port"]}, # same values: not a change
):
response = client.patch(f"/datasources/{ds_id}", json=body)
assert response.status_code == 200
assert response.json()["data"]["last_test_category"] == "auth_failed"
stored = _stored(ds_id)
assert stored.last_test_category == "auth_failed"
assert stored.last_test_message == tested.last_test_message
assert stored.last_test_at == tested.last_test_at
def test_patch_rejections(cleanup) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
other = _create(client)
ds_id = created["id"]
for body in (
{"kind": "api"},
{"engine": "oracle"},
{"tenant_id": "other"},
{"enabled": False},
{"name": None},
{"port": 0},
):
response = client.patch(f"/datasources/{ds_id}", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
clash = client.patch(f"/datasources/{ds_id}", json={"name": other["name"]})
assert clash.status_code == 409
assert client.patch(f"/datasources/{ds_id}", json={"engine": "mysql"}).json()["data"]["engine"] == "mysql"
# --- disable, references -----------------------------------------------------------------
def test_disable_blocks_test_without_network_and_stays_readable(cleanup, no_network) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
before = _stored(ds_id)
disabled = client.post(f"/datasources/{ds_id}/disable")
assert disabled.status_code == 200 and disabled.json()["data"]["enabled"] is False
assert _stored(ds_id).updated_at > before.updated_at
assert client.get(f"/datasources/{ds_id}").json()["data"]["enabled"] is False
assert client.delete(f"/datasources/{ds_id}").status_code == 405
response = client.post(f"/datasources/{ds_id}/test")
assert response.status_code == 409
error = response.json()["error"]
assert error["details"]["reason"] == "disabled"
assert _stored(ds_id).last_test_category is None
operator = _client(cleanup, OPERATOR).post(f"/datasources/{ds_id}/test")
assert operator.status_code == 403
events = _audit_events(ds_id, "datasource.disable")
assert len(events) == 1 and events[0].payload["id"] == ds_id
def test_references_are_empty(cleanup) -> None:
created = _create(_client(cleanup, ADMIN))
response = _client(cleanup, ADMIN).get(f"/datasources/{created['id']}/references")
assert response.status_code == 200
assert response.json()["data"] == {"id": created["id"], "items": []}
# --- connection test -------------------------------------------------------------------------
def _fake_probe(monkeypatch: pytest.MonkeyPatch, category: ProbeCategory) -> list[ProbeTarget]:
seen: list[ProbeTarget] = []
def _probe(target: ProbeTarget, **_kwargs) -> ProbeResult:
seen.append(target)
return ProbeResult(category=category, message=f"fixed text for {category.value}")
monkeypatch.setattr(service, "probe_datasource", _probe)
return seen
def test_connection_test_success_uses_saved_target_only(cleanup, monkeypatch) -> None:
admin = _client(cleanup, ADMIN)
created = _create(admin)
seen = _fake_probe(monkeypatch, ProbeCategory.SUCCESS)
before = _stored(created["id"])
# Only admin may test. The probe sees the saved target and the decrypted password.
response = _client(cleanup, ADMIN).post(f"/datasources/{created['id']}/test")
assert response.status_code == 200
data = response.json()["data"]
assert response.json()["success"] is True
assert data["category"] == "success" and data["message"] == "fixed text for success"
assert [(t.host, t.port, t.database, t.username, t.engine) for t in seen] == [
("db.synthetic.invalid", 5432, "synthetic_db", "synthetic_user", "postgresql")
]
assert seen[0].password == SENTINEL
assert SENTINEL not in response.text
after = _stored(created["id"])
assert after.last_test_category == "success"
assert after.last_test_message == "fixed text for success"
assert after.last_test_at is not None and after.updated_at > before.updated_at
events = _audit_events(created["id"], "datasource.test")
assert len(events) == 1
assert events[0].payload == {
"id": created["id"], "name": created["name"], "engine": "postgresql", "category": "success"
} # fmt: skip
def test_connection_test_rejects_any_target_in_body(cleanup, monkeypatch) -> None:
admin = _client(cleanup, ADMIN)
created = _create(admin)
seen = _fake_probe(monkeypatch, ProbeCategory.SUCCESS)
for body in ({"host": "evil.invalid"}, {"url": "postgresql://u:p@h/db"}, {"tenant_id": "x"}, {"port": 1}):
response = admin.post(f"/datasources/{created['id']}/test", json=body)
assert response.status_code == 400 and response.json()["error"]["code"] == 40000
assert seen == []
@pytest.mark.parametrize(
("category", "retryable"),
[
(ProbeCategory.AUTH_FAILED, False),
(ProbeCategory.TIMEOUT, True),
(ProbeCategory.UNREACHABLE, True),
(ProbeCategory.REJECTED, False),
],
)
def test_connection_test_failure_envelope(cleanup, monkeypatch, category, retryable) -> None:
admin = _client(cleanup, ADMIN)
created = _create(admin)
_fake_probe(monkeypatch, category)
response = admin.post(f"/datasources/{created['id']}/test")
assert response.status_code == 400
body = response.json()
assert body["success"] is False
error = body["error"]
assert error["code"] == 40000
assert error["message"] == f"fixed text for {category.value}"
assert error["details"] == {"category": category.value}
assert error["retryable"] is retryable
assert SENTINEL not in response.text
stored = _stored(created["id"])
assert stored.last_test_category == category.value
assert stored.last_test_message == f"fixed text for {category.value}"
assert stored.last_test_at is not None
events = _audit_events(created["id"], "datasource.test")
assert [e.payload["category"] for e in events] == [category.value]
# --- live PostgreSQL through the API --------------------------------------------------------------
def test_live_postgres_success_and_wrong_password(cleanup) -> None:
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
if any(not env.get(f"WATCHMAN_TEST_PG_{k}") for k in keys):
pytest.skip("WATCHMAN_TEST_PG_* env not configured")
live = dict(
host=env["WATCHMAN_TEST_PG_HOST"],
port=int(env["WATCHMAN_TEST_PG_PORT"]),
database_name=env["WATCHMAN_TEST_PG_DATABASE"],
username=env["WATCHMAN_TEST_PG_USER"],
)
precheck = probe_datasource(
ProbeTarget(
engine="postgresql",
host=live["host"],
port=live["port"],
database=live["database_name"],
username=live["username"],
password=env["WATCHMAN_TEST_PG_PASSWORD"],
)
)
if precheck.category is not ProbeCategory.SUCCESS:
pytest.skip(f"live postgres not available ({precheck.category.value})")
admin = _client(cleanup, ADMIN)
good = _create(admin, password=env["WATCHMAN_TEST_PG_PASSWORD"], **live)
ok = admin.post(f"/datasources/{good['id']}/test")
assert ok.status_code == 200
assert ok.json()["data"]["category"] == "success"
assert _stored(good["id"]).last_test_category == "success"
bad = _create(admin, password=SENTINEL, **live)
failed = admin.post(f"/datasources/{bad['id']}/test")
assert failed.status_code == 400
error = failed.json()["error"]
assert error["details"]["category"] == "auth_failed"
assert error["retryable"] is False
assert env["WATCHMAN_TEST_PG_PASSWORD"] not in ok.text + failed.text
assert SENTINEL not in failed.text
assert _stored(bad["id"]).last_test_category == "auth_failed"
@@ -0,0 +1,677 @@
"""Datasource enable, draft test and circuit breaker tests (M03 S6, D23).
Why: the circuit decides whether a saved source may be probed at all, so open/close
timing, which probes count, and the draft-test isolation need executable proof.
Boundary: real platform Postgres through the API like test_datasource_api; probes are
fakes and time is frozen by replacing the service clock. Rows created here are removed
by the shared cleanup fixture (audit events are append-only and kept).
Depends on test_datasource_api helpers, the datasource service and the probe module.
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from fastapi.testclient import TestClient
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import ( # noqa: F401
ADMIN,
NAME_PREFIX,
OPERATOR,
SENTINEL,
_audit_events,
_body,
_client,
_create,
_stored,
cleanup,
datasource_key,
)
from watchman.core.config import get_settings
from watchman.core.db import get_session_factory, set_tenant
from watchman.datasources import ProbeCategory, ProbeResult, ProbeTarget, probe_datasource
from watchman.datasources import probe as probe_module
from watchman.services import datasources as service
T0 = datetime(2030, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
class Clock:
"""A controllable replacement for service._now."""
def __init__(self) -> None:
self.now = T0
def advance(self, seconds: float) -> None:
self.now += timedelta(seconds=seconds)
def __call__(self) -> datetime:
return self.now
@pytest.fixture
def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
fake = Clock()
monkeypatch.setattr(service, "_now", fake)
return fake
class FakeProbe:
"""Records targets; returns the queued category (the last one repeats)."""
def __init__(self, *categories: ProbeCategory) -> None:
self.categories = list(categories) or [ProbeCategory.SUCCESS]
self.targets: list[ProbeTarget] = []
def __call__(self, target: ProbeTarget, **_kwargs) -> ProbeResult:
self.targets.append(target)
category = self.categories.pop(0) if len(self.categories) > 1 else self.categories[0]
return ProbeResult(category=category, message=f"fixed text for {category.value}")
def _install(monkeypatch: pytest.MonkeyPatch, *categories: ProbeCategory) -> FakeProbe:
fake = FakeProbe(*categories)
monkeypatch.setattr(service, "probe_datasource", fake)
return fake
def _draft_body(**overrides) -> dict:
values = {
"engine": "postgresql",
"host": "draft.synthetic.invalid",
"port": 5432,
"database_name": "draft_db",
"username": "draft_user",
"password": "draft-pw-not-a-credential",
}
values.update(overrides)
return values
def _test(client: TestClient, ds_id: str):
return client.post(f"/datasources/{ds_id}/test")
# --- enable --------------------------------------------------------------------------------
def test_enable_after_disable_restores_testing(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
assert client.post(f"/datasources/{ds_id}/disable").json()["data"]["enabled"] is False
refused = _test(client, ds_id)
assert refused.status_code == 409
assert refused.json()["error"]["details"]["reason"] == "disabled"
assert fake.targets == []
enabled = client.post(f"/datasources/{ds_id}/enable")
assert enabled.status_code == 200
assert enabled.json()["data"]["enabled"] is True
assert _stored(ds_id).enabled is True
assert _test(client, ds_id).status_code == 200
assert len(fake.targets) == 1
assert len(_audit_events(ds_id, "datasource.enable")) == 1
def test_enable_does_not_clear_open_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
assert _stored(ds_id).circuit_state == "open"
client.post(f"/datasources/{ds_id}/disable")
data = client.post(f"/datasources/{ds_id}/enable").json()["data"]
assert data["enabled"] is True and data["circuit_state"] == "open"
assert _test(client, ds_id).json()["error"]["details"]["reason"] == "circuit_open"
# --- draft test ----------------------------------------------------------------------------
def test_draft_test_writes_no_last_test_and_no_circuit_accounting(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.AUTH_FAILED)
before = _stored(ds_id)
for _ in range(5): # more than the threshold of 3
response = client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id))
assert response.status_code == 400
assert response.json()["error"]["details"] == {"category": "auth_failed"}
after = _stored(ds_id)
assert after.last_test_category is None and after.last_test_at is None
assert after.last_test_message is None
assert after.circuit_state == "closed" and after.circuit_failure_count == 0
assert after.circuit_window_started_at is None and after.circuit_opened_at is None
assert after.updated_at == before.updated_at
assert len(fake.targets) == 5
# The draft values are what was probed, not the saved row.
assert fake.targets[0].host == "draft.synthetic.invalid"
assert _audit_events(ds_id, "datasource.test") == []
def test_draft_test_success_and_stored_password_fallback(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
explicit = client.post("/datasources/test-draft", json=_draft_body())
assert explicit.status_code == 200
assert explicit.json()["data"]["category"] == "success"
assert fake.targets[-1].password == "draft-pw-not-a-credential"
for blank in (None, "", " "):
body = _draft_body(datasource_id=ds_id)
if blank is None:
del body["password"]
else:
body["password"] = blank
response = client.post("/datasources/test-draft", json=body)
assert response.status_code == 200, body
assert fake.targets[-1].password == SENTINEL
assert SENTINEL not in response.text
assert _stored(ds_id).last_test_at is None
def test_draft_test_validation_and_tenant_scope(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
for body in (
_draft_body(password=""), # create-style, no stored secret to fall back on
{k: v for k, v in _draft_body().items() if k != "password"},
_draft_body(engine="oracle"),
_draft_body(kind="api"),
_draft_body(host=" "),
_draft_body(tenant_id="other"),
_draft_body(password="x", url="postgresql://u:p@h/db"),
):
response = client.post("/datasources/test-draft", json=body)
assert response.status_code == 400, body
assert response.json()["error"]["code"] == 40000
assert fake.targets == []
for missing in (str(uuid.uuid4()), "not-a-uuid"):
response = client.post(
"/datasources/test-draft", json=_draft_body(password="", datasource_id=missing)
)
assert response.status_code == 404
assert ds_id # the real row is untouched by the failed lookups
def test_draft_test_ignores_disabled_and_open_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable")
assert _stored(ds_id).circuit_state == "open"
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
response = client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id, password=""))
assert response.status_code == 200
assert len(fake.targets) == 1
def test_draft_audit_has_no_target_or_secret(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.SUCCESS)
client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id, password=""))
events = _audit_events(ds_id, "datasource.test_draft")
assert len(events) == 1
assert events[0].payload == {"engine": "postgresql", "category": "success", "id": ds_id}
dumped = json.dumps(events[0].payload) + events[0].idempotency_key
assert SENTINEL not in dumped and "draft.synthetic.invalid" not in dumped
# --- circuit breaker ----------------------------------------------------------------------------
def test_failures_open_circuit_then_reject_then_auto_close(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
fake = _install(monkeypatch, ProbeCategory.TIMEOUT)
for attempt in (1, 2, 3):
response = _test(client, ds_id)
assert response.status_code == 400
stored = _stored(ds_id)
# last_test is persisted on every saved test, including the one that opens the circuit.
assert stored.last_test_category == "timeout"
assert stored.last_test_at == clock.now
assert stored.circuit_failure_count == attempt
assert stored.circuit_state == ("open" if attempt == 3 else "closed")
clock.advance(1)
assert len(fake.targets) == 3
opened = _stored(ds_id)
assert opened.enabled is True # never auto-disabled
assert opened.circuit_opened_at == T0 + timedelta(seconds=2)
assert len(_audit_events(ds_id, "datasource.circuit_open")) == 1
data = client.get(f"/datasources/{ds_id}").json()["data"]
assert data["circuit_state"] == "open"
assert data["circuit_open_until"] == (opened.circuit_opened_at + timedelta(seconds=600)).isoformat()
rejected = _test(client, ds_id)
assert rejected.status_code == 409
assert rejected.json()["error"]["details"]["reason"] == "circuit_open"
assert len(fake.targets) == 3 # refused before any probe
# Still inside the cooldown: refused. Past it: assert_usable closes the circuit.
clock.advance(590)
assert _test(client, ds_id).status_code == 409
clock.advance(20)
fake_ok = _install(monkeypatch, ProbeCategory.SUCCESS)
assert _test(client, ds_id).status_code == 200
assert len(fake_ok.targets) == 1
closed = _stored(ds_id)
assert closed.circuit_state == "closed" and closed.circuit_opened_at is None
assert closed.circuit_failure_count == 0 and closed.circuit_window_started_at is None
assert closed.last_test_category == "success"
data = client.get(f"/datasources/{ds_id}").json()["data"]
assert data["circuit_state"] == "closed" and data["circuit_open_until"] is None
def test_auth_failed_counts_toward_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.AUTH_FAILED)
for _ in range(3):
assert _test(client, ds_id).status_code == 400
assert _stored(ds_id).circuit_state == "open"
assert _test(client, ds_id).status_code == 409
def test_rejected_and_unreachable_also_count(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.REJECTED, ProbeCategory.UNREACHABLE, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
assert _stored(ds_id).circuit_state == "open"
def test_success_resets_failure_count(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT, ProbeCategory.TIMEOUT, ProbeCategory.SUCCESS, ProbeCategory.TIMEOUT)
for _ in range(2):
_test(client, ds_id)
assert _stored(ds_id).circuit_failure_count == 2
_test(client, ds_id) # success
reset = _stored(ds_id)
assert reset.circuit_failure_count == 0 and reset.circuit_window_started_at is None
_test(client, ds_id) # one failure again
final = _stored(ds_id)
assert final.circuit_failure_count == 1 and final.circuit_state == "closed"
def test_failures_outside_window_do_not_accumulate(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
assert client.patch(
f"/datasources/{ds_id}", json={"circuit_failure_window_seconds": 60}
).status_code == 200
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
_test(client, ds_id)
clock.advance(61) # first window expired
_test(client, ds_id)
stored = _stored(ds_id)
assert stored.circuit_failure_count == 1 and stored.circuit_state == "closed"
assert stored.circuit_window_started_at == clock.now
def test_circuit_parameters_persist_and_apply(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
assert created["circuit_failure_window_seconds"] == 300
assert created["circuit_failure_threshold"] == 3
assert created["circuit_open_cooldown_seconds"] == 600
assert created["circuit_state"] == "closed"
response = client.patch(
f"/datasources/{ds_id}",
json={
"circuit_failure_window_seconds": 120,
"circuit_failure_threshold": 2,
"circuit_open_cooldown_seconds": 30,
},
)
assert response.status_code == 200
data = response.json()["data"]
assert (
data["circuit_failure_window_seconds"],
data["circuit_failure_threshold"],
data["circuit_open_cooldown_seconds"],
) == (120, 2, 30)
stored = _stored(ds_id)
assert (stored.circuit_failure_window_seconds, stored.circuit_failure_threshold) == (120, 2)
assert stored.circuit_open_cooldown_seconds == 30
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
_test(client, ds_id) # threshold 2 opens it
assert _stored(ds_id).circuit_state == "open"
clock.advance(31) # custom cooldown of 30 s has passed
_install(monkeypatch, ProbeCategory.SUCCESS)
assert _test(client, ds_id).status_code == 200
@pytest.mark.parametrize(
"change",
[
{"circuit_failure_window_seconds": 0},
{"circuit_failure_window_seconds": 86401},
{"circuit_failure_threshold": 0},
{"circuit_failure_threshold": 101},
{"circuit_open_cooldown_seconds": 0},
{"circuit_open_cooldown_seconds": 86401},
{"circuit_open_cooldown_seconds": "10"},
{"circuit_failure_threshold": 2.5},
{"circuit_failure_threshold": None},
{"circuit_state": "closed"},
{"circuit_failure_count": 0},
],
)
def test_circuit_parameter_validation(cleanup, change) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
response = client.patch(f"/datasources/{ds_id}", json=change)
assert response.status_code == 400, change
assert response.json()["error"]["code"] == 40000
stored = _stored(ds_id)
assert (stored.circuit_failure_window_seconds, stored.circuit_failure_threshold) == (300, 3)
assert stored.circuit_open_cooldown_seconds == 600
def test_circuit_parameter_boundaries_accepted(cleanup) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
for change in (
{"circuit_failure_window_seconds": 1, "circuit_failure_threshold": 1, "circuit_open_cooldown_seconds": 1},
{"circuit_failure_window_seconds": 86400, "circuit_failure_threshold": 100, "circuit_open_cooldown_seconds": 86400},
):
assert client.patch(f"/datasources/{ds_id}", json=change).status_code == 200
def test_circuit_config_change_keeps_last_test_and_state(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
client.patch(f"/datasources/{ds_id}", json={"circuit_failure_threshold": 5})
stored = _stored(ds_id)
assert stored.last_test_category == "timeout" and stored.circuit_failure_count == 1
def test_disable_is_decoupled_from_circuit(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable")
stored = _stored(ds_id)
assert stored.enabled is False
assert stored.circuit_failure_count == 1 and stored.circuit_state == "closed"
def test_disabled_check_wins_over_circuit_reason(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable")
refused = _test(client, ds_id)
assert refused.status_code == 409
assert refused.json()["error"]["details"]["reason"] == "disabled"
# --- assert_usable and the usable list -----------------------------------------------------------
def test_assert_usable_service_contract(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
with pytest.raises(service.ConflictError) as raised:
service.assert_usable(session, ds_id) # by id
assert raised.value.details["reason"] == "circuit_open"
row = service.get_datasource(session, ds_id)
with pytest.raises(service.ConflictError):
service.assert_usable(session, row) # by row
clock.advance(601)
assert service.assert_usable(session, row) is row
assert row.circuit_state == "closed" and row.circuit_opened_at is None
assert row.circuit_failure_count == 0
row.enabled = False
with pytest.raises(service.ConflictError) as disabled:
service.assert_usable(session, row)
assert disabled.value.details["reason"] == "disabled"
session.rollback()
finally:
session.close()
def test_record_probe_outcome_can_skip_last_test(cleanup, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
row = service.get_datasource(session, ds_id)
failure = ProbeResult(ProbeCategory.AUTH_FAILED, "authentication failed")
assert service.record_probe_outcome(session, row, failure, update_last_test=False) is False
assert row.last_test_category is None and row.circuit_failure_count == 1
service.record_probe_outcome(session, row, failure)
assert row.last_test_category == "auth_failed"
assert service.record_probe_outcome(session, row, failure) is True
assert row.circuit_state == "open"
session.rollback()
finally:
session.close()
def test_usable_list_filters_disabled_and_open_sources(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
good = _create(client)["id"]
disabled = _create(client)["id"]
tripped = _create(client)["id"]
client.post(f"/datasources/{disabled}/disable")
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, tripped)
def ids(path: str) -> set[str]:
response = client.get(path)
assert response.status_code == 200
return {item["id"] for item in response.json()["data"]["items"]}
everything = ids("/datasources")
assert {good, disabled, tripped} <= everything
usable = ids("/datasources?usable=true")
assert good in usable and disabled not in usable and tripped not in usable
assert ids("/datasources?usable=false") == everything
clock.advance(601) # cooldown over: usable again, and the circuit is persisted closed
assert tripped in ids("/datasources?usable=true")
assert _stored(tripped).circuit_state == "closed"
def test_detail_get_closes_elapsed_cooldown(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
still_open = client.get(f"/datasources/{ds_id}").json()["data"]
assert still_open["circuit_state"] == "open"
assert still_open["circuit_open_until"] is not None
clock.advance(601) # default cooldown is 600s
detail = client.get(f"/datasources/{ds_id}")
assert detail.status_code == 200
data = detail.json()["data"]
assert data["circuit_state"] == "closed"
assert data["circuit_opened_at"] is None and data["circuit_open_until"] is None
stored = _stored(ds_id)
assert stored.circuit_state == "closed" and stored.circuit_opened_at is None
assert stored.circuit_failure_count == 0
def test_plain_list_closes_elapsed_cooldown(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
_install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(3):
_test(client, ds_id)
client.post(f"/datasources/{ds_id}/disable") # disabled rows are normalized too
clock.advance(601)
items = client.get("/datasources").json()["data"]["items"]
item = next(entry for entry in items if entry["id"] == ds_id)
assert item["circuit_state"] == "closed"
assert item["circuit_opened_at"] is None and item["circuit_open_until"] is None
assert _stored(ds_id).circuit_state == "closed"
# --- secrecy and validation ---------------------------------------------------------------------
def test_public_json_never_contains_password_or_ciphertext(cleanup, monkeypatch, clock) -> None:
client = _client(cleanup, ADMIN)
created = _create(client)
ds_id = created["id"]
ciphertext = _stored(ds_id).secret_ciphertext
_install(monkeypatch, ProbeCategory.AUTH_FAILED)
surfaces = [json.dumps(created)]
for _ in range(3):
surfaces.append(_test(client, ds_id).text)
surfaces.append(_test(client, ds_id).text) # circuit_open conflict
surfaces.append(client.get(f"/datasources/{ds_id}").text)
surfaces.append(client.get("/datasources").text)
surfaces.append(client.get("/datasources?usable=true").text)
surfaces.append(client.post(f"/datasources/{ds_id}/disable").text)
surfaces.append(client.post(f"/datasources/{ds_id}/enable").text)
surfaces.append(client.post("/datasources/test-draft", json=_draft_body(datasource_id=ds_id, password="")).text)
for surface in surfaces:
assert SENTINEL not in surface and ciphertext not in surface
assert "secret_ciphertext" not in surface and '"password"' not in surface
for event in _audit_events(ds_id, "datasource.circuit_open"):
dumped = json.dumps(event.payload) + event.idempotency_key
assert SENTINEL not in dumped and ciphertext not in dumped and "synthetic_user" not in dumped
def test_host_is_required_only(cleanup) -> None:
client = _client(cleanup, ADMIN)
for blank in ("", " ", "\t "):
response = client.post("/datasources", json=_body(host=blank))
assert response.status_code == 400, repr(blank)
assert response.json()["error"]["code"] == 40000
# No format check any more: non-empty unusual strings are accepted and stored trimmed.
for index, host in enumerate(("my host.example", "postgres://u:p@h/db", " padded.example ", "db_01/√")):
created = _create(client, host=host, name=f"{NAME_PREFIX}host-{index}")
assert created["host"] == host.strip()
too_long = client.post("/datasources", json=_body(host="h" * 256))
assert too_long.status_code == 400
ds_id = _create(client)["id"]
assert client.patch(f"/datasources/{ds_id}", json={"host": "weird host!"}).status_code == 200
assert client.patch(f"/datasources/{ds_id}", json={"host": " "}).status_code == 400
def test_enable_unknown_and_foreign_ids_are_404(cleanup) -> None:
client = _client(cleanup, ADMIN)
assert client.post(f"/datasources/{uuid.uuid4()}/enable").status_code == 404
assert client.post("/datasources/not-a-uuid/enable").status_code == 404
assert _client(cleanup, OPERATOR).post(f"/datasources/{uuid.uuid4()}/enable").status_code == 403
# --- probe retry ----------------------------------------------------------------------------------
def _target() -> ProbeTarget:
return ProbeTarget(
engine="postgresql", host="h.invalid", port=5432, database="d", username="u", password="p"
)
@pytest.mark.parametrize(
("first", "second", "calls", "expected"),
[
(ProbeCategory.TIMEOUT, ProbeCategory.SUCCESS, 2, ProbeCategory.SUCCESS),
(ProbeCategory.UNREACHABLE, ProbeCategory.SUCCESS, 2, ProbeCategory.SUCCESS),
(ProbeCategory.TIMEOUT, ProbeCategory.TIMEOUT, 2, ProbeCategory.TIMEOUT),
(ProbeCategory.AUTH_FAILED, ProbeCategory.SUCCESS, 1, ProbeCategory.AUTH_FAILED),
(ProbeCategory.REJECTED, ProbeCategory.SUCCESS, 1, ProbeCategory.REJECTED),
(ProbeCategory.SUCCESS, ProbeCategory.TIMEOUT, 1, ProbeCategory.SUCCESS),
],
)
def test_probe_retries_only_timeout_and_unreachable_once(monkeypatch, first, second, calls, expected) -> None:
queue = [first, second]
seen: list[int] = []
def _connector(_target, _timeout):
seen.append(1)
return queue.pop(0)
monkeypatch.setitem(probe_module._CONNECTORS, "postgresql", _connector)
result = probe_datasource(_target(), max_attempts=2)
assert result.category is expected
assert len(seen) == calls
def test_probe_default_is_single_attempt_and_cap_is_respected(monkeypatch) -> None:
seen: list[int] = []
def _connector(_target, _timeout):
seen.append(1)
return ProbeCategory.TIMEOUT
monkeypatch.setitem(probe_module._CONNECTORS, "postgresql", _connector)
probe_datasource(_target())
assert len(seen) == 1
seen.clear()
probe_datasource(_target(), max_attempts=5)
assert len(seen) == 5 # callers (settings) cap attempts at 2; the function obeys its argument
def test_service_passes_configured_timeout_and_attempts(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create(client)["id"]
captured: dict = {}
def _probe(target, **kwargs):
captured.update(kwargs)
return ProbeResult(ProbeCategory.SUCCESS, "ok")
monkeypatch.setattr(service, "probe_datasource", _probe)
monkeypatch.setenv("WATCHMAN_DATASOURCE_PROBE_TIMEOUT_SECONDS", "2.5")
monkeypatch.setenv("WATCHMAN_DATASOURCE_PROBE_MAX_ATTEMPTS", "1")
from watchman.core.config import reload_settings
reload_settings()
assert _test(client, ds_id).status_code == 200
assert captured == {"timeout_seconds": 2.5, "max_attempts": 1}
@@ -0,0 +1,328 @@
"""Scheduled datasource health check tests (M03 S7, D23).
Why: the health check probes saved sources unattended, so the switch, the cron guard, the
skip rules, the secret hygiene of its audit events and the beat wiring need executable proof.
Boundary: real platform Postgres like test_datasource_circuit; probes are fakes (no network)
and the candidate list is restricted to this run's rows so other dev rows are never touched.
Depends on test_datasource_api helpers, the health check service and the jobs adapter.
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import select
# The imported autouse fixtures (key + cleanup) must be visible in this module.
from test_datasource_api import ( # noqa: F401
ADMIN,
NAME_PREFIX,
SENTINEL,
_audit_events,
_client,
_create,
_stored,
cleanup,
datasource_key,
)
from watchman.core.config import _settings_from_env_map, get_settings, reload_settings
from watchman.core.db import get_session_factory, set_tenant
from watchman.datasources import ProbeCategory, ProbeResult, ProbeTarget
from watchman.jobs.schedule import (
DATASOURCE_HEALTHCHECK_ENTRY,
DATASOURCE_HEALTHCHECK_TASK,
build_beat_schedule,
)
from watchman.models.datasource import DataSource
from watchman.services import datasource_healthcheck as healthcheck
from watchman.services import datasources as service
from watchman.services.cron import is_valid_unix_cron
VALID_CRON = "*/5 * * * *"
class FakeProbe:
"""Records targets; returns the queued category (the last one repeats)."""
def __init__(self, *categories: ProbeCategory) -> None:
self.categories = list(categories) or [ProbeCategory.SUCCESS]
self.targets: list[ProbeTarget] = []
def __call__(self, target: ProbeTarget, **_kwargs) -> ProbeResult:
self.targets.append(target)
category = self.categories.pop(0) if len(self.categories) > 1 else self.categories[0]
return ProbeResult(category=category, message=f"fixed text for {category.value}")
@pytest.fixture(autouse=True)
def only_test_rows(monkeypatch: pytest.MonkeyPatch):
"""Limit the candidate list to rows created by this test run."""
real = healthcheck.list_datasources
def _filtered(session, **kwargs):
return [row for row in real(session, **kwargs) if row.name.startswith(NAME_PREFIX)]
monkeypatch.setattr(healthcheck, "list_datasources", _filtered)
def _install(monkeypatch: pytest.MonkeyPatch, *categories: ProbeCategory) -> FakeProbe:
fake = FakeProbe(*categories)
monkeypatch.setattr(service, "probe_datasource", fake)
return fake
def _settings(*, enabled: bool = True, cron: str = VALID_CRON):
return get_settings().model_copy(
update={"datasource_healthcheck_enabled": enabled, "datasource_healthcheck_cron": cron}
)
def _run(settings=None) -> healthcheck.HealthcheckSummary:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
summary = healthcheck.run_datasource_healthcheck(session, settings=settings or _settings())
session.commit()
return summary
finally:
session.close()
def _create_source(client, label: str) -> str:
return _create(client, host=f"{label}.synthetic.invalid")["id"]
def _open_circuit(ds_id: str) -> None:
session = get_session_factory()()
try:
set_tenant(session, get_settings().tenant_id)
row = session.scalar(select(DataSource).where(DataSource.id == uuid.UUID(ds_id)))
row.circuit_state = "open"
row.circuit_opened_at = datetime.now(timezone.utc) - timedelta(seconds=5)
session.commit()
finally:
session.close()
# --- switch and cron guard -----------------------------------------------------------------
def test_disabled_flag_probes_nothing(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "off")
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run(_settings(enabled=False))
assert summary.skipped_reason == healthcheck.SKIP_DISABLED
assert fake.targets == []
stored = _stored(ds_id)
assert stored.last_test_category is None and stored.last_test_at is None
@pytest.mark.parametrize("cron", ["", "not a cron", "* * * *", "* * * * * *", "*/5 * * * ?", "61 * * * *"])
def test_invalid_cron_is_a_noop(cleanup, monkeypatch, cron) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "badcron")
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run(_settings(cron=cron))
assert summary.skipped_reason == healthcheck.SKIP_INVALID_CRON
assert fake.targets == []
assert _stored(ds_id).last_test_category is None
# --- skip rules ----------------------------------------------------------------------------
def test_disabled_and_open_circuit_sources_are_skipped(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
live = _create_source(client, "live")
disabled = _create_source(client, "disabled")
opened = _create_source(client, "opened")
assert client.post(f"/datasources/{disabled}/disable").status_code == 200
_open_circuit(opened)
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run()
assert [t.host for t in fake.targets] == ["live.synthetic.invalid"]
assert summary.checked == 1 and summary.succeeded == 1
assert _stored(live).last_test_category == "success"
for skipped in (disabled, opened):
assert _stored(skipped).last_test_category is None
# The health check never changes enabled.
assert _stored(disabled).enabled is False and _stored(live).enabled is True
def test_source_disabled_mid_loop_is_skipped(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
first = _create_source(client, "first")
second = _create_source(client, "second")
fake = FakeProbe(ProbeCategory.SUCCESS)
def _probe_then_disable_other(target, **kwargs):
result = fake(target, **kwargs)
# While the first source is probed, the other one gets disabled.
other = second if target.host.startswith("first.") else first
client.post(f"/datasources/{other}/disable")
return result
monkeypatch.setattr(service, "probe_datasource", _probe_then_disable_other)
summary = _run()
assert len(fake.targets) == 1
assert summary.checked == 1 and summary.skipped == 1
# --- outcomes ------------------------------------------------------------------------------
def test_success_updates_last_test(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "ok")
_install(monkeypatch, ProbeCategory.SUCCESS)
summary = _run()
stored = _stored(ds_id)
assert stored.last_test_category == "success"
assert stored.last_test_at is not None
assert stored.circuit_state == "closed"
assert summary.categories == {"success": 1}
assert _audit_events(ds_id, "datasource.healthcheck_failed") == []
def test_failure_updates_last_test_and_audits_without_secrets(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "bad")
_install(monkeypatch, ProbeCategory.AUTH_FAILED)
summary = _run()
stored = _stored(ds_id)
assert stored.last_test_category == "auth_failed"
assert stored.last_test_at is not None
assert stored.enabled is True
assert stored.circuit_failure_count == 1
assert summary.failed == 1 and summary.categories == {"auth_failed": 1}
events = _audit_events(ds_id, "datasource.healthcheck_failed")
assert len(events) == 1
payload = events[0].payload
assert set(payload) == {"id", "name", "engine", "category"}
assert payload["category"] == "auth_failed"
dumped = json.dumps(payload)
for secret in (SENTINEL, "bad.synthetic.invalid", "synthetic_user", "synthetic_db"):
assert secret not in dumped
def test_repeated_failures_open_the_circuit(cleanup, monkeypatch) -> None:
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "flaky")
fake = _install(monkeypatch, ProbeCategory.TIMEOUT)
for _ in range(4):
_run()
assert len(fake.targets) == 3 # the fourth run skips the now-open source
assert _stored(ds_id).circuit_state == "open"
assert len(_audit_events(ds_id, "datasource.circuit_open")) == 1
# --- cron validation and beat wiring -------------------------------------------------------
@pytest.mark.parametrize(
"expression",
["*/5 * * * *", "0 3 * * *", "15,45 8-18 * * 1-5", "0 0 1 * *", " 30 2 * * 0 "],
)
def test_valid_cron_accepted(expression) -> None:
assert is_valid_unix_cron(expression)
@pytest.mark.parametrize(
"expression",
[None, "", " ", "* * * *", "* * * * * *", "@daily", "0 0 L * *", "0 0 * * mon", "0 0 1 * 1"],
)
def test_invalid_cron_rejected(expression) -> None:
# The last case restricts both day fields; croniter ORs them and Celery ANDs them.
assert not is_valid_unix_cron(expression)
def test_beat_schedule_only_when_enabled_and_valid() -> None:
base = get_settings()
def schedule(enabled: bool, cron: str):
return build_beat_schedule(
base.model_copy(
update={"datasource_healthcheck_enabled": enabled, "datasource_healthcheck_cron": cron}
)
)
assert schedule(False, VALID_CRON) == {}
assert schedule(True, "") == {}
assert schedule(True, "nonsense") == {}
entry = schedule(True, "*/5 * * * *")[DATASOURCE_HEALTHCHECK_ENTRY]
assert entry["task"] == DATASOURCE_HEALTHCHECK_TASK
assert entry["schedule"].minute == {m for m in range(0, 60, 5)}
def test_settings_from_env_map_defaults_and_values() -> None:
off = _settings_from_env_map({})
assert off.datasource_healthcheck_enabled is False
assert off.datasource_healthcheck_cron == ""
on = _settings_from_env_map(
{
"WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED": "true",
"WATCHMAN_DATASOURCE_HEALTHCHECK_CRON": " */10 * * * * ",
}
)
assert on.datasource_healthcheck_enabled is True
assert on.datasource_healthcheck_cron == "*/10 * * * *"
# Unknown boolean text stays off.
assert _settings_from_env_map(
{"WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED": "maybe"}
).datasource_healthcheck_enabled is False
def test_celery_app_registers_task_and_schedule_from_env(monkeypatch) -> None:
from watchman.jobs import celery_app as module
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "true")
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_CRON", "*/5 * * * *")
reload_settings()
app = module.create_celery_app()
assert DATASOURCE_HEALTHCHECK_ENTRY in app.conf.beat_schedule
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "false")
reload_settings()
assert module.create_celery_app().conf.beat_schedule == {}
assert DATASOURCE_HEALTHCHECK_TASK in module.celery_app.tasks
assert "watchman.probe.ping" in module.celery_app.tasks
def test_celery_task_runs_check_when_enabled(cleanup, monkeypatch) -> None:
from watchman.jobs.celery_app import datasource_healthcheck
client = _client(cleanup, ADMIN)
ds_id = _create_source(client, "task")
fake = _install(monkeypatch, ProbeCategory.SUCCESS)
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "false")
reload_settings()
assert datasource_healthcheck()["skipped_reason"] == healthcheck.SKIP_DISABLED
assert fake.targets == []
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_ENABLED", "true")
monkeypatch.setenv("WATCHMAN_DATASOURCE_HEALTHCHECK_CRON", VALID_CRON)
reload_settings()
result = datasource_healthcheck()
assert result["skipped_reason"] is None and result["checked"] >= 1
assert _stored(ds_id).last_test_category == "success"
@@ -0,0 +1,338 @@
"""Connector probe tests: category mapping, secret hygiene and live per-engine checks.
Why: the probe is the only code that talks to customer databases, so classification and
"no secret in message/log" must be proven per engine, not assumed from one driver.
Boundary: live tests use isolated databases from .env.local and skip (with a reason)
when an engine is not reachable; they never write to the platform database.
Depends on watchman.datasources and watchman.core.config.merge_layered_env.
"""
from __future__ import annotations
import logging
import socket
import time
import psycopg
import pymssql
import pymysql
import pytest
from watchman.core.config import merge_layered_env
from watchman.datasources import (
ProbeCategory,
ProbeTarget,
UnsupportedDataSourceError,
probe_datasource,
)
from watchman.datasources import probe as probe_module
SENTINEL = "Zq9-sentinel-pw-7f3a1c"
NON_ROUTABLE_HOST = "10.255.255.1"
ENGINES = {
"postgresql": "WATCHMAN_TEST_PG",
"mysql": "WATCHMAN_TEST_MYSQL",
"sqlserver": "WATCHMAN_TEST_SQLSERVER",
}
def _closed_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _target(engine: str, **overrides) -> ProbeTarget:
p = ENGINES[engine]
env = merge_layered_env()
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
if any(not env.get(f"{p}_{k}") for k in keys):
pytest.skip(f"{p}_* env not configured")
base = dict(
engine=engine,
host=env[f"{p}_HOST"],
port=int(env[f"{p}_PORT"]),
database=env[f"{p}_DATABASE"],
username=env[f"{p}_USER"],
password=env[f"{p}_PASSWORD"],
)
base.update(overrides)
return ProbeTarget(**base)
@pytest.fixture(params=sorted(ENGINES))
def engine(request) -> str:
return request.param
@pytest.fixture
def live_engine(engine: str) -> str:
"""Skip (not pass) when the engine cannot be reached with the correct password."""
result = probe_datasource(_target(engine), timeout_seconds=5)
if result.category is not ProbeCategory.SUCCESS:
pytest.skip(f"{engine} live instance not available ({result.category.value})")
return engine
# --- unit: mapping and fixed messages (no network) -----------------------------------
def _raise(exc: BaseException):
def _inner(*_a, **_k):
raise exc
return _inner
def _mysql_timeout() -> BaseException:
err = pymysql.err.OperationalError(2003, "Can't connect to MySQL server (timed out)")
err.__cause__ = TimeoutError("timed out")
return err
@pytest.mark.parametrize(
("engine", "patch_target", "exc", "expected"),
[
("mysql", (pymysql, "connect"), _mysql_timeout(), ProbeCategory.TIMEOUT),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1045, "denied"), ProbeCategory.AUTH_FAILED),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(2003, "refused"), ProbeCategory.UNREACHABLE),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1044, "denied to db"), ProbeCategory.AUTH_FAILED),
# Unknown database / host not allowed: server answered, no credential evidence.
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1049, "unknown db"), ProbeCategory.REJECTED),
("mysql", (pymysql, "connect"), pymysql.err.OperationalError(1130, "host not allowed"), ProbeCategory.REJECTED),
],
)
def test_driver_exception_mapping(monkeypatch, engine, patch_target, exc, expected):
monkeypatch.setattr(patch_target[0], patch_target[1], _raise(exc))
target = ProbeTarget(engine=engine, host="h.invalid", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is expected
# Message is fixed text, never the driver's exception text.
assert str(exc) not in result.message
assert SENTINEL not in result.message
@pytest.mark.parametrize(
("exc", "tcp", "expected"),
[
# SQLSTATE 28xxx is trusted when libpq supplies it, whatever the TCP check says.
(psycopg.errors.InvalidPassword("bad"), "open", ProbeCategory.AUTH_FAILED),
# No SQLSTATE and port open: only positive text evidence counts as auth_failed.
(psycopg.OperationalError('FATAL: password authentication failed for user "u"'), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError("FATAL: Authentication failed"), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError("致命错误: 用户 u Password 认证失败"), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError('FATAL: no pg_hba.conf entry for host'), "open", ProbeCategory.AUTH_FAILED),
(psycopg.OperationalError('FATAL: database "d" does not exist'), "open", ProbeCategory.REJECTED),
(psycopg.OperationalError('致命错误: 数据库 "d" 不存在'), "open", ProbeCategory.REJECTED),
# Unclassifiable text must not be guessed into auth_failed.
(psycopg.OperationalError("connection failed: <unrecognised FATAL>"), "open", ProbeCategory.REJECTED),
# Port open but libpq's own connect timeout fired: a genuine stall.
(psycopg.errors.ConnectionTimeout("connection timeout expired"), "open", ProbeCategory.TIMEOUT),
# Windows libpq waits out the timeout on a refused port; TCP check corrects it.
(psycopg.errors.ConnectionTimeout("connection timeout expired"), "refused", ProbeCategory.UNREACHABLE),
(psycopg.OperationalError("connection failed"), "refused", ProbeCategory.UNREACHABLE),
(psycopg.OperationalError("connection failed"), "timeout", ProbeCategory.TIMEOUT),
],
)
def test_postgresql_exception_mapping(monkeypatch, exc, tcp, expected):
monkeypatch.setattr(psycopg, "connect", _raise(exc))
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: tcp)
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is expected
assert str(exc) not in result.message
@pytest.mark.parametrize(
("exc", "tcp", "expected"),
[
# Login rejected: only the "login failed" text is positive evidence; the code is ignored.
(pymssql.OperationalError((18456, b"Login failed for user")), "open", ProbeCategory.AUTH_FAILED),
(pymssql.OperationalError((18456, b"Cannot open database requested by the login. The login failed.")), "open", ProbeCategory.REJECTED),
(pymssql.OperationalError((18456, b"something else entirely")), "open", ProbeCategory.REJECTED),
# pymssql can carry a stale 18456 on a network failure; TCP evidence must win.
(pymssql.OperationalError((18456, b"Unable to connect: TDS server is unavailable")), "refused", ProbeCategory.UNREACHABLE),
(pymssql.OperationalError((18456, b"TDS server connection timed out")), "timeout", ProbeCategory.TIMEOUT),
# Port accepts TCP but login stalls.
(pymssql.OperationalError(20003, b"TDS server connection timed out"), "open", ProbeCategory.TIMEOUT),
],
)
def test_sqlserver_exception_mapping(monkeypatch, exc, tcp, expected):
monkeypatch.setattr(pymssql, "connect", _raise(exc))
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: tcp)
target = ProbeTarget(engine="sqlserver", host="h", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is expected
assert "Login failed" not in result.message
def test_postgresql_replacement_chars_trigger_gb18030_reclassification(monkeypatch):
"""A UTF8 client mangles zh_CN server text; the GB18030 retry restores the keywords."""
encodings: list[str] = []
def _fake_connect(*_a, **kwargs):
encodings.append(kwargs["client_encoding"])
if kwargs["client_encoding"] == "UTF8":
raise psycopg.OperationalError("\ufffd\ufffd\ufffd: \ufffd\ufffd \ufffd\ufffd\ufffd\ufffd")
raise psycopg.OperationalError("致命错误: 用户 u Password 认证失败")
monkeypatch.setattr(psycopg, "connect", _fake_connect)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "open")
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
assert probe_datasource(target).category is ProbeCategory.AUTH_FAILED
assert encodings == ["UTF8", "GB18030"]
def test_postgresql_no_retry_when_utf8_text_is_already_classified(monkeypatch):
encodings: list[str] = []
def _fake_connect(*_a, **kwargs):
encodings.append(kwargs["client_encoding"])
raise psycopg.OperationalError('FATAL: database "d" does not exist')
monkeypatch.setattr(psycopg, "connect", _fake_connect)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "open")
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
assert probe_datasource(target).category is ProbeCategory.REJECTED
assert encodings == ["UTF8"]
def test_rejected_message_is_fixed():
from watchman.datasources.probe import _result
assert _result(ProbeCategory.REJECTED).message == "data source rejected the connection"
def test_unexpected_driver_error_is_unreachable_without_leaking(monkeypatch):
monkeypatch.setattr(psycopg, "connect", _raise(RuntimeError(f"boom {SENTINEL}")))
target = ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password=SENTINEL)
result = probe_datasource(target)
assert result.category is ProbeCategory.UNREACHABLE
assert SENTINEL not in result.message
@pytest.mark.parametrize(
("kind", "engine"),
[("database", "oracle"), ("api", "postgresql"), ("file", "mysql"), ("database", "")],
)
def test_unsupported_kind_or_engine_opens_no_socket(monkeypatch, kind, engine):
def _forbidden(*_a, **_k):
raise AssertionError("driver must not be called for unsupported targets")
monkeypatch.setattr(psycopg, "connect", _forbidden)
monkeypatch.setattr(pymysql, "connect", _forbidden)
monkeypatch.setattr(pymssql, "connect", _forbidden)
monkeypatch.setattr(socket, "create_connection", _forbidden)
target = ProbeTarget(kind=kind, engine=engine, host="h", port=1, database="d", username="u", password=SENTINEL)
with pytest.raises(UnsupportedDataSourceError) as info:
probe_datasource(target)
assert SENTINEL not in str(info.value)
assert engine not in str(info.value) or engine == ""
def test_probe_target_repr_hides_password():
target = ProbeTarget(engine="mysql", host="h", port=1, database="d", username="u", password=SENTINEL)
assert SENTINEL not in repr(target)
def test_timeout_is_passed_to_driver_connect(monkeypatch):
seen: dict[str, object] = {}
def _capture(*_a, **kwargs):
seen.update(kwargs)
raise psycopg.OperationalError("x")
monkeypatch.setattr(psycopg, "connect", _capture)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "refused")
probe_datasource(
ProbeTarget(engine="postgresql", host="h", port=1, database="d", username="u", password="p"),
timeout_seconds=2.5,
)
assert seen["connect_timeout"] == 3
seen.clear()
monkeypatch.setattr(pymysql, "connect", _capture)
probe_datasource(
ProbeTarget(engine="mysql", host="h", port=1, database="d", username="u", password="p"),
timeout_seconds=2.5,
)
assert seen["connect_timeout"] == 2.5
seen.clear()
monkeypatch.setattr(pymssql, "connect", _capture)
monkeypatch.setattr(probe_module, "_tcp_reachability", lambda *_a: "refused")
probe_datasource(
ProbeTarget(engine="sqlserver", host="h", port=1, database="d", username="u", password="p"),
timeout_seconds=2.5,
)
assert seen["login_timeout"] == 3
# --- live: one engine at a time -------------------------------------------------------
def test_live_success(live_engine, caplog):
caplog.set_level(logging.DEBUG)
target = _target(live_engine)
result = probe_datasource(target, timeout_seconds=5)
assert result.category is ProbeCategory.SUCCESS
# Exact log shape instead of a substring check: dev passwords can be short words that
# legitimately appear in engine names, so "not in" would be both flaky and weak.
assert [r.getMessage() for r in caplog.records if r.name == probe_module.logger.name] == [
f"datasource probe engine={target.engine} host={target.host} port={target.port} "
f"database={target.database} category=success"
]
assert result.message == "connection succeeded"
def test_live_wrong_password(live_engine, caplog):
caplog.set_level(logging.DEBUG)
result = probe_datasource(_target(live_engine, password=SENTINEL), timeout_seconds=5)
assert result.category is ProbeCategory.AUTH_FAILED
assert SENTINEL not in result.message
assert SENTINEL not in caplog.text
def test_live_missing_database_is_rejected_not_auth_failed(live_engine, caplog):
"""Regression: valid credentials + nonexistent database must not read as bad password."""
caplog.set_level(logging.DEBUG)
target = _target(live_engine, database="watchman_no_such_db_s2")
result = probe_datasource(target, timeout_seconds=5)
assert result.category is ProbeCategory.REJECTED
assert result.message == "data source rejected the connection"
assert target.password not in result.message
assert "category=rejected" in caplog.text
assert "\ufffd" not in caplog.text
def test_live_connection_refused_on_closed_port(engine, caplog):
caplog.set_level(logging.DEBUG)
result = probe_datasource(
_target(engine, host="127.0.0.1", port=_closed_port(), password=SENTINEL), timeout_seconds=5
)
assert result.category is ProbeCategory.UNREACHABLE
assert SENTINEL not in result.message
assert SENTINEL not in caplog.text
def test_live_timeout_on_non_routable_address(engine, caplog):
caplog.set_level(logging.DEBUG)
started = time.monotonic()
result = probe_datasource(
_target(engine, host=NON_ROUTABLE_HOST, port=5432, password=SENTINEL), timeout_seconds=2
)
elapsed = time.monotonic() - started
assert SENTINEL not in result.message
assert SENTINEL not in caplog.text
assert elapsed < 15, "probe exceeded the driver timeout bound"
if result.category is not ProbeCategory.TIMEOUT:
# The OS may fail fast (no route) instead of dropping packets; do not call that a pass.
pytest.skip(
f"live timeout not reproducible for {engine}: OS returned "
f"{result.category.value} in {elapsed:.1f}s"
)
assert result.category is ProbeCategory.TIMEOUT
def test_module_logger_name_is_stable():
assert probe_module.logger.name == "watchman.datasources.probe"
@@ -0,0 +1,197 @@
"""RLS and constraint tests for data_sources against local Postgres."""
from __future__ import annotations
import uuid
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.exc import DBAPIError, IntegrityError
from sqlalchemy.orm import Session, sessionmaker
from watchman.core.config import get_settings, reload_settings
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
from watchman.models.datasource import DataSource
# Opaque stand-in; the table stores whatever text it is given, so no real key is needed.
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
@pytest.fixture()
def ds_factory():
reload_settings()
reset_engine()
_ensure_after_begin_listener()
settings = get_settings()
engine = create_engine(settings.database_url, pool_pre_ping=True)
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
created: list[tuple[str, str]] = [] # (tenant_id, name)
yield factory, created, settings
cleanup = factory()
try:
for tenant, name in created:
set_tenant(cleanup, tenant)
cleanup.execute(
text("DELETE FROM data_sources WHERE tenant_id = :t AND name = :n"),
{"t": tenant, "n": name},
)
cleanup.commit()
finally:
cleanup.close()
engine.dispose()
reset_engine()
def _row(tenant_id: str, name: str, **overrides) -> DataSource: # type: ignore[no-untyped-def]
values = dict(
tenant_id=tenant_id,
name=name,
kind="database",
engine="postgresql",
host="127.0.0.1",
port=5432,
database_name="synthetic",
username="synthetic_user",
secret_ciphertext=FAKE_CIPHERTEXT,
)
values.update(overrides)
return DataSource(**values)
def test_data_sources_owner_is_not_app_role() -> None:
reload_settings()
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
with engine.connect() as conn:
owner = conn.execute(
text(
"SELECT tableowner FROM pg_tables "
"WHERE schemaname = 'public' AND tablename = 'data_sources'"
)
).scalar_one()
forced = conn.execute(
text(
"SELECT relrowsecurity, relforcerowsecurity FROM pg_class "
"WHERE relname = 'data_sources'"
)
).one()
engine.dispose()
assert owner != "watchman_app"
assert forced.relrowsecurity is True
assert forced.relforcerowsecurity is True
def test_insert_under_configured_tenant_and_defaults(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-rls-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
row = _row(settings.tenant_id, name)
session.add(row)
session.commit()
stored = session.execute(
text(
"SELECT enabled, read_only_intent, created_at IS NOT NULL AS has_created "
"FROM data_sources WHERE name = :n"
),
{"n": name},
).one()
assert stored.enabled is True
assert stored.read_only_intent is True
assert stored.has_created is True
finally:
session.close()
def test_other_tenant_cannot_see_row(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-iso-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row(settings.tenant_id, name))
session.commit()
finally:
session.close()
other: Session = factory()
try:
set_tenant(other, "other-tenant")
assert other.execute(
text("SELECT count(*) FROM data_sources WHERE name = :n"), {"n": name}
).scalar() == 0
finally:
other.close()
bare: Session = factory()
try:
assert bare.execute(
text("SELECT count(*) FROM data_sources WHERE name = :n"), {"n": name}
).scalar() == 0
finally:
bare.close()
same: Session = factory()
try:
set_tenant(same, settings.tenant_id)
assert same.execute(
text("SELECT count(*) FROM data_sources WHERE name = :n"), {"n": name}
).scalar() == 1
finally:
same.close()
def test_write_for_foreign_tenant_is_rejected(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, _created, settings = ds_factory
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row("other-tenant", f"ds-foreign-{uuid.uuid4().hex[:12]}"))
with pytest.raises(DBAPIError):
session.commit()
session.rollback()
finally:
session.close()
def test_duplicate_name_in_tenant_is_rejected(ds_factory) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-dup-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row(settings.tenant_id, name))
session.commit()
session.add(_row(settings.tenant_id, name))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@pytest.mark.parametrize(
"overrides",
[
{"kind": "api"},
{"engine": "oracle"},
{"port": 0},
{"port": 65536},
],
)
def test_check_constraints_backstop(ds_factory, overrides) -> None: # type: ignore[no-untyped-def]
factory, created, settings = ds_factory
name = f"ds-chk-{uuid.uuid4().hex[:12]}"
created.append((settings.tenant_id, name))
session: Session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(_row(settings.tenant_id, name, **overrides))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
finally:
session.close()
@@ -0,0 +1,138 @@
"""Unit tests for datasource password encryption and kind/engine validation."""
from __future__ import annotations
import pytest
from cryptography.fernet import Fernet
from watchman.core.config import get_settings, reload_settings, settings_as_public_dict
from watchman.core.secrets import (
KEY_ENV_NAME,
SecretDecryptError,
SecretKeyError,
decrypt_secret,
encrypt_secret,
)
from watchman.models.datasource import DataSource, validate_kind_engine
# Unique marker so a leak into messages or repr is detectable; not a real credential.
SENTINEL = "sentinel-7f3a91c2-not-a-real-password"
@pytest.fixture()
def with_key(monkeypatch: pytest.MonkeyPatch):
key = Fernet.generate_key().decode("ascii")
monkeypatch.setenv(KEY_ENV_NAME, key)
reload_settings()
yield key
monkeypatch.undo()
reload_settings()
def test_roundtrip(with_key: str) -> None:
token = encrypt_secret(SENTINEL)
assert SENTINEL not in token
assert decrypt_secret(token) == SENTINEL
def test_encrypt_is_not_deterministic(with_key: str) -> None:
assert encrypt_secret(SENTINEL) != encrypt_secret(SENTINEL)
def test_wrong_key_fails_without_leak(monkeypatch: pytest.MonkeyPatch, with_key: str) -> None:
token = encrypt_secret(SENTINEL)
other_key = Fernet.generate_key().decode("ascii")
monkeypatch.setenv(KEY_ENV_NAME, other_key)
reload_settings()
with pytest.raises(SecretDecryptError) as exc:
decrypt_secret(token)
message = str(exc.value)
assert SENTINEL not in message
assert other_key not in message
assert with_key not in message
def test_garbage_ciphertext_fails(with_key: str) -> None:
with pytest.raises(SecretDecryptError):
decrypt_secret("not-a-fernet-token")
@pytest.mark.parametrize("value", ["", " ", "CHANGE-ME"])
def test_missing_key_names_env_var(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
monkeypatch.setenv(KEY_ENV_NAME, value)
reload_settings()
try:
with pytest.raises(SecretKeyError) as exc:
encrypt_secret(SENTINEL)
assert KEY_ENV_NAME in str(exc.value)
assert SENTINEL not in str(exc.value)
finally:
monkeypatch.undo()
reload_settings()
def test_malformed_key_does_not_echo_key(monkeypatch: pytest.MonkeyPatch) -> None:
bad = "short-bad-key-value"
monkeypatch.setenv(KEY_ENV_NAME, bad)
reload_settings()
try:
with pytest.raises(SecretKeyError) as exc:
encrypt_secret(SENTINEL)
assert bad not in str(exc.value)
assert SENTINEL not in str(exc.value)
assert exc.value.__cause__ is None
assert exc.value.__suppress_context__ is True
finally:
monkeypatch.undo()
reload_settings()
def test_public_settings_exclude_key(with_key: str) -> None:
public = settings_as_public_dict(get_settings())
assert with_key not in repr(public)
assert all("key" not in name for name in public)
assert with_key not in repr(get_settings())
def test_datasource_key_not_required_at_boot() -> None:
from watchman.core.config import REQUIRED_RUNTIME_KEYS
assert KEY_ENV_NAME not in REQUIRED_RUNTIME_KEYS
def test_validate_accepts_supported_values() -> None:
for engine in ("postgresql", "mysql", "sqlserver"):
validate_kind_engine("database", engine)
@pytest.mark.parametrize(
("kind", "engine"),
[
("api", "postgresql"),
("", "postgresql"),
("database", "oracle"),
("database", "PostgreSQL"),
("database", ""),
],
)
def test_validate_rejects_unsupported(kind: str, engine: str) -> None:
with pytest.raises(ValueError):
validate_kind_engine(kind, engine)
def test_model_repr_hides_secret() -> None:
ciphertext = f"gAAAA-{SENTINEL}"
row = DataSource(
tenant_id="t1",
name="src",
kind="database",
engine="postgresql",
host="h",
port=5432,
database_name="d",
username="u",
secret_ciphertext=ciphertext,
)
text = repr(row)
assert SENTINEL not in text
assert "secret" not in text
Generated
+45
View File
@@ -182,6 +182,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
[[package]]
name = "croniter"
version = "6.2.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "python-dateutil" },
]
sdist = { url = "https://files.pythonhosted.org/packages/37/57/2e2a65aee2a70483cb28e2b7e15a072d00a523207593b44400d4717bb100/croniter-6.2.4.tar.gz", hash = "sha256:fc124f751b1b04805c2a04b061898b436b45ab2320b045e1e052ea895de65189", size = 166267, upload-time = "2026-07-10T09:52:59.955Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cd/ba/d678e5bd329646ca51d3c92addbc77804e86d21f4b6b6a027218e6abb010/croniter-6.2.4-py3-none-any.whl", hash = "sha256:8ef3d544107a5c05a150a2d78f8bf5a8eb9c5c4d93405a736b824109574e3f4d", size = 46677, upload-time = "2026-07-10T09:52:58.425Z" },
]
[[package]]
name = "cryptography"
version = "50.0.2"
@@ -561,6 +573,31 @@ crypto = [
{ name = "cryptography" },
]
[[package]]
name = "pymssql"
version = "2.4.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/70/86/ec7658cf5ff34dbe6f9e631db252b6f22bd39129af105c489f64754836c1/pymssql-2.4.6.tar.gz", hash = "sha256:2399f7dabcbacd56f10337f353a885a0954be611f6ec8da0e9a5d0f6f0311e0f", size = 213011, upload-time = "2026-10-27T02:53:50.798Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a6/ee/0f7da0b75041f3700839499a7b579688d5569f2e93fbf88712addf4917d0/pymssql-2.4.6-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:c5d8ccef171b335e6ed3da4689f113a5cdbcce738ea5f1870cc7c71f763a0f8d", size = 3230920, upload-time = "2026-10-27T02:52:35.016Z" },
{ url = "https://files.pythonhosted.org/packages/4e/69/20fa7c64b5f826919381e47af5e4539f1581d592707bf43b3bf81c81f6ad/pymssql-2.4.6-cp312-cp312-macosx_15_0_x86_64.whl", hash = "sha256:ed10c66ed9c1ec2964480c0ab2daeb4f6b6a6ee261a0e42abe45a74465cdad67", size = 2998868, upload-time = "2026-10-27T02:52:36.256Z" },
{ url = "https://files.pythonhosted.org/packages/65/60/d0cb02444abd419268a226769d66398834ea635e8443508d736a4bf03a15/pymssql-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d6ea24c9983543db3dd33c5806ce0425d741a3e2104090e8962c9901803ef653", size = 3102143, upload-time = "2026-10-27T02:52:37.773Z" },
{ url = "https://files.pythonhosted.org/packages/42/f9/5c561c35a0be1e234f16658b9a76e5adacbe0a77c91d93390ba5ab3e5ca5/pymssql-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dd1e5a1af9508033ef14bb8d074cfbf6cf2a4e04aab09207e63c9d4b37e3c485", size = 3278701, upload-time = "2026-10-27T02:52:38.988Z" },
{ url = "https://files.pythonhosted.org/packages/40/55/c9c6f537863399437d22a13bc3472da82638dcde9ac554ee99fb0545593e/pymssql-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e31e9a10196b39d9b0645009b122dc1e18458b84e93e3789febd9f3720e11054", size = 4492333, upload-time = "2026-10-27T02:52:40.49Z" },
{ url = "https://files.pythonhosted.org/packages/d5/ad/d3870696da44fb126fdd473f890c048ae4f2cf6e46df5abebb9fe4c8d3a4/pymssql-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:afee0c02cf275cda2b7498e1019a938a00e8765b08cec71634a1fd45757b900e", size = 4228007, upload-time = "2026-10-27T02:52:42.229Z" },
{ url = "https://files.pythonhosted.org/packages/bc/70/cce95b45f6f0d214ebc1a368e7088ac86e86cae638e51210bbb03f3c92dd/pymssql-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:f1b1d1a67a447e995f9588018170fe3c940f74dd8703b829edaf7dc332debd32", size = 2316243, upload-time = "2026-10-27T02:52:43.792Z" },
{ url = "https://files.pythonhosted.org/packages/31/b2/1b4556be296c5fd2aafaec2f2df53479c22c718db2ce9e956c983fddb0a7/pymssql-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:786eedbef791a9faf445a83020826254f7d12fcf2cd453328399867de1fa162a", size = 1839928, upload-time = "2026-10-27T02:52:45.237Z" },
]
[[package]]
name = "pymysql"
version = "1.2.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c8/69/808dc3d9bcc7d2841cdc2909b978c64eb1c450b7cd7b42d5907f7de7567d/pymysql-1.2.4.tar.gz", hash = "sha256:491558165b8e11f3644c5f9cfb30cc9c9111ffd54e53d3aa91b9a0a20be2294f", size = 51598, upload-time = "2026-11-09T09:37:09.356Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a3/60/acffa1e7261fdc68fadf6f196b66058e03dcb3df239f2c0acbfd11165845/pymysql-1.2.4-py3-none-any.whl", hash = "sha256:e169bed906168fffd0088925f45b3df024c2775c6fd128da0df773d47c458840", size = 46892, upload-time = "2026-11-09T09:37:07.987Z" },
]
[[package]]
name = "pytest"
version = "8.4.2"
@@ -778,11 +815,15 @@ source = { editable = "services/watchman" }
dependencies = [
{ name = "alembic" },
{ name = "celery" },
{ name = "croniter" },
{ name = "cryptography" },
{ name = "fastapi" },
{ name = "psycopg", extra = ["binary"] },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt", extra = ["crypto"] },
{ name = "pymssql" },
{ name = "pymysql" },
{ name = "python-dotenv" },
{ name = "sqlalchemy" },
{ name = "uvicorn", extra = ["standard"] },
@@ -792,11 +833,15 @@ dependencies = [
requires-dist = [
{ name = "alembic", specifier = ">=1.14,<2" },
{ name = "celery", specifier = ">=5.4,<6" },
{ name = "croniter", specifier = ">=3,<7" },
{ name = "cryptography", specifier = ">=43,<51" },
{ name = "fastapi", specifier = ">=0.115,<1" },
{ name = "psycopg", extras = ["binary"], specifier = ">=3.2,<4" },
{ name = "pydantic", specifier = ">=2.10,<3" },
{ name = "pydantic-settings", specifier = ">=2.6,<3" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.10,<3" },
{ name = "pymssql", specifier = ">=2.3,<3" },
{ name = "pymysql", specifier = ">=1.1,<2" },
{ name = "python-dotenv", specifier = ">=1.0,<2" },
{ name = "sqlalchemy", specifier = ">=2.0.36,<2.1" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },
+816
View File
@@ -0,0 +1,816 @@
import { expect, test, type Page, type Route } from "@playwright/test";
import path from "node:path";
import { fileURLToPath } from "node:url";
const evidenceDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../../docs/evidence/M03/ui",
);
// Synthetic data only. Hosts use the reserved .example.test suffix.
// The password below stands in for a saved secret: the mocked API never returns it.
const SAVED_SECRET = "pw-never-shown-9f3a";
const DRIVER_TEXT = "FATAL: driver said something private";
type Row = {
id: string;
name: string;
description: string | null;
kind: string;
engine: string;
host: string;
port: number;
database_name: string;
username: string;
secret_configured: boolean;
read_only_intent: boolean;
enabled: boolean;
circuit_state: "closed" | "open";
circuit_opened_at: string | null;
circuit_open_until: string | null;
circuit_failure_window_seconds: number;
circuit_failure_threshold: number;
circuit_open_cooldown_seconds: number;
last_test_category: string | null;
last_test_at: string | null;
last_test_message: string | null;
created_at: string;
updated_at: string;
};
function row(overrides: Partial<Row> & Pick<Row, "id" | "name">): Row {
return {
description: "示例(虚构)",
kind: "database",
engine: "postgresql",
host: "db.example.test",
port: 5432,
database_name: "process_demo",
username: "readonly_demo",
secret_configured: true,
read_only_intent: true,
enabled: true,
circuit_state: "closed",
circuit_opened_at: null,
circuit_open_until: null,
circuit_failure_window_seconds: 300,
circuit_failure_threshold: 3,
circuit_open_cooldown_seconds: 600,
last_test_category: null,
last_test_at: null,
last_test_message: null,
created_at: "2026-11-17T01:00:00+00:00",
updated_at: "2026-11-17T01:00:00+00:00",
...overrides,
};
}
const ID_ONE = "11111111-1111-4111-8111-111111111111";
const ID_OFF = "44444444-4444-4444-8444-444444444444";
const ID_OPEN = "66666666-6666-4666-8666-666666666666";
function seedRows(): Row[] {
return [
row({
id: ID_ONE,
name: "产线工艺库",
last_test_category: "success",
last_test_at: "2026-11-17T01:12:00+00:00",
}),
row({
id: "22222222-2222-4222-8222-222222222222",
name: "设备台账库",
engine: "mysql",
host: "mysql.example.test",
port: 3306,
database_name: "asset_demo",
last_test_category: "auth_failed",
last_test_at: "2026-11-16T09:40:00+00:00",
}),
row({
id: "33333333-3333-4333-8333-333333333333",
name: "质检结果库",
engine: "sqlserver",
host: "mssql.example.test",
port: 1433,
database_name: "quality_demo",
}),
row({
id: ID_OFF,
name: "历史归档库",
host: "archive.example.test",
database_name: "archive_demo",
enabled: false,
last_test_category: "success",
last_test_at: "2026-11-10T06:03:00+00:00",
}),
row({
id: ID_OPEN,
name: "熔断演示库",
host: "flaky.example.test",
database_name: "flaky_demo",
circuit_state: "open",
circuit_opened_at: "2026-11-18T09:20:00+00:00",
circuit_open_until: "2026-11-18T09:30:00+00:00",
circuit_failure_window_seconds: 120,
circuit_failure_threshold: 5,
circuit_open_cooldown_seconds: 900,
last_test_category: "unreachable",
last_test_at: "2026-11-18T09:20:00+00:00",
}),
];
}
function ok(data: unknown): string {
return JSON.stringify({ success: true, data, request_id: "pw-ds" });
}
function fail(code: number, message: string, details: Record<string, unknown> = {}): string {
return JSON.stringify({
success: false,
error: { code, message, details, retryable: false },
request_id: "pw-ds",
});
}
type Mock = {
rows: Row[];
requests: { method: string; pathname: string; body: unknown }[];
testOutcome: { status: number; body: string; delayMs: number };
draftOutcome: { status: number; body: string; delayMs: number };
};
async function signIn(page: Page, roles: string[]): Promise<void> {
await page.route("**/auth/me", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ subject: "user-1", display_name: "Worker", roles }),
});
});
await page.route("**/health", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ status: "ok", app: "watchman", version: "0.1.0" }),
});
});
}
/** Mock /datasources exactly; source files under /src/datasources are never matched. */
async function mockDatasources(page: Page, rows: Row[] = seedRows()): Promise<Mock> {
const mock: Mock = {
rows,
requests: [],
testOutcome: { status: 200, delayMs: 0, body: "" },
draftOutcome: { status: 200, delayMs: 0, body: ok({ category: "success", message: "fixed" }) },
};
mock.testOutcome.body = ok({
id: ID_ONE,
category: "success",
message: "fixed",
last_test_at: "2026-11-18T02:00:00+00:00",
});
const matcher = (url: URL) =>
/^\/datasources(\/(test-draft|[0-9a-f-]{36}(\/(test|disable|enable|references))?))?$/.test(url.pathname);
await page.route(matcher, async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const method = request.method();
let body: unknown = null;
if (method === "POST" || method === "PATCH") {
body = request.postDataJSON();
}
mock.requests.push({ method, pathname: url.pathname, body });
const json = (status: number, text: string) =>
route.fulfill({ status, contentType: "application/json", body: text });
const parts = url.pathname.split("/").filter(Boolean);
const id = parts[1];
const found = mock.rows.find((item) => item.id === id);
if (id === "test-draft") {
const draft = body as Record<string, unknown>;
if (!draft.password && !draft.datasource_id) {
return json(400, fail(40000, "Password is required", { fields: ["password"] }));
}
await new Promise((resolve) => setTimeout(resolve, mock.draftOutcome.delayMs));
return json(mock.draftOutcome.status, mock.draftOutcome.body);
}
if (parts.length === 1) {
if (method === "GET") {
return json(200, ok({ items: mock.rows }));
}
const created = row({ id: "55555555-5555-4555-8555-555555555555", name: "x" });
Object.assign(created, body, { secret_configured: true });
delete (created as Partial<Record<string, unknown>>).password;
mock.rows.push(created);
return json(200, ok(created));
}
if (!found) {
return json(404, fail(40400, "Datasource not found"));
}
const action = parts[2];
if (!action) {
if (method === "GET") {
return json(200, ok(found));
}
const patch = { ...(body as Record<string, unknown>) };
delete patch.password;
Object.assign(found, patch);
return json(200, ok(found));
}
if (action === "references") {
return json(200, ok({ id: found.id, items: [] }));
}
if (action === "disable") {
found.enabled = false;
return json(200, ok(found));
}
if (action === "enable") {
found.enabled = true;
return json(200, ok(found));
}
if (!found.enabled) {
return json(409, fail(40900, "Datasource is disabled", { reason: "disabled" }));
}
if (found.circuit_state === "open") {
return json(
409,
fail(40900, "Circuit open", { reason: "circuit_open", circuit_open_until: found.circuit_open_until }),
);
}
await new Promise((resolve) => setTimeout(resolve, mock.testOutcome.delayMs));
return json(mock.testOutcome.status, mock.testOutcome.body);
});
return mock;
}
async function expectNoSecretAnywhere(page: Page): Promise<void> {
await expect(page.locator("body")).not.toContainText(SAVED_SECRET);
const html = await page.content();
expect(html).not.toContain(SAVED_SECRET);
const stored = await page.evaluate(() =>
JSON.stringify({ local: { ...window.localStorage }, session: { ...window.sessionStorage } }),
);
expect(stored).not.toContain(SAVED_SECRET);
}
test.describe("datasources console", () => {
test("admin list: breadcrumb, create button above the table, columns, disabled row", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockDatasources(page);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-table")).toBeVisible();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("Watchman");
await expect(crumb).toContainText("数据源");
await expect(crumb).not.toContainText("新建");
await expect(crumb).not.toContainText("详情");
await expect(page.getByTestId("nav-datasources")).toBeVisible();
for (const header of ["名称", "引擎", "主机", "端口", "库名", "用户名", "状态", "最近测试", "操作"]) {
await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible();
}
await expect(page.getByTestId("datasource-table")).toContainText("产线工艺库");
await expect(page.getByTestId("datasource-table")).toContainText("SQL Server");
await expect(page.getByTestId("datasource-table")).toContainText("2026-11-17");
await expect(page.getByTestId("datasource-table")).toContainText("尚未测试");
// 新建 sits above the table, right aligned.
const create = await page.getByTestId("datasource-create").boundingBox();
const table = await page.getByTestId("datasource-table").boundingBox();
const viewport = page.viewportSize();
expect(create && table && viewport).toBeTruthy();
expect(create!.y + create!.height).toBeLessThanOrEqual(table!.y);
expect(create!.x + create!.width).toBeGreaterThan(table!.x + table!.width - 40);
// No page footer on the list.
await expect(page.getByTestId("datasource-footer")).toHaveCount(0);
// Disabled row: visible, 测试 disabled, no 停用, no "停用后不能测试" copy.
const off = page.getByTestId(`datasource-row-${ID_OFF}`);
await expect(off).toBeVisible();
await expect(off.getByTestId("row-test")).toBeDisabled();
await expect(off.getByTestId("row-test-why")).toHaveCount(0);
await expect(off).not.toContainText("停用后不能测试");
await expect(off.getByTestId("row-disable")).toHaveCount(0);
const live = page.getByTestId(`datasource-row-${ID_ONE}`);
await expect(live.getByTestId("row-edit")).toBeVisible();
await expect(live.getByTestId("row-test")).toBeEnabled();
await expect(live.getByTestId("row-disable")).toBeVisible();
await expect(page.locator("body")).not.toContainText("只读意图");
await expect(page.locator("body")).not.toContainText("正式版本进行删除");
await page.screenshot({ path: path.join(evidenceDir, "datasource-list.png"), fullPage: true });
});
test("empty list shows the empty state with 新建 above it", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockDatasources(page, []);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-empty")).toContainText("还没有数据源");
await expect(page.getByTestId("datasource-create")).toBeVisible();
await page.screenshot({ path: path.join(evidenceDir, "datasource-empty.png"), fullPage: true });
});
test("detail: masked password, footer outside the scroll area, blank save omits password", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 520 });
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-edit").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("详情");
await expect(crumb).not.toContainText("新建");
await expect(page.getByTestId("field-name").locator("input")).toHaveValue("产线工艺库");
// Password: el-input type=password with show-password, fixed mask, never the saved secret.
const password = page.getByTestId("field-password").locator("input");
await expect(password).toHaveAttribute("type", "password");
await expect(page.getByTestId("field-password").locator(".el-input__password")).toBeVisible();
await expect(password).toHaveValue("••••••••");
await expectNoSecretAnywhere(page);
// Footer: visible, centered, outside the scrolling body, and it does not move on scroll.
const footer = page.getByTestId("datasource-footer");
await expect(footer).toBeVisible();
await expect(page.getByTestId("datasource-scroll").getByTestId("datasource-footer")).toHaveCount(0);
for (const id of ["footer-save", "footer-test", "footer-disable", "footer-back"]) {
await expect(page.getByTestId(id)).toBeVisible();
}
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("footer-save")).toHaveText("保存");
await expect(page.getByTestId("footer-test")).toHaveText("测试连接");
await expect(page.getByTestId("footer-disable")).toHaveText("停用");
await expect(page.getByTestId("footer-back")).toHaveText("返回列表");
const footerBox = (await footer.boundingBox())!;
const first = (await page.getByTestId("footer-save").boundingBox())!;
const last = (await page.getByTestId("footer-back").boundingBox())!;
const buttonsCenter = (first.x + last.x + last.width) / 2;
expect(Math.abs(buttonsCenter - (footerBox.x + footerBox.width / 2))).toBeLessThan(6);
const bodyScrolls = await page
.getByTestId("datasource-scroll")
.evaluate((el) => el.scrollHeight > el.clientHeight);
expect(bodyScrolls).toBe(true);
await page.getByTestId("datasource-scroll").evaluate((el) => el.scrollTo(0, el.scrollHeight));
const afterScroll = (await footer.boundingBox())!;
expect(afterScroll.y).toBeCloseTo(footerBox.y, 0);
expect(afterScroll.y + afterScroll.height).toBeLessThanOrEqual(520);
await page.getByTestId("datasource-scroll").evaluate((el) => el.scrollTo(0, 0));
// References are empty.
await expect(page.getByTestId("references-empty")).toHaveText("尚无引用");
await page.screenshot({ path: path.join(evidenceDir, "datasource-detail.png"), fullPage: true });
// Focus clears the mask. Leaving it blank restores it. A blank save omits the password.
await password.focus();
await expect(password).toHaveValue("");
await page.getByTestId("field-name").locator("input").focus();
await expect(password).toHaveValue("••••••••");
await page.getByTestId("field-host").locator("input").fill("db2.example.test");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const patch = mock.requests.find((item) => item.method === "PATCH");
expect(patch).toBeTruthy();
const body = patch!.body as Record<string, unknown>;
expect("password" in body).toBe(false);
expect(body.host).toBe("db2.example.test");
expect(body.circuit_failure_window_seconds).toBe(300);
expect(body.circuit_failure_threshold).toBe(3);
expect(body.circuit_open_cooldown_seconds).toBe(600);
expect(JSON.stringify(mock.requests)).not.toContain("••••");
await expectNoSecretAnywhere(page);
});
test("detail: a typed password is sent, and test shows testing then the category only", async ({
page,
}) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
mock.testOutcome = {
status: 400,
delayMs: 700,
body: fail(40000, DRIVER_TEXT, { category: "auth_failed" }),
};
// List「测试」opens the detail with ?test=1 and probes the saved connection (no detail button).
await page.goto("/#/datasources");
await page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-test").click();
await expect(page.getByTestId("test-running")).toContainText("测试中");
const result = page.getByTestId("test-result");
await expect(result).toBeVisible();
await expect(result).toHaveAttribute("data-category", "auth_failed");
await expect(result).toHaveAttribute("data-source", "saved");
await expect(page.getByTestId("test-source-note")).toContainText("最近测试");
await expect(result).toContainText("认证失败");
await expect(page.locator("body")).not.toContainText(DRIVER_TEXT);
await expectNoSecretAnywhere(page);
await page.screenshot({ path: path.join(evidenceDir, "datasource-test-auth.png"), fullPage: true });
mock.testOutcome = { status: 200, delayMs: 0, body: ok({ id: ID_ONE, category: "success", message: "m", last_test_at: null }) };
await page.goto(`/#/datasources/${ID_ONE}?test=1`);
await page.reload();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
for (const category of ["timeout", "unreachable", "rejected"]) {
mock.testOutcome = {
status: 400,
delayMs: 0,
body: fail(40000, DRIVER_TEXT, { category }),
};
await page.goto(`/#/datasources/${ID_ONE}?test=1`);
await page.reload();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", category);
}
await expect(page.locator("body")).not.toContainText(DRIVER_TEXT);
await page.getByTestId("field-password").locator("input").focus();
await page.getByTestId("field-password").locator("input").fill("typed-replacement-pw");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const patch = mock.requests.find((item) => item.method === "PATCH");
expect((patch!.body as Record<string, unknown>).password).toBe("typed-replacement-pw");
});
test("disabled detail: no saved-test button, 启用 replaces 停用, draft test stays", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_OFF}`);
await expect(page.getByTestId("datasource-disabled-note")).toBeVisible();
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-test")).toBeEnabled();
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
await expect(page.getByTestId("footer-enable")).toHaveText("启用");
await page.screenshot({ path: path.join(evidenceDir, "datasource-disabled.png"), fullPage: true });
// Enable needs no prior test; the page stays on detail.
await page.getByTestId("footer-enable").click();
await expect(page.getByTestId("footer-disable")).toBeVisible();
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("datasource-disabled-note")).toHaveCount(0);
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
const calls = mock.requests.filter((item) => item.method === "POST");
expect(calls.map((item) => item.pathname)).toEqual([`/datasources/${ID_OFF}/enable`]);
});
test("list: enable a disabled row without testing first", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
const off = page.getByTestId(`datasource-row-${ID_OFF}`);
await expect(off.getByTestId("row-enable")).toHaveText("启用");
await expect(off.getByTestId("row-test")).toBeDisabled();
await expect(page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-enable")).toHaveCount(0);
await off.getByTestId("row-enable").click();
await expect(off.getByTestId("row-disable")).toBeVisible();
await expect(off.getByTestId("row-enable")).toHaveCount(0);
await expect(off.getByTestId("row-test")).toBeEnabled();
expect(mock.requests.filter((item) => item.method === "POST").map((item) => item.pathname)).toEqual([
`/datasources/${ID_OFF}/enable`,
]);
await page.screenshot({ path: path.join(evidenceDir, "datasource-list-enabled.png"), fullPage: true });
});
test("circuit open: list and detail block the saved test and show the until time", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
const open = page.getByTestId(`datasource-row-${ID_OPEN}`);
await expect(page.getByTestId("datasource-table")).toContainText("熔断中");
await expect(open.getByTestId("row-test")).toBeDisabled();
await expect(open.getByTestId("row-test")).toHaveAttribute("title", /2026-11-18/);
await expect(open.getByTestId("row-enable")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "datasource-list-circuit.png"), fullPage: true });
await open.getByTestId("row-edit").click();
await expect(page.getByTestId("circuit-open-alert")).toContainText("2026-11-18");
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-test")).toBeEnabled();
await expect(page.getByTestId("field-circuit-window").locator("input")).toHaveValue("120");
await expect(page.getByTestId("field-circuit-threshold").locator("input")).toHaveValue("5");
await expect(page.getByTestId("field-circuit-cooldown").locator("input")).toHaveValue("900");
await page.screenshot({ path: path.join(evidenceDir, "datasource-circuit-open.png"), fullPage: true });
// The list's test link does not run a saved probe while the circuit is open.
await page.goto(`/#/datasources/${ID_OPEN}?test=1`);
await page.reload();
await expect(page.getByTestId("circuit-open-alert")).toBeVisible();
expect(mock.requests.filter((item) => item.pathname.endsWith("/test"))).toHaveLength(0);
// Circuit parameters are saved with the rest of the form.
await page.getByTestId("field-circuit-window").locator("input").fill("60");
await page.getByTestId("field-circuit-threshold").locator("input").fill("4");
await page.getByTestId("field-circuit-cooldown").locator("input").fill("1200");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const patch = mock.requests.find((item) => item.method === "PATCH");
const body = patch!.body as Record<string, unknown>;
expect(body.circuit_failure_window_seconds).toBe(60);
expect(body.circuit_failure_threshold).toBe(4);
expect(body.circuit_open_cooldown_seconds).toBe(1200);
});
test("circuit open: list ?test=1 against an open circuit does not call /test", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
const target = mock.rows.find((item) => item.id === ID_ONE)!;
target.circuit_state = "open";
target.circuit_open_until = "2026-11-18T09:45:00+00:00";
await page.goto(`/#/datasources/${ID_ONE}?test=1`);
await page.reload();
await expect(page.getByTestId("circuit-open-alert")).toBeVisible();
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
expect(mock.requests.filter((item) => item.pathname.endsWith("/test"))).toHaveLength(0);
});
test("circuit parameters are validated on the detail page", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_ONE}`);
const window = page.getByTestId("field-circuit-window").locator("input");
const threshold = page.getByTestId("field-circuit-threshold").locator("input");
const cooldown = page.getByTestId("field-circuit-cooldown").locator("input");
await window.fill("0");
await window.press("Tab");
await threshold.fill("101");
await threshold.press("Tab");
await cooldown.fill("86401");
await cooldown.press("Tab");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("field-circuit-window").locator(".el-form-item__error")).toContainText("1–86400");
await expect(page.getByTestId("field-circuit-threshold").locator(".el-form-item__error")).toContainText("1–100");
await expect(page.getByTestId("field-circuit-cooldown").locator(".el-form-item__error")).toContainText("1–86400");
expect(mock.requests.filter((item) => item.method === "PATCH")).toHaveLength(0);
await window.fill("86400");
await window.press("Tab");
await threshold.fill("100");
await threshold.press("Tab");
await cooldown.fill("1");
await cooldown.press("Tab");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toBeVisible();
const body = mock.requests.find((item) => item.method === "PATCH")!.body as Record<string, unknown>;
expect([body.circuit_failure_window_seconds, body.circuit_failure_threshold, body.circuit_open_cooldown_seconds]).toEqual([
86400, 100, 1,
]);
});
test("create form validation: required fields, port range, host has no format rule", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources/new");
await expect(page.getByTestId("datasource-circuit")).toHaveCount(0);
await page.getByTestId("footer-save").click();
for (const field of ["name", "host", "database", "username", "password"]) {
await expect(page.getByTestId(`field-${field}`).locator(".el-form-item__error")).toContainText("必填");
}
expect(mock.requests).toHaveLength(0);
// A spaces-only host is still empty.
await page.getByTestId("field-host").locator("input").fill(" ");
await page.getByTestId("field-host").locator("input").press("Tab");
await expect(page.getByTestId("field-host").locator(".el-form-item__error")).toContainText("必填");
// Port: empty and out of range are both refused.
const port = page.getByTestId("field-port").locator("input");
await port.fill("");
await port.press("Tab");
await expect(page.getByTestId("field-port").locator(".el-form-item__error")).toContainText("必填");
await port.fill("70000");
await port.press("Tab");
await expect(page.getByTestId("field-port").locator(".el-form-item__error")).toContainText("1–65535");
await port.fill("0");
await port.press("Tab");
await expect(page.getByTestId("field-port").locator(".el-form-item__error")).toContainText("1–65535");
await page.screenshot({ path: path.join(evidenceDir, "datasource-validation.png"), fullPage: true });
// Host takes any non-blank text: no hostname regex.
await page.getByTestId("field-name").locator("input").fill("宽松主机库");
await page.getByTestId("field-host").locator("input").fill("not a hostname_at all");
await port.fill("65535");
await port.press("Tab");
await page.getByTestId("field-database").locator("input").fill("d");
await page.getByTestId("field-username").locator("input").fill("u");
await page.getByTestId("field-password").locator("input").fill("typed-pw");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toContainText("宽松主机库");
const post = mock.requests.find((item) => item.method === "POST")!.body as Record<string, unknown>;
expect(post.host).toBe("not a hostname_at all");
expect(post.port).toBe(65535);
expect(JSON.stringify(post)).not.toContain("circuit");
});
test("create: draft test works before saving and never saves or leaks the password", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources/new");
await expect(page.getByTestId("footer-test")).toHaveText("测试连接");
await expect(page.getByTestId("test-none")).toContainText("保存前");
// Missing fields and a missing password stop the test before any request.
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("field-host").locator(".el-form-item__error")).toContainText("必填");
await expect(page.getByTestId("field-password").locator(".el-form-item__error")).toContainText("必填");
expect(mock.requests).toHaveLength(0);
await page.getByTestId("field-host").locator("input").fill("draft.example.test");
await page.getByTestId("field-database").locator("input").fill("draft_demo");
await page.getByTestId("field-username").locator("input").fill("readonly_demo");
await page.getByTestId("footer-test").click();
expect(mock.requests).toHaveLength(0);
await page.getByTestId("field-password").locator("input").fill(SAVED_SECRET);
mock.draftOutcome = {
status: 400,
delayMs: 500,
body: fail(40000, DRIVER_TEXT, { category: "auth_failed" }),
};
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-running")).toContainText("测试中");
const result = page.getByTestId("test-result");
await expect(result).toHaveAttribute("data-category", "auth_failed");
await expect(result).toHaveAttribute("data-source", "draft");
await expect(page.getByTestId("test-source-note")).toContainText("草稿测试");
await expect(page.getByTestId("test-source-note")).toContainText("不会保存");
const draft = mock.requests.filter((item) => item.pathname === "/datasources/test-draft");
expect(draft).toHaveLength(1);
expect(draft[0].body).toEqual({
engine: "postgresql",
host: "draft.example.test",
port: 5432,
database_name: "draft_demo",
username: "readonly_demo",
password: SAVED_SECRET,
});
// Nothing was saved: no create call and no saved-record test.
expect(mock.requests.filter((item) => item.pathname !== "/datasources/test-draft")).toHaveLength(0);
expect(mock.rows.some((item) => item.name === "x")).toBe(false);
await expect(page.locator("body")).not.toContainText(DRIVER_TEXT);
await expectNoSecretAnywhere(page);
mock.draftOutcome = { status: 200, delayMs: 0, body: ok({ category: "success", message: "m" }) };
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
await page.screenshot({ path: path.join(evidenceDir, "datasource-draft-test.png"), fullPage: true });
});
test("edit: draft test with a blank password uses the stored secret via datasource_id", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_ONE}`);
await page.getByTestId("field-host").locator("input").fill("changed.example.test");
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-source", "draft");
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
const draft = mock.requests.filter((item) => item.pathname === "/datasources/test-draft");
expect(draft).toHaveLength(1);
const body = draft[0].body as Record<string, unknown>;
expect(body.datasource_id).toBe(ID_ONE);
expect(body.host).toBe("changed.example.test");
expect("password" in body).toBe(false);
expect(JSON.stringify(body)).not.toContain("••••");
// The draft did not touch the saved record or call the saved test.
expect(mock.requests.filter((item) => item.pathname.endsWith(`${ID_ONE}/test`))).toHaveLength(0);
expect(mock.requests.filter((item) => item.method !== "GET" && item.pathname !== "/datasources/test-draft")).toHaveLength(0);
expect(mock.rows.find((item) => item.id === ID_ONE)!.host).toBe("db.example.test");
await expectNoSecretAnywhere(page);
// A typed password goes along with the id.
await page.getByTestId("field-password").locator("input").focus();
await page.getByTestId("field-password").locator("input").fill("typed-replacement-pw");
await page.getByTestId("footer-test").click();
await expect.poll(() => mock.requests.filter((item) => item.pathname === "/datasources/test-draft").length).toBe(2);
const second = mock.requests.filter((item) => item.pathname === "/datasources/test-draft")[1].body as Record<string, unknown>;
expect(second.password).toBe("typed-replacement-pw");
expect(second.datasource_id).toBe(ID_ONE);
});
test("a draft test is also available on a disabled datasource", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto(`/#/datasources/${ID_OFF}`);
await page.getByTestId("footer-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-source", "draft");
expect(mock.requests.filter((item) => item.pathname === "/datasources/test-draft")).toHaveLength(1);
});
test("list test action opens the detail and runs the test once", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await page.getByTestId(`datasource-row-${ID_ONE}`).getByTestId("row-test").click();
await expect(page.getByTestId("test-result")).toHaveAttribute("data-category", "success");
expect(mock.requests.filter((item) => item.pathname.endsWith("/test")).length).toBe(1);
});
test("create: breadcrumb, empty password, three engines, footer, payload", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await page.getByTestId("datasource-create").click();
const crumb = page.getByTestId("breadcrumb");
await expect(crumb).toContainText("新建");
await expect(crumb).not.toContainText("详情");
const password = page.getByTestId("field-password").locator("input");
await expect(password).toHaveValue("");
await expect(password).toHaveAttribute("type", "password");
await expect(page.locator("body")).not.toContainText("只读意图");
await expect(page.locator("body")).not.toContainText("正式版本进行删除");
// Footer: 保存, 测试连接 (draft) and 返回列表; no saved-record actions yet.
await expect(page.getByTestId("footer-save")).toBeVisible();
await expect(page.getByTestId("footer-test")).toBeVisible();
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-test-saved")).toHaveCount(0);
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
// Engines: exactly the three supported ones.
await page.getByTestId("field-engine").click();
const options = page.locator(".el-select-dropdown__item");
await expect(options).toHaveText(["PostgreSQL", "MySQL", "SQL Server"]);
await options.filter({ hasText: "MySQL" }).click();
await expect(page.getByTestId("field-port").locator("input")).toHaveValue("3306");
await page.screenshot({ path: path.join(evidenceDir, "datasource-create.png"), fullPage: true });
// A blank form does not submit, and a missing password blocks create.
await page.getByTestId("footer-save").click();
await expect(page.locator(".el-form-item__error").first()).toBeVisible();
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
await page.getByTestId("field-name").locator("input").fill("新建演示库");
await page.getByTestId("field-host").locator("input").fill("new.example.test");
await page.getByTestId("field-database").locator("input").fill("new_demo");
await page.getByTestId("field-username").locator("input").fill("readonly_demo");
await page.getByTestId("footer-save").click();
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
await password.fill(SAVED_SECRET);
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-table")).toContainText("新建演示库");
const post = mock.requests.find((item) => item.method === "POST");
const body = post!.body as Record<string, unknown>;
expect(body.password).toBe(SAVED_SECRET);
expect(body.engine).toBe("mysql");
expect("read_only_intent" in body).toBe(false);
await expectNoSecretAnywhere(page);
});
test("duplicate name shows the API reason on the form", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockDatasources(page);
await page.route(/\/datasources$/, async (route) => {
if (route.request().method() === "POST") {
await route.fulfill({
status: 409,
contentType: "application/json",
body: fail(40900, "Conflict", { reason: "duplicate_name" }),
});
return;
}
await route.fallback();
});
await page.goto("/#/datasources/new");
await page.getByTestId("field-name").locator("input").fill("产线工艺库");
await page.getByTestId("field-host").locator("input").fill("x.example.test");
await page.getByTestId("field-database").locator("input").fill("d");
await page.getByTestId("field-username").locator("input").fill("u");
await page.getByTestId("field-password").locator("input").fill("typed-pw");
await page.getByTestId("footer-save").click();
await expect(page.getByTestId("datasource-save-error")).toContainText("名称已存在");
});
test("a viewer sees 无法进入数据源 and no datasource request is made", async ({ page }) => {
await signIn(page, ["watchman-viewer"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-denied")).toContainText("无法进入数据源");
await expect(page.getByTestId("breadcrumb")).toContainText("数据源");
await expect(page.getByTestId("datasource-table")).toHaveCount(0);
await expect(page.getByTestId("datasource-create")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "datasource-denied-viewer.png"), fullPage: true });
// Deep links are gated too.
await page.goto(`/#/datasources/${ID_ONE}`);
await expect(page.getByTestId("datasource-denied")).toBeVisible();
await page.goto("/#/datasources/new");
await expect(page.getByTestId("datasource-denied")).toBeVisible();
await expect(page.getByTestId("breadcrumb")).not.toContainText("新建");
expect(mock.requests).toHaveLength(0);
});
test("an operator is denied as well", async ({ page }) => {
await signIn(page, ["watchman-operator"]);
const mock = await mockDatasources(page);
await page.goto("/#/datasources");
await expect(page.getByTestId("datasource-denied")).toBeVisible();
expect(mock.requests).toHaveLength(0);
});
});
+134
View File
@@ -32,5 +32,139 @@
"failure": "Health check failed",
"successDetail": "Service available: {detail}",
"failureDetail": "Service unavailable: {detail}"
},
"nav": {
"home": "Overview",
"datasources": "Data sources",
"create": "New",
"detail": "Details"
},
"datasource": {
"list": {
"create": "New",
"loading": "Loading data sources",
"loadFailed": "Failed to load data sources",
"empty": "No data sources yet",
"emptyHint": "An administrator can create the first data source."
},
"columns": {
"name": "Name",
"engine": "Engine",
"host": "Host",
"port": "Port",
"database": "Database",
"username": "Username",
"status": "Status",
"lastTest": "Last test",
"actions": "Actions"
},
"status": {
"enabled": "Enabled",
"disabled": "Disabled",
"circuitOpen": "Circuit open"
},
"actions": {
"edit": "Edit",
"test": "Test",
"disable": "Disable",
"save": "Save",
"backToList": "Back to list",
"testDisabledWhy": "A disabled data source cannot be tested",
"testConnection": "Test connection",
"testSaved": "Test saved connection",
"enable": "Enable"
},
"denied": {
"title": "Data sources are not available",
"body": "Only administrators can open the data source pages."
},
"form": {
"connection": "Connection",
"name": "Name",
"engine": "Engine",
"description": "Purpose",
"host": "Host",
"hostPlaceholder": "For example db.example.test",
"port": "Port",
"database": "Database",
"username": "Username",
"password": "Password",
"passwordPlaceholder": "Enter a password",
"required": "Required",
"saving": "Saving",
"invalidRange": "Enter a whole number from {min} to {max}"
},
"disabledNote": "This data source is disabled, so its saved connection cannot be tested. Click Enable to restore it.",
"circuit": {
"title": "Circuit breaker",
"hint": "When the saved connection fails the threshold number of times within the window, the circuit opens. It cannot be tested during the cooldown and recovers automatically afterwards.",
"window": "Failure window (seconds)",
"threshold": "Failure threshold (times)",
"cooldown": "Cooldown (seconds)",
"openTitle": "Circuit open",
"openBody": "Repeated failures opened the circuit. The saved connection cannot be tested until {until}.",
"testBlocked": "Circuit open, cannot be tested until {until}"
},
"enabledDone": "Enabled",
"loadFailed": "Failed to load the data source",
"notFound": "Data source not found",
"test": {
"title": "Connection test",
"none": "Not tested yet",
"noneDraft": "You can test the connection with the current form values before saving.",
"draftNote": "Draft test: uses the current form values. Nothing is saved and Last test is not updated.",
"savedNote": "Test of the saved connection. The result is recorded in Last test.",
"running": "Testing",
"failedUnknown": "The test did not finish. Try again shortly."
},
"category": {
"success": {
"title": "Test succeeded",
"body": "Connected and completed the read-only probe."
},
"auth_failed": {
"title": "Authentication failed",
"body": "The server did not accept the username or password. Check the username, then enter the password again and save."
},
"timeout": {
"title": "Timed out",
"body": "No reply from the server in the allowed time. Try again later, or check the network and firewall."
},
"unreachable": {
"title": "Unreachable",
"body": "Could not connect to the host and port. Check the host, the port, and whether the network allows it."
},
"rejected": {
"title": "Rejected by the server",
"body": "The server replied but refused the request, for example because the database does not exist. This is not a password error."
}
},
"lastTest": {
"success": "Succeeded",
"auth_failed": "Authentication failed",
"timeout": "Timed out",
"unreachable": "Unreachable",
"rejected": "Rejected",
"none": "Not tested yet"
},
"refs": {
"title": "References",
"empty": "No references yet",
"loadFailed": "Failed to load references"
},
"disableConfirm": {
"title": "Disable data source",
"body": "A disabled data source cannot be tested. The record is kept. Disable \"{name}\"?",
"ok": "Disable",
"cancel": "Cancel"
},
"errors": {
"duplicate_name": "This name already exists. Choose another.",
"disabled": "The data source is disabled, so the saved connection cannot be tested",
"circuit_open": "Circuit open, the saved connection cannot be tested for now",
"secret_unavailable": "The saved password cannot be used. Enter the password again, then test."
},
"saved": "Saved",
"disabled": "Disabled"
}
}
+134
View File
@@ -32,5 +32,139 @@
"failure": "ตรวจสอบสถานะล้มเหลว",
"successDetail": "บริการพร้อมใช้งาน: {detail}",
"failureDetail": "บริการไม่พร้อมใช้งาน: {detail}"
},
"nav": {
"home": "ภาพรวม",
"datasources": "แหล่งข้อมูล",
"create": "สร้างใหม่",
"detail": "รายละเอียด"
},
"datasource": {
"list": {
"create": "สร้างใหม่",
"loading": "กำลังโหลดแหล่งข้อมูล",
"loadFailed": "โหลดแหล่งข้อมูลไม่สำเร็จ",
"empty": "ยังไม่มีแหล่งข้อมูล",
"emptyHint": "ผู้ดูแลสามารถสร้างแหล่งข้อมูลแรกได้"
},
"columns": {
"name": "ชื่อ",
"engine": "เอนจิน",
"host": "โฮสต์",
"port": "พอร์ต",
"database": "ฐานข้อมูล",
"username": "ชื่อผู้ใช้",
"status": "สถานะ",
"lastTest": "ทดสอบล่าสุด",
"actions": "การดำเนินการ"
},
"status": {
"enabled": "เปิดใช้งาน",
"disabled": "ปิดใช้งานแล้ว",
"circuitOpen": "วงจรตัดการทำงาน"
},
"actions": {
"edit": "แก้ไข",
"test": "ทดสอบ",
"disable": "ปิดใช้งาน",
"save": "บันทึก",
"backToList": "กลับไปที่รายการ",
"testDisabledWhy": "แหล่งข้อมูลที่ปิดใช้งานทดสอบไม่ได้",
"testConnection": "ทดสอบการเชื่อมต่อ",
"testSaved": "ทดสอบการเชื่อมต่อที่บันทึกไว้",
"enable": "เปิดใช้งาน"
},
"denied": {
"title": "ไม่สามารถเข้าหน้าแหล่งข้อมูลได้",
"body": "เฉพาะผู้ดูแลเท่านั้นที่เข้าหน้าแหล่งข้อมูลได้"
},
"form": {
"connection": "ข้อมูลการเชื่อมต่อ",
"name": "ชื่อ",
"engine": "เอนจิน",
"description": "วัตถุประสงค์",
"host": "โฮสต์",
"hostPlaceholder": "เช่น db.example.test",
"port": "พอร์ต",
"database": "ฐานข้อมูล",
"username": "ชื่อผู้ใช้",
"password": "รหัสผ่าน",
"passwordPlaceholder": "กรอกรหัสผ่าน",
"required": "จำเป็นต้องกรอก",
"saving": "กำลังบันทึก",
"invalidRange": "ต้องเป็นจำนวนเต็มตั้งแต่ {min} ถึง {max}"
},
"disabledNote": "แหล่งข้อมูลนี้ปิดใช้งานแล้ว จึงทดสอบการเชื่อมต่อที่บันทึกไว้ไม่ได้ กด \"เปิดใช้งาน\" เพื่อกู้คืน",
"circuit": {
"title": "การป้องกันด้วยวงจรตัด",
"hint": "เมื่อการเชื่อมต่อที่บันทึกไว้ล้มเหลวถึงเกณฑ์ภายในช่วงเวลาที่กำหนด วงจรจะตัดการทำงาน ทดสอบไม่ได้ในช่วงพัก และจะกลับมาเองเมื่อครบเวลา",
"window": "ช่วงนับความล้มเหลว (วินาที)",
"threshold": "เกณฑ์ความล้มเหลว (ครั้ง)",
"cooldown": "ระยะเวลาพัก (วินาที)",
"openTitle": "วงจรตัดการทำงานอยู่",
"openBody": "ความล้มเหลวซ้ำทำให้วงจรตัด ทดสอบการเชื่อมต่อที่บันทึกไว้ไม่ได้จนถึง {until}",
"testBlocked": "วงจรตัดอยู่ ทดสอบไม่ได้จนถึง {until}"
},
"enabledDone": "เปิดใช้งานแล้ว",
"loadFailed": "โหลดแหล่งข้อมูลไม่สำเร็จ",
"notFound": "ไม่พบแหล่งข้อมูล",
"test": {
"title": "ทดสอบการเชื่อมต่อ",
"none": "ยังไม่ได้ทดสอบ",
"noneDraft": "ทดสอบการเชื่อมต่อด้วยค่าในแบบฟอร์มปัจจุบันได้ก่อนบันทึก",
"draftNote": "ทดสอบแบบร่าง: ใช้ค่าในแบบฟอร์มปัจจุบัน ไม่มีการบันทึกและไม่อัปเดต \"ทดสอบล่าสุด\"",
"savedNote": "ทดสอบการเชื่อมต่อที่บันทึกไว้ ผลลัพธ์ถูกบันทึกใน \"ทดสอบล่าสุด\"",
"running": "กำลังทดสอบ",
"failedUnknown": "การทดสอบไม่เสร็จสมบูรณ์ โปรดลองอีกครั้ง"
},
"category": {
"success": {
"title": "ทดสอบสำเร็จ",
"body": "เชื่อมต่อและตรวจสอบแบบอ่านอย่างเดียวเสร็จแล้ว"
},
"auth_failed": {
"title": "การยืนยันตัวตนล้มเหลว",
"body": "เซิร์ฟเวอร์ไม่ยอมรับชื่อผู้ใช้หรือรหัสผ่าน ตรวจสอบชื่อผู้ใช้ แล้วกรอกรหัสผ่านใหม่และบันทึก"
},
"timeout": {
"title": "หมดเวลา",
"body": "ไม่ได้รับการตอบกลับจากเซิร์ฟเวอร์ภายในเวลาที่กำหนด ลองอีกครั้งภายหลัง หรือตรวจสอบเครือข่ายและไฟร์วอลล์"
},
"unreachable": {
"title": "เข้าถึงไม่ได้",
"body": "เชื่อมต่อกับโฮสต์และพอร์ตไม่ได้ ตรวจสอบโฮสต์ พอร์ต และการอนุญาตของเครือข่าย"
},
"rejected": {
"title": "เซิร์ฟเวอร์ปฏิเสธ",
"body": "เซิร์ฟเวอร์ตอบกลับแต่ปฏิเสธคำขอ เช่น ไม่มีฐานข้อมูลนี้ ไม่ใช่ปัญหารหัสผ่าน"
}
},
"lastTest": {
"success": "สำเร็จ",
"auth_failed": "ยืนยันตัวตนล้มเหลว",
"timeout": "หมดเวลา",
"unreachable": "เข้าถึงไม่ได้",
"rejected": "ถูกปฏิเสธ",
"none": "ยังไม่ได้ทดสอบ"
},
"refs": {
"title": "การอ้างอิง",
"empty": "ยังไม่มีการอ้างอิง",
"loadFailed": "โหลดการอ้างอิงไม่สำเร็จ"
},
"disableConfirm": {
"title": "ปิดใช้งานแหล่งข้อมูล",
"body": "แหล่งข้อมูลที่ปิดใช้งานทดสอบไม่ได้ แต่ยังเก็บบันทึกไว้ ต้องการปิดใช้งาน \"{name}\" หรือไม่",
"ok": "ปิดใช้งาน",
"cancel": "ยกเลิก"
},
"errors": {
"duplicate_name": "ชื่อนี้มีอยู่แล้ว โปรดใช้ชื่ออื่น",
"disabled": "แหล่งข้อมูลปิดใช้งานอยู่ จึงทดสอบการเชื่อมต่อที่บันทึกไว้ไม่ได้",
"circuit_open": "วงจรตัดอยู่ ทดสอบการเชื่อมต่อที่บันทึกไว้ไม่ได้ในขณะนี้",
"secret_unavailable": "ใช้รหัสผ่านที่บันทึกไว้ไม่ได้ โปรดกรอกรหัสผ่านใหม่แล้วทดสอบอีกครั้ง"
},
"saved": "บันทึกแล้ว",
"disabled": "ปิดใช้งานแล้ว"
}
}
+134
View File
@@ -33,5 +33,139 @@
"failure": "健康检查失败",
"successDetail": "服务可用:{detail}",
"failureDetail": "服务不可用:{detail}"
},
"nav": {
"home": "概览",
"datasources": "数据源",
"create": "新建",
"detail": "详情"
},
"datasource": {
"list": {
"create": "新建",
"loading": "数据源加载中",
"loadFailed": "数据源加载失败",
"empty": "还没有数据源",
"emptyHint": "管理者可以新建第一个数据源。"
},
"columns": {
"name": "名称",
"engine": "引擎",
"host": "主机",
"port": "端口",
"database": "库名",
"username": "用户名",
"status": "状态",
"lastTest": "最近测试",
"actions": "操作"
},
"status": {
"enabled": "启用",
"disabled": "已停用",
"circuitOpen": "熔断中"
},
"actions": {
"edit": "编辑",
"test": "测试",
"disable": "停用",
"save": "保存",
"backToList": "返回列表",
"testDisabledWhy": "停用后不能测试",
"testConnection": "测试连接",
"testSaved": "测试已保存连接",
"enable": "启用"
},
"denied": {
"title": "无法进入数据源",
"body": "只有管理者可以进入数据源界面。"
},
"form": {
"connection": "连接信息",
"name": "名称",
"engine": "引擎",
"description": "用途说明",
"host": "主机",
"hostPlaceholder": "例如 db.example.test",
"port": "端口",
"database": "库名",
"username": "用户名",
"password": "密码",
"passwordPlaceholder": "请输入密码",
"required": "必填",
"saving": "保存中",
"invalidRange": "须为 {min}–{max} 的整数"
},
"disabledNote": "该数据源已停用,不能测试已保存的连接。点击「启用」可恢复。",
"circuit": {
"title": "熔断保护",
"hint": "已保存连接在时间窗内连续失败达到阈值后会熔断,冷却期内不能测试,到期后自动恢复。",
"window": "统计窗口(秒)",
"threshold": "失败阈值(次)",
"cooldown": "冷却时长(秒)",
"openTitle": "已熔断",
"openBody": "连续失败触发熔断,{until} 前不能测试已保存的连接。",
"testBlocked": "熔断中,{until} 前不能测试"
},
"enabledDone": "已启用",
"loadFailed": "数据源加载失败",
"notFound": "数据源不存在",
"test": {
"title": "连接测试",
"none": "尚未测试",
"noneDraft": "可在保存前用当前表单内容测试连接。",
"draftNote": "草稿测试:使用当前表单内容,不会保存,也不会更新「最近测试」。",
"savedNote": "已保存连接的测试,结果已记录到「最近测试」。",
"running": "测试中",
"failedUnknown": "测试未完成,请稍后再试"
},
"category": {
"success": {
"title": "测试成功",
"body": "已连接并完成只读探测。"
},
"auth_failed": {
"title": "认证失败",
"body": "服务端不接受该用户名或密码。请核对用户名,并在密码框重新输入后保存。"
},
"timeout": {
"title": "超时",
"body": "在允许的时间内没有收到服务端响应。可稍后重试,或检查网络与防火墙。"
},
"unreachable": {
"title": "不可达",
"body": "无法与目标主机和端口建立连接。请核对主机、端口,以及网络是否放行。"
},
"rejected": {
"title": "服务端拒绝",
"body": "服务端已响应但拒绝了请求,例如库名不存在。这不是密码错误。"
}
},
"lastTest": {
"success": "成功",
"auth_failed": "认证失败",
"timeout": "超时",
"unreachable": "不可达",
"rejected": "服务端拒绝",
"none": "尚未测试"
},
"refs": {
"title": "引用",
"empty": "尚无引用",
"loadFailed": "引用加载失败"
},
"disableConfirm": {
"title": "停用数据源",
"body": "停用后不能测试,记录仍然保留。确定停用「{name}」吗?",
"ok": "停用",
"cancel": "取消"
},
"errors": {
"duplicate_name": "名称已存在,请换一个名称",
"disabled": "数据源已停用,不能测试已保存的连接",
"circuit_open": "熔断中,暂不能测试已保存的连接",
"secret_unavailable": "已保存的密码无法使用,请在密码框重新输入后再测试"
},
"saved": "已保存",
"disabled": "已停用"
}
}
+134
View File
@@ -32,5 +32,139 @@
"failure": "健康檢查失敗",
"successDetail": "服務可用:{detail}",
"failureDetail": "服務不可用:{detail}"
},
"nav": {
"home": "概覽",
"datasources": "資料來源",
"create": "新增",
"detail": "詳情"
},
"datasource": {
"list": {
"create": "新增",
"loading": "資料來源載入中",
"loadFailed": "資料來源載入失敗",
"empty": "還沒有資料來源",
"emptyHint": "管理者可以新增第一個資料來源。"
},
"columns": {
"name": "名稱",
"engine": "引擎",
"host": "主機",
"port": "連接埠",
"database": "資料庫名",
"username": "使用者名稱",
"status": "狀態",
"lastTest": "最近測試",
"actions": "操作"
},
"status": {
"enabled": "啟用",
"disabled": "已停用",
"circuitOpen": "熔斷中"
},
"actions": {
"edit": "編輯",
"test": "測試",
"disable": "停用",
"save": "儲存",
"backToList": "返回列表",
"testDisabledWhy": "停用後不能測試",
"testConnection": "測試連線",
"testSaved": "測試已儲存連線",
"enable": "啟用"
},
"denied": {
"title": "無法進入資料來源",
"body": "只有管理者可以進入資料來源介面。"
},
"form": {
"connection": "連線資訊",
"name": "名稱",
"engine": "引擎",
"description": "用途說明",
"host": "主機",
"hostPlaceholder": "例如 db.example.test",
"port": "連接埠",
"database": "資料庫名",
"username": "使用者名稱",
"password": "密碼",
"passwordPlaceholder": "請輸入密碼",
"required": "必填",
"saving": "儲存中",
"invalidRange": "須為 {min}–{max} 的整數"
},
"disabledNote": "該資料來源已停用,不能測試已儲存的連線。點擊「啟用」可恢復。",
"circuit": {
"title": "熔斷保護",
"hint": "已儲存連線在時間窗內連續失敗達到門檻後會熔斷,冷卻期內不能測試,到期後自動恢復。",
"window": "統計視窗(秒)",
"threshold": "失敗門檻(次)",
"cooldown": "冷卻時長(秒)",
"openTitle": "已熔斷",
"openBody": "連續失敗觸發熔斷,{until} 前不能測試已儲存的連線。",
"testBlocked": "熔斷中,{until} 前不能測試"
},
"enabledDone": "已啟用",
"loadFailed": "資料來源載入失敗",
"notFound": "資料來源不存在",
"test": {
"title": "連線測試",
"none": "尚未測試",
"noneDraft": "可在儲存前用目前表單內容測試連線。",
"draftNote": "草稿測試:使用目前表單內容,不會儲存,也不會更新「最近測試」。",
"savedNote": "已儲存連線的測試,結果已記錄到「最近測試」。",
"running": "測試中",
"failedUnknown": "測試未完成,請稍後再試"
},
"category": {
"success": {
"title": "測試成功",
"body": "已連線並完成唯讀探測。"
},
"auth_failed": {
"title": "認證失敗",
"body": "服務端不接受該使用者名稱或密碼。請核對使用者名稱,並在密碼框重新輸入後儲存。"
},
"timeout": {
"title": "逾時",
"body": "在允許的時間內沒有收到服務端回應。可稍後重試,或檢查網路與防火牆。"
},
"unreachable": {
"title": "無法連線",
"body": "無法與目標主機和連接埠建立連線。請核對主機、連接埠,以及網路是否放行。"
},
"rejected": {
"title": "服務端拒絕",
"body": "服務端已回應但拒絕了請求,例如資料庫名不存在。這不是密碼錯誤。"
}
},
"lastTest": {
"success": "成功",
"auth_failed": "認證失敗",
"timeout": "逾時",
"unreachable": "無法連線",
"rejected": "服務端拒絕",
"none": "尚未測試"
},
"refs": {
"title": "引用",
"empty": "尚無引用",
"loadFailed": "引用載入失敗"
},
"disableConfirm": {
"title": "停用資料來源",
"body": "停用後不能測試,記錄仍然保留。確定停用「{name}」嗎?",
"ok": "停用",
"cancel": "取消"
},
"errors": {
"duplicate_name": "名稱已存在,請換一個名稱",
"disabled": "資料來源已停用,不能測試已儲存的連線",
"circuit_open": "熔斷中,暫不能測試已儲存的連線",
"secret_unavailable": "已儲存的密碼無法使用,請在密碼框重新輸入後再測試"
},
"saved": "已儲存",
"disabled": "已停用"
}
}
+3 -1
View File
@@ -2,8 +2,10 @@ import { flushPromises, mount } from "@vue/test-utils";
import { createPinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createI18n } from "vue-i18n";
import { createMemoryHistory } from "vue-router";
import { BusinessError } from "@watchman/api";
import App from "./App.vue";
import { createAppRouter } from "./router";
import zhCN from "../locales/zh-CN/common.json";
import en from "../locales/en/common.json";
@@ -47,7 +49,7 @@ function mountApp(locale = "zh-CN") {
});
return mount(App, {
global: {
plugins: [i18n, createPinia()],
plugins: [i18n, createPinia(), createAppRouter(createMemoryHistory())],
stubs: {
ElConfigProvider: { template: "<div><slot /></div>" },
ElCard: {
+3 -69
View File
@@ -1,19 +1,14 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElAlert, ElButton, ElCard, ElConfigProvider, ElTag } from "element-plus";
import { ElAlert, ElButton, ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import zhTw from "element-plus/es/locale/lang/zh-tw";
import en from "element-plus/es/locale/lang/en";
import th from "element-plus/es/locale/lang/th";
import { BusinessError } from "@watchman/api";
import { api } from "./api";
import {
healthFailureView,
healthSuccessView,
type HealthPayload,
type HealthState,
} from "./health";
import AppShell from "./AppShell.vue";
import LoginPanel from "./LoginPanel.vue";
import { allowsEnter, loadSession, type SessionUser } from "./session";
import { useAuthStore } from "./stores/auth";
@@ -37,7 +32,6 @@ type Screen = "booting" | "login" | "forbidden" | "shell";
const auth = useAuthStore();
const screen = ref<Screen>("booting");
const identity = ref<SessionUser | null>(null);
const state = ref<HealthState>("loading");
const detail = ref("");
function applyIdentity(user: SessionUser): void {
@@ -51,23 +45,6 @@ function applyIdentity(user: SessionUser): void {
auth.login(next);
identity.value = auth.user;
screen.value = allowsEnter(next.roles) ? "shell" : "forbidden";
if (screen.value === "shell") {
void loadHealth();
}
}
async function loadHealth(): Promise<void> {
state.value = "loading";
try {
const data = await api<HealthPayload>("/health");
const view = healthSuccessView(data);
state.value = view.state;
detail.value = view.detail;
} catch (error) {
const view = healthFailureView(error);
state.value = view.state;
detail.value = view.detail;
}
}
async function signOut(): Promise<void> {
@@ -136,49 +113,6 @@ onMounted(async () => {
<ElButton class="mt-6" data-testid="logout" @click="signOut">{{ t("login.logout") }}</ElButton>
</section>
</main>
<main
v-else
class="min-h-screen bg-[var(--bg-surface-soft)] p-8 text-[length:var(--font-size-base)] text-[var(--text-primary)]"
>
<div class="mb-4 flex items-center justify-between gap-4">
<p data-testid="shell-welcome">{{ t("shell.welcome", { name: identity?.display_name }) }}</p>
<ElButton data-testid="logout" @click="signOut">{{ t("login.logout") }}</ElButton>
</div>
<ElCard>
<template #header>
<div class="flex items-center justify-between gap-4">
<span>{{ t("appName") }}</span>
<span data-testid="health-tag">
<ElTag :type="state === 'loading' ? 'info' : state === 'success' ? 'success' : 'danger'">
{{
state === "loading"
? t("health.loading")
: state === "success"
? t("health.success")
: t("health.failure")
}}
</ElTag>
</span>
</div>
</template>
<ElAlert
v-if="state === 'success'"
type="success"
data-testid="health-success"
:title="t('health.successDetail', { detail })"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="state === 'failure'"
type="error"
data-testid="health-failure"
:title="t('health.failureDetail', { detail })"
show-icon
:closable="false"
/>
<p v-else data-testid="health-loading">{{ t("health.loading") }}</p>
</ElCard>
</main>
<AppShell v-else :display-name="identity?.display_name" @logout="signOut" />
</ElConfigProvider>
</template>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
/**
* Signed-in layout: side navigation, a top bar with the breadcrumb, and the routed page.
* The routed page owns its own scrolling, so footers can stay outside the scroll area.
*/
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { RouterLink, RouterView, useRoute } from "vue-router";
import { ElBreadcrumb, ElBreadcrumbItem, ElButton } from "element-plus";
import { allowsDatasources } from "./session";
import { useAuthStore } from "./stores/auth";
defineProps<{ displayName?: string }>();
const emit = defineEmits<{ logout: [] }>();
const { t } = useI18n();
const route = useRoute();
const auth = useAuthStore();
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources" };
const crumbs = computed(() => {
let keys = (route.meta.crumbs as string[] | undefined) ?? [];
// Roles that cannot enter datasources see the list level only.
if (route.path.startsWith("/datasources") && !allowsDatasources(auth.user?.roles ?? [])) {
keys = ["datasources"];
}
const items: { label: string; to?: string }[] = [
{ label: t("appName"), to: keys.length > 0 ? "/" : undefined },
];
keys.forEach((key, index) => {
items.push({
label: t(`nav.${key}`),
to: index < keys.length - 1 ? CRUMB_LINKS[key] : undefined,
});
});
return items;
});
const linkClass =
"block rounded-md px-2.5 py-[7px] text-[var(--text-secondary)] no-underline hover:text-[var(--color-primary)]";
const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
</script>
<template>
<div
class="flex h-screen bg-[var(--bg-surface-soft)] text-[length:var(--font-size-base)] text-[var(--text-primary)]"
>
<aside
class="w-48 shrink-0 border-r border-[var(--border-subtle)] bg-white px-2.5 py-3.5"
data-testid="side-nav"
>
<div class="px-2.5 pb-3.5 text-base font-bold tracking-wide">{{ t("appName") }}</div>
<nav class="flex flex-col gap-1">
<RouterLink to="/" :class="linkClass" :exact-active-class="activeClass" data-testid="nav-home">
{{ t("nav.home") }}
</RouterLink>
<RouterLink
to="/datasources"
:class="linkClass"
:active-class="activeClass"
data-testid="nav-datasources"
>
{{ t("nav.datasources") }}
</RouterLink>
</nav>
</aside>
<div class="flex min-w-0 flex-1 flex-col">
<header
class="flex h-12 shrink-0 items-center justify-between border-b border-[var(--border-subtle)] bg-white px-5"
>
<ElBreadcrumb separator="/" data-testid="breadcrumb">
<ElBreadcrumbItem v-for="item in crumbs" :key="item.label" :to="item.to">
{{ item.label }}
</ElBreadcrumbItem>
</ElBreadcrumb>
<div class="flex items-center gap-3">
<span data-testid="shell-welcome">{{ t("shell.welcome", { name: displayName }) }}</span>
<ElButton data-testid="logout" @click="emit('logout')">{{ t("login.logout") }}</ElButton>
</div>
</header>
<main class="min-h-0 flex-1 overflow-hidden">
<RouterView />
</main>
</div>
</div>
</template>
+73
View File
@@ -0,0 +1,73 @@
<script setup lang="ts">
/** Overview page: the service health card. It loads when the page opens. */
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElAlert, ElCard, ElTag } from "element-plus";
import { api } from "./api";
import {
healthFailureView,
healthSuccessView,
type HealthPayload,
type HealthState,
} from "./health";
const { t } = useI18n();
const state = ref<HealthState>("loading");
const detail = ref("");
async function loadHealth(): Promise<void> {
state.value = "loading";
try {
const data = await api<HealthPayload>("/health");
const view = healthSuccessView(data);
state.value = view.state;
detail.value = view.detail;
} catch (error) {
const view = healthFailureView(error);
state.value = view.state;
detail.value = view.detail;
}
}
onMounted(loadHealth);
</script>
<template>
<div class="h-full overflow-auto p-8">
<ElCard>
<template #header>
<div class="flex items-center justify-between gap-4">
<span>{{ t("appName") }}</span>
<span data-testid="health-tag">
<ElTag :type="state === 'loading' ? 'info' : state === 'success' ? 'success' : 'danger'">
{{
state === "loading"
? t("health.loading")
: state === "success"
? t("health.success")
: t("health.failure")
}}
</ElTag>
</span>
</div>
</template>
<ElAlert
v-if="state === 'success'"
type="success"
data-testid="health-success"
:title="t('health.successDetail', { detail })"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="state === 'failure'"
type="error"
data-testid="health-failure"
:title="t('health.failureDetail', { detail })"
show-icon
:closable="false"
/>
<p v-else data-testid="health-loading">{{ t("health.loading") }}</p>
</ElCard>
</div>
</template>
@@ -0,0 +1,606 @@
<script setup lang="ts">
/**
* Datasource create and detail page (one form, two modes chosen by the route).
* Page buttons live in a footer outside the scrolling body so they stay visible.
* The saved password is never loaded: on edit the password box shows a fixed mask,
* and a blank box keeps the stored password.
* "Test connection" probes the current form values (draft, nothing saved); the saved test
* probes the stored record and needs it enabled with the circuit closed.
*/
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElMessage,
ElMessageBox,
ElOption,
ElSelect,
type FormInstance,
type FormRules,
} from "element-plus";
import { BusinessError } from "@watchman/api";
import {
createDatasource,
disableDatasource,
enableDatasource,
getDatasource,
getReferences,
testDatasource,
testDraftDatasource,
updateDatasource,
} from "./client";
import { describeError } from "./errors";
import { failureCategory, formatDateTime } from "./format";
import { buildCreatePayload, buildDraftTestPayload, buildUpdatePayload } from "./payload";
import SecretInput from "./SecretInput.vue";
import {
CIRCUIT_DEFAULTS,
CIRCUIT_SECONDS_RANGE,
CIRCUIT_THRESHOLD_RANGE,
ENGINES,
type Datasource,
type DatasourceForm,
type TestCategory,
} from "./types";
import { isFilledText, isIntegerInRange } from "./validation";
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const isCreate = route.name === "datasource-create";
const datasourceId = isCreate ? "" : String(route.params.id ?? "");
/** "draft" probes the form values; "saved" probes the stored record and updates last_test. */
type TestSource = "draft" | "saved";
type TestView =
| { state: "idle" }
| { state: "running" }
| { state: "done"; source: TestSource; category: TestCategory; at: string | null }
| { state: "error"; source: TestSource; text: string };
const DRAFT_FIELDS = ["engine", "host", "port", "database_name", "username", "password"];
const formRef = ref<FormInstance>();
const record = ref<Datasource | null>(null);
const loaded = ref(isCreate);
const loadError = ref("");
const saving = ref(false);
const saveError = ref("");
const testView = ref<TestView>({ state: "idle" });
const references = ref<{ name?: string; id?: string }[] | null>(null);
const referencesError = ref("");
const form = reactive<DatasourceForm>({
name: "",
description: "",
engine: "postgresql",
host: "",
port: ENGINES[0].port,
database_name: "",
username: "",
password: "",
// Create does not send these (the server defaults apply); they are edited on the detail page.
circuit_failure_window_seconds: CIRCUIT_DEFAULTS.window,
circuit_failure_threshold: CIRCUIT_DEFAULTS.threshold,
circuit_open_cooldown_seconds: CIRCUIT_DEFAULTS.cooldown,
});
type Validator = (rule: unknown, value: unknown, callback: (error?: Error) => void) => void;
const trigger = ["blur", "change"];
const requiredText = () => ({
validator: ((_rule, value, callback) =>
isFilledText(value) ? callback() : callback(new Error(t("datasource.form.required")))) as Validator,
trigger,
});
const integerIn = (min: number, max: number, message: () => string) => ({
validator: ((_rule, value, callback) => {
if (value === null || value === undefined || value === "") {
return callback(new Error(t("datasource.form.required")));
}
return isIntegerInRange(value, min, max) ? callback() : callback(new Error(message()));
}) as Validator,
trigger,
});
const rangeMessage = (min: number, max: number) => () => t("datasource.form.invalidRange", { min, max });
const secondsRule = () =>
integerIn(CIRCUIT_SECONDS_RANGE.min, CIRCUIT_SECONDS_RANGE.max, rangeMessage(CIRCUIT_SECONDS_RANGE.min, CIRCUIT_SECONDS_RANGE.max));
const thresholdRule = () =>
integerIn(CIRCUIT_THRESHOLD_RANGE.min, CIRCUIT_THRESHOLD_RANGE.max, rangeMessage(CIRCUIT_THRESHOLD_RANGE.min, CIRCUIT_THRESHOLD_RANGE.max));
const rules = computed<FormRules>(() => ({
name: [requiredText()],
engine: [requiredText()],
// Host is required only; the probe decides whether it is usable.
host: [requiredText()],
port: [integerIn(1, 65535, rangeMessage(1, 65535))],
database_name: [requiredText()],
username: [requiredText()],
// A new datasource needs a password. On edit, blank keeps the stored one.
password: isCreate ? [requiredText()] : [],
circuit_failure_window_seconds: isCreate ? [] : [secondsRule()],
circuit_failure_threshold: isCreate ? [] : [thresholdRule()],
circuit_open_cooldown_seconds: isCreate ? [] : [secondsRule()],
}));
const recordEnabled = computed(() => record.value?.enabled === true);
const circuitOpen = computed(() => record.value?.circuit_state === "open");
const circuitUntil = computed(() => formatDateTime(record.value?.circuit_open_until ?? null));
const busy = computed(() => saving.value || testView.value.state === "running");
/** List ?test=1 runs a saved probe; needs enabled + circuit closed. */
const canSavedTest = computed(() => !isCreate && recordEnabled.value && !circuitOpen.value);
function applyRecord(row: Datasource): void {
record.value = row;
form.circuit_failure_window_seconds = row.circuit_failure_window_seconds;
form.circuit_failure_threshold = row.circuit_failure_threshold;
form.circuit_open_cooldown_seconds = row.circuit_open_cooldown_seconds;
form.name = row.name;
form.description = row.description ?? "";
form.engine = row.engine;
form.host = row.host;
form.port = row.port;
form.database_name = row.database_name;
form.username = row.username;
form.password = "";
}
function onEngineChange(value: string): void {
// The default port follows the engine only while creating.
if (!isCreate) {
return;
}
const engine = ENGINES.find((item) => item.value === value);
if (engine) {
form.port = engine.port;
}
}
function backToList(): void {
void router.push({ name: "datasource-list" });
}
async function save(): Promise<void> {
saveError.value = "";
const valid = await formRef.value?.validate().catch(() => false);
if (!valid) {
return;
}
saving.value = true;
try {
if (isCreate) {
await createDatasource(buildCreatePayload(form));
} else {
await updateDatasource(datasourceId, buildUpdatePayload(form));
}
ElMessage.success(t("datasource.saved"));
backToList();
} catch (error) {
saveError.value = describeError(error, t, te, "datasource.loadFailed");
} finally {
saving.value = false;
}
}
async function validateFields(props: string[]): Promise<boolean> {
try {
await formRef.value?.validateField(props);
return formRef.value !== undefined;
} catch {
return false;
}
}
/** Re-read the record (circuit state, last test) without touching what the user typed. */
async function refreshRecord(): Promise<void> {
try {
record.value = await getDatasource(datasourceId);
} catch {
// The test result is already on screen; a failed refresh keeps the previous state.
}
}
/** Probe the current form values. Works before saving; nothing is stored on the server. */
async function runDraftTest(): Promise<void> {
if (busy.value || !(await validateFields(DRAFT_FIELDS))) {
return;
}
testView.value = { state: "running" };
try {
const outcome = await testDraftDatasource(buildDraftTestPayload(form, isCreate ? undefined : datasourceId));
testView.value = { state: "done", source: "draft", category: outcome.category, at: null };
} catch (error) {
const category = failureCategory(error);
testView.value = category
? { state: "done", source: "draft", category, at: null }
: { state: "error", source: "draft", text: describeError(error, t, te, "datasource.test.failedUnknown") };
}
}
/** Probe the stored record. Needs it enabled with the circuit closed. */
async function runSavedTest(): Promise<void> {
if (!canSavedTest.value || busy.value) {
return;
}
testView.value = { state: "running" };
try {
const outcome = await testDatasource(datasourceId);
testView.value = { state: "done", source: "saved", category: outcome.category, at: outcome.last_test_at };
} catch (error) {
const category = failureCategory(error);
if (category) {
testView.value = { state: "done", source: "saved", category, at: null };
} else if (error instanceof BusinessError && error.details.reason === "circuit_open") {
const until = formatDateTime(String(error.details.circuit_open_until ?? ""));
testView.value = { state: "error", source: "saved", text: t("datasource.circuit.testBlocked", { until }) };
} else {
testView.value = {
state: "error",
source: "saved",
text: describeError(error, t, te, "datasource.test.failedUnknown"),
};
}
}
// A saved test records last_test and can open the circuit, so show the stored state.
await refreshRecord();
}
async function enable(): Promise<void> {
saveError.value = "";
try {
record.value = await enableDatasource(datasourceId);
ElMessage.success(t("datasource.enabledDone"));
} catch (error) {
saveError.value = describeError(error, t, te, "datasource.loadFailed");
}
}
async function disable(): Promise<void> {
if (!record.value) {
return;
}
try {
await ElMessageBox.confirm(
t("datasource.disableConfirm.body", { name: record.value.name }),
t("datasource.disableConfirm.title"),
{
type: "warning",
confirmButtonText: t("datasource.disableConfirm.ok"),
cancelButtonText: t("datasource.disableConfirm.cancel"),
},
);
} catch {
return;
}
try {
await disableDatasource(datasourceId);
ElMessage.success(t("datasource.disabled"));
backToList();
} catch (error) {
saveError.value = describeError(error, t, te, "datasource.loadFailed");
}
}
async function loadReferences(): Promise<void> {
try {
references.value = (await getReferences(datasourceId)).items as { name?: string; id?: string }[];
} catch (error) {
referencesError.value = describeError(error, t, te, "datasource.refs.loadFailed");
}
}
onMounted(async () => {
if (isCreate) {
return;
}
try {
applyRecord(await getDatasource(datasourceId));
loaded.value = true;
} catch (error) {
const notFound = error instanceof BusinessError && error.status === 404;
loadError.value = notFound
? t("datasource.notFound")
: describeError(error, t, te, "datasource.loadFailed");
return;
}
void loadReferences();
// The list's "test" action arrives with ?test=1 and runs the test once.
if (route.query.test === "1") {
void router.replace({ name: "datasource-detail", params: { id: datasourceId } });
await runSavedTest();
}
});
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="datasource-scroll">
<ElAlert
v-if="loadError"
type="error"
data-testid="datasource-load-error"
:title="loadError"
show-icon
:closable="false"
/>
<template v-else-if="loaded">
<ElAlert
v-if="!isCreate && record && !record.enabled"
class="mb-3.5"
type="warning"
data-testid="datasource-disabled-note"
:title="t('datasource.disabledNote')"
show-icon
:closable="false"
/>
<ElAlert
v-if="saveError"
class="mb-3.5"
type="error"
data-testid="datasource-save-error"
:title="saveError"
show-icon
:closable="false"
/>
<ElForm
ref="formRef"
:model="form"
:rules="rules"
label-position="top"
data-testid="datasource-form"
@submit.prevent
>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("datasource.form.connection") }}</h3>
<div class="grid max-w-3xl grid-cols-1 gap-x-6 sm:grid-cols-2">
<ElFormItem :label="t('datasource.form.name')" prop="name" data-testid="field-name">
<ElInput v-model="form.name" />
</ElFormItem>
<ElFormItem :label="t('datasource.form.engine')" prop="engine" data-testid="field-engine">
<ElSelect
v-model="form.engine"
class="w-full"
@change="onEngineChange"
>
<ElOption
v-for="engine in ENGINES"
:key="engine.value"
:label="engine.label"
:value="engine.value"
/>
</ElSelect>
</ElFormItem>
<ElFormItem
:label="t('datasource.form.description')"
prop="description"
class="sm:col-span-2"
data-testid="field-description"
>
<ElInput v-model="form.description" type="textarea" :rows="2" />
</ElFormItem>
<ElFormItem :label="t('datasource.form.host')" prop="host" data-testid="field-host">
<ElInput
v-model="form.host"
:placeholder="t('datasource.form.hostPlaceholder')"
/>
</ElFormItem>
<ElFormItem :label="t('datasource.form.port')" prop="port" data-testid="field-port">
<ElInputNumber
v-model="form.port"
style="width: 100%"
:controls="false"
:precision="0"
align="left"
/>
</ElFormItem>
<ElFormItem :label="t('datasource.form.database')" prop="database_name" data-testid="field-database">
<ElInput v-model="form.database_name" />
</ElFormItem>
<ElFormItem :label="t('datasource.form.username')" prop="username" data-testid="field-username">
<ElInput v-model="form.username" autocomplete="off" />
</ElFormItem>
<ElFormItem :label="t('datasource.form.password')" prop="password" data-testid="field-password">
<SecretInput
v-model="form.password"
:maskable="!isCreate"
:placeholder="t('datasource.form.passwordPlaceholder')"
/>
</ElFormItem>
</div>
</section>
<section
v-if="!isCreate"
class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4"
data-testid="datasource-circuit"
>
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("datasource.circuit.title") }}</h3>
<p class="mb-3 text-[var(--text-secondary)]">{{ t("datasource.circuit.hint") }}</p>
<ElAlert
v-if="circuitOpen"
class="mb-3.5"
type="warning"
data-testid="circuit-open-alert"
:title="t('datasource.circuit.openTitle')"
:description="t('datasource.circuit.openBody', { until: circuitUntil })"
show-icon
:closable="false"
/>
<div class="grid max-w-3xl grid-cols-1 gap-x-6 sm:grid-cols-3">
<ElFormItem
:label="t('datasource.circuit.window')"
prop="circuit_failure_window_seconds"
data-testid="field-circuit-window"
>
<ElInputNumber
v-model="form.circuit_failure_window_seconds"
style="width: 100%"
:controls="false"
:precision="0"
align="left"
/>
</ElFormItem>
<ElFormItem
:label="t('datasource.circuit.threshold')"
prop="circuit_failure_threshold"
data-testid="field-circuit-threshold"
>
<ElInputNumber
v-model="form.circuit_failure_threshold"
style="width: 100%"
:controls="false"
:precision="0"
align="left"
/>
</ElFormItem>
<ElFormItem
:label="t('datasource.circuit.cooldown')"
prop="circuit_open_cooldown_seconds"
data-testid="field-circuit-cooldown"
>
<ElInputNumber
v-model="form.circuit_open_cooldown_seconds"
style="width: 100%"
:controls="false"
:precision="0"
align="left"
/>
</ElFormItem>
</div>
</section>
</ElForm>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("datasource.test.title") }}</h3>
<ElAlert
v-if="testView.state === 'running'"
type="info"
data-testid="test-running"
:title="t('datasource.test.running')"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="testView.state === 'error'"
type="error"
data-testid="test-error"
:title="testView.text"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="testView.state === 'done'"
:type="
testView.category === 'success' ? 'success' : testView.category === 'timeout' ? 'warning' : 'error'
"
data-testid="test-result"
:data-category="testView.category"
:data-source="testView.source"
:title="t(`datasource.category.${testView.category}.title`)"
:description="t(`datasource.category.${testView.category}.body`)"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="record?.last_test_category"
:type="
record.last_test_category === 'success'
? 'success'
: record.last_test_category === 'timeout'
? 'warning'
: 'error'
"
data-testid="test-last"
:data-category="record.last_test_category"
:title="`${t(`datasource.category.${record.last_test_category}.title`)} ${formatDateTime(record.last_test_at)}`"
:description="t(`datasource.category.${record.last_test_category}.body`)"
show-icon
:closable="false"
/>
<p
v-else
data-testid="test-none"
class="rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-surface-soft)] px-3 py-2 text-[var(--text-secondary)]"
>
{{ isCreate ? t("datasource.test.noneDraft") : t("datasource.test.none") }}
</p>
<p
v-if="testView.state === 'done' || testView.state === 'error'"
class="mt-2 text-xs text-[var(--text-secondary)]"
data-testid="test-source-note"
>
{{ testView.source === "draft" ? t("datasource.test.draftNote") : t("datasource.test.savedNote") }}
</p>
</section>
<section
v-if="!isCreate"
class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4"
data-testid="datasource-references"
>
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("datasource.refs.title") }}</h3>
<ElAlert
v-if="referencesError"
type="error"
:title="referencesError"
show-icon
:closable="false"
/>
<ul v-else-if="references && references.length > 0" data-testid="references-list">
<li v-for="(item, index) in references" :key="item.id ?? index">{{ item.name ?? item.id }}</li>
</ul>
<p
v-else-if="references"
data-testid="references-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-5 text-center text-[var(--text-secondary)]"
>
{{ t("datasource.refs.empty") }}
</p>
</section>
</template>
</div>
<footer
data-testid="datasource-footer"
class="flex shrink-0 items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
>
<ElButton
v-if="loaded && !loadError"
type="primary"
data-testid="footer-save"
:loading="saving"
:disabled="testView.state === 'running'"
@click="save"
>
{{ t("datasource.actions.save") }}
</ElButton>
<ElButton v-if="loaded && !loadError" data-testid="footer-test" :disabled="busy" @click="runDraftTest">
{{ t("datasource.actions.testConnection") }}
</ElButton>
<template v-if="!isCreate && loaded && !loadError">
<ElButton
v-if="recordEnabled"
type="danger"
plain
data-testid="footer-disable"
:disabled="busy"
@click="disable"
>
{{ t("datasource.actions.disable") }}
</ElButton>
<ElButton v-else type="success" plain data-testid="footer-enable" :disabled="busy" @click="enable">
{{ t("datasource.actions.enable") }}
</ElButton>
</template>
<ElButton data-testid="footer-back" @click="backToList">{{ t("datasource.actions.backToList") }}</ElButton>
</footer>
</div>
</template>
@@ -0,0 +1,29 @@
<script setup lang="ts">
/**
* Gate for every datasource page. Only watchman-admin sees the child routes.
* Other signed-in roles get the "cannot enter" panel, and no child page is created,
* so no datasource request is sent for them. The backend enforces the same rule.
*/
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { RouterView } from "vue-router";
import { allowsDatasources } from "../session";
import { useAuthStore } from "../stores/auth";
const { t } = useI18n();
const auth = useAuthStore();
const allowed = computed(() => allowsDatasources(auth.user?.roles ?? []));
</script>
<template>
<RouterView v-if="allowed" />
<div v-else class="h-full overflow-auto p-5">
<div
data-testid="datasource-denied"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("datasource.denied.title") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("datasource.denied.body") }}</p>
</div>
</div>
</template>
@@ -0,0 +1,235 @@
<script setup lang="ts">
/**
* Datasource list. The page button sits above the table, right aligned.
* Row actions stay in the row. Disabled rows stay visible, can be enabled again and cannot be
* tested; rows with an open circuit cannot be tested until the cooldown ends.
*/
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElMessage,
ElMessageBox,
ElTable,
ElTableColumn,
vLoading,
} from "element-plus";
import { disableDatasource, enableDatasource, listDatasources } from "./client";
import { describeError } from "./errors";
import { engineLabel, formatDateTime } from "./format";
import type { Datasource } from "./types";
const { t, te } = useI18n();
const router = useRouter();
const items = ref<Datasource[]>([]);
const loading = ref(true);
const loadError = ref("");
async function load(): Promise<void> {
loading.value = true;
loadError.value = "";
try {
items.value = (await listDatasources()).items;
} catch (error) {
loadError.value = describeError(error, t, te, "datasource.list.loadFailed");
} finally {
loading.value = false;
}
}
// Table slots type their rows loosely, so row handlers take the slot row and narrow it here.
function asRow(source: unknown): Datasource {
return source as Datasource;
}
function rowClass({ row }: { row: unknown }): string {
return asRow(row).enabled ? "" : "datasource-row-off";
}
function lastTestText(source: unknown): string {
const row = asRow(source);
if (!row.last_test_category) {
return t("datasource.lastTest.none");
}
const when = formatDateTime(row.last_test_at);
const result = t(`datasource.lastTest.${row.last_test_category}`);
return when ? `${when} ${result}` : result;
}
function openCreate(): void {
void router.push({ name: "datasource-create" });
}
function openDetail(source: unknown): void {
void router.push({ name: "datasource-detail", params: { id: asRow(source).id } });
}
/** The detail page runs the test on arrival, so the result shows in the same place as there. */
function openTest(source: unknown): void {
void router.push({
name: "datasource-detail",
params: { id: asRow(source).id },
query: { test: "1" },
});
}
function testBlocked(source: unknown): boolean {
const row = asRow(source);
return !row.enabled || row.circuit_state === "open";
}
function circuitWhy(source: unknown): string {
return t("datasource.circuit.testBlocked", { until: formatDateTime(asRow(source).circuit_open_until) });
}
function testTitle(source: unknown): string | undefined {
const row = asRow(source);
if (!row.enabled) {
return t("datasource.actions.testDisabledWhy");
}
return row.circuit_state === "open" ? circuitWhy(row) : undefined;
}
async function enable(source: unknown): Promise<void> {
const row = asRow(source);
try {
await enableDatasource(row.id);
ElMessage.success(t("datasource.enabledDone"));
await load();
} catch (error) {
ElMessage.error(describeError(error, t, te, "datasource.loadFailed"));
}
}
async function disable(source: unknown): Promise<void> {
const row = asRow(source);
try {
await ElMessageBox.confirm(
t("datasource.disableConfirm.body", { name: row.name }),
t("datasource.disableConfirm.title"),
{
type: "warning",
confirmButtonText: t("datasource.disableConfirm.ok"),
cancelButtonText: t("datasource.disableConfirm.cancel"),
},
);
} catch {
return;
}
try {
await disableDatasource(row.id);
ElMessage.success(t("datasource.disabled"));
await load();
} catch (error) {
ElMessage.error(describeError(error, t, te, "datasource.loadFailed"));
}
}
onMounted(load);
</script>
<template>
<div class="h-full overflow-auto p-5" data-testid="datasource-list">
<div class="mb-3 flex justify-end">
<ElButton type="primary" data-testid="datasource-create" @click="openCreate">
{{ t("datasource.list.create") }}
</ElButton>
</div>
<ElAlert
v-if="loadError"
type="error"
data-testid="datasource-load-error"
:title="loadError"
show-icon
:closable="false"
/>
<div
v-else-if="!loading && items.length === 0"
data-testid="datasource-empty"
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("datasource.list.empty") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("datasource.list.emptyHint") }}</p>
</div>
<ElTable
v-else
v-loading="loading"
:data="items"
data-testid="datasource-table"
:row-class-name="rowClass"
>
<ElTableColumn prop="name" :label="t('datasource.columns.name')" min-width="140" />
<ElTableColumn :label="t('datasource.columns.engine')" min-width="110">
<template #default="{ row }">{{ engineLabel(row.engine) }}</template>
</ElTableColumn>
<ElTableColumn prop="host" :label="t('datasource.columns.host')" min-width="170" />
<ElTableColumn prop="port" :label="t('datasource.columns.port')" width="80" />
<ElTableColumn prop="database_name" :label="t('datasource.columns.database')" min-width="130" />
<ElTableColumn prop="username" :label="t('datasource.columns.username')" min-width="130" />
<ElTableColumn :label="t('datasource.columns.status')" min-width="150">
<template #default="{ row }">
<span class="inline-flex items-center gap-1.5">
<span
class="h-[7px] w-[7px] rounded-full"
:class="row.enabled ? 'bg-[#1a7f37]' : 'bg-[var(--text-muted)]'"
/>
{{ row.enabled ? t("datasource.status.enabled") : t("datasource.status.disabled") }}
<span v-if="row.circuit_state === 'open'" class="text-xs text-[#cf222e]" data-testid="row-circuit-open">
{{ t("datasource.status.circuitOpen") }}
</span>
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('datasource.columns.lastTest')" min-width="190">
<template #default="{ row }">
<span
:class="
row.last_test_category === 'success'
? 'text-[#1a7f37]'
: row.last_test_category
? 'text-[#cf222e]'
: 'text-[var(--text-muted)]'
"
>
{{ lastTestText(row) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('datasource.columns.actions')" width="148" fixed="right">
<template #default="{ row }">
<div class="whitespace-nowrap" :data-testid="`datasource-row-${row.id}`">
<ElButton link type="primary" data-testid="row-edit" @click="openDetail(row)">
{{ t("datasource.actions.edit") }}
</ElButton>
<ElButton
link
type="primary"
data-testid="row-test"
:disabled="testBlocked(row)"
:title="testTitle(row)"
@click="openTest(row)"
>
{{ t("datasource.actions.test") }}
</ElButton>
<ElButton v-if="row.enabled" link type="danger" data-testid="row-disable" @click="disable(row)">
{{ t("datasource.actions.disable") }}
</ElButton>
<ElButton v-else link type="success" data-testid="row-enable" @click="enable(row)">
{{ t("datasource.actions.enable") }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
</div>
</template>
<style scoped>
:deep(.datasource-row-off td) {
color: var(--text-muted);
}
</style>
@@ -0,0 +1,108 @@
import { flushPromises, mount } from "@vue/test-utils";
import { describe, expect, it } from "vitest";
import { defineComponent, ref } from "vue";
import SecretInput from "./SecretInput.vue";
import { buildUpdatePayload } from "./payload";
import { SECRET_MASK, type DatasourceForm } from "./types";
// A stand-in for a saved password. The API never returns it, so it must never be rendered.
const SAVED_SECRET = "saved-secret-should-never-render";
async function mountEdit() {
const Host = defineComponent({
components: { SecretInput },
setup() {
const password = ref("");
return { password };
},
template: '<SecretInput v-model="password" maskable />',
});
const wrapper = mount(Host, { attachTo: document.body });
// Element Plus attaches its focus listener after the first flush.
await flushPromises();
const input = wrapper.get("input");
const model = () => (wrapper.vm as unknown as { password: string }).password;
return { wrapper, input, model };
}
function payloadFor(password: string) {
const form: DatasourceForm = {
name: "n",
description: "",
engine: "postgresql",
host: "h",
port: 5432,
database_name: "d",
username: "u",
password,
circuit_failure_window_seconds: 300,
circuit_failure_threshold: 3,
circuit_open_cooldown_seconds: 600,
};
return buildUpdatePayload(form);
}
describe("SecretInput password mask", () => {
it("is an Element Plus password input with the reveal toggle", async () => {
const { wrapper, input } = await mountEdit();
expect(input.attributes("type")).toBe("password");
expect(wrapper.find(".el-input__password").exists()).toBe(true);
wrapper.unmount();
});
it("edit shows a fixed-length mask and never the saved secret", async () => {
const { wrapper, input } = await mountEdit();
expect((input.element as HTMLInputElement).value).toBe(SECRET_MASK);
expect(wrapper.html()).not.toContain(SAVED_SECRET);
wrapper.unmount();
});
it("focus clears the mask without changing the model", async () => {
const { wrapper, input, model } = await mountEdit();
await input.trigger("focus");
await flushPromises();
expect((input.element as HTMLInputElement).value).toBe("");
expect(model()).toBe("");
wrapper.unmount();
});
it("blank after focus restores the mask on blur", async () => {
const { wrapper, input } = await mountEdit();
await input.trigger("focus");
await flushPromises();
await input.trigger("blur");
await flushPromises();
expect((input.element as HTMLInputElement).value).toBe(SECRET_MASK);
wrapper.unmount();
});
it("blank means the payload omits the password", async () => {
const { wrapper, input, model } = await mountEdit();
await input.trigger("focus");
await flushPromises();
await input.trigger("blur");
await flushPromises();
expect("password" in payloadFor(model())).toBe(false);
wrapper.unmount();
});
it("a typed value reaches the model and the payload, and the mask stays away", async () => {
const { wrapper, input, model } = await mountEdit();
await input.trigger("focus");
await flushPromises();
await input.setValue("typed-new-secret");
await flushPromises();
await input.trigger("blur");
await flushPromises();
expect(model()).toBe("typed-new-secret");
expect((input.element as HTMLInputElement).value).toBe("typed-new-secret");
expect(payloadFor(model()).password).toBe("typed-new-secret");
wrapper.unmount();
});
it("create mode shows an empty box, not the mask", () => {
const wrapper = mount(SecretInput, { props: { modelValue: "" } });
expect((wrapper.get("input").element as HTMLInputElement).value).toBe("");
wrapper.unmount();
});
});
@@ -0,0 +1,49 @@
<script setup lang="ts">
/**
* Password field for a datasource.
* Uses el-input with show-password. When `maskable` is set (editing a saved datasource) the
* box shows a fixed-length placeholder instead of any saved value. Focus clears it, and a
* blank box on blur restores it. The placeholder is never emitted as the value.
*/
import { computed, ref } from "vue";
import { ElInput } from "element-plus";
import { SECRET_MASK } from "./types";
const props = defineProps<{
modelValue: string;
maskable?: boolean;
placeholder?: string;
}>();
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
const masked = ref(Boolean(props.maskable) && props.modelValue === "");
const shown = computed(() => (masked.value ? SECRET_MASK : props.modelValue));
function onFocus(): void {
masked.value = false;
}
function onBlur(): void {
if (props.maskable && props.modelValue === "") {
masked.value = true;
}
}
function onInput(value: string): void {
masked.value = false;
emit("update:modelValue", value);
}
</script>
<template>
<ElInput
:model-value="shown"
type="password"
show-password
autocomplete="new-password"
:placeholder="placeholder"
@focus="onFocus"
@blur="onBlur"
@update:model-value="onInput"
/>
</template>
@@ -0,0 +1,66 @@
/** Calls to the /datasources routes. Each one returns the unwrapped envelope data. */
import { api } from "../api";
import type { CreatePayload, DraftTestPayload, UpdatePayload } from "./payload";
import type {
ConnectionTestOutcome,
Datasource,
DatasourceList,
DatasourceReferences,
DraftTestOutcome,
} from "./types";
const JSON_HEADERS = { "Content-Type": "application/json" };
export function listDatasources(): Promise<DatasourceList> {
return api<DatasourceList>("/datasources");
}
export function getDatasource(id: string): Promise<Datasource> {
return api<Datasource>(`/datasources/${encodeURIComponent(id)}`);
}
export function createDatasource(payload: CreatePayload): Promise<Datasource> {
return api<Datasource>("/datasources", {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
export function updateDatasource(id: string, payload: UpdatePayload): Promise<Datasource> {
return api<Datasource>(`/datasources/${encodeURIComponent(id)}`, {
method: "PATCH",
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
export function disableDatasource(id: string): Promise<Datasource> {
return api<Datasource>(`/datasources/${encodeURIComponent(id)}/disable`, { method: "POST" });
}
/** Enabling does not touch the circuit state and needs no prior test. */
export function enableDatasource(id: string): Promise<Datasource> {
return api<Datasource>(`/datasources/${encodeURIComponent(id)}/enable`, { method: "POST" });
}
/** Probe the form's values without saving. A failed probe throws like the saved test. */
export function testDraftDatasource(payload: DraftTestPayload): Promise<DraftTestOutcome> {
return api<DraftTestOutcome>("/datasources/test-draft", {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify(payload),
});
}
/** A failed probe is HTTP 400 code 40000 with details.category, so it throws BusinessError. */
export function testDatasource(id: string): Promise<ConnectionTestOutcome> {
return api<ConnectionTestOutcome>(`/datasources/${encodeURIComponent(id)}/test`, {
method: "POST",
});
}
export function getReferences(id: string): Promise<DatasourceReferences> {
return api<DatasourceReferences>(`/datasources/${encodeURIComponent(id)}/references`);
}
@@ -0,0 +1,20 @@
/** Turns a failed API call into one line for the user. No server message text is shown. */
import { BusinessError } from "@watchman/api";
type Translate = (key: string) => string;
type Exists = (key: string) => boolean;
export function describeError(error: unknown, t: Translate, te: Exists, fallbackKey: string): string {
if (!(error instanceof BusinessError)) {
return t(fallbackKey);
}
const reason = error.details.reason;
if (typeof reason === "string" && te(`datasource.errors.${reason}`)) {
return t(`datasource.errors.${reason}`);
}
if (te(`codes.${error.code}`)) {
return `${t(`codes.${error.code}`)} (${error.code})`;
}
return `${t(fallbackKey)} (${error.code})`;
}
@@ -0,0 +1,40 @@
/** Display helpers for datasource rows. */
import { BusinessError } from "@watchman/api";
import { ENGINES, FAILURE_CATEGORIES, type TestCategory } from "./types";
export function engineLabel(engine: string): string {
return ENGINES.find((item) => item.value === engine)?.label ?? engine;
}
function pad(value: number): string {
return String(value).padStart(2, "0");
}
/** "2026-11-17 09:12" in the browser's time zone, or an empty string when unset or invalid. */
export function formatDateTime(iso: string | null): string {
if (!iso) {
return "";
}
const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return "";
}
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
export function isTestCategory(value: unknown): value is TestCategory {
return value === "success" || FAILURE_CATEGORIES.includes(value as TestCategory);
}
/**
* The category of a failed connection test, or null when the error is something else.
* Only the category is used; any message text from the server is not shown.
*/
export function failureCategory(error: unknown): TestCategory | null {
if (!(error instanceof BusinessError) || error.code !== 40000) {
return null;
}
const category = error.details.category;
return isTestCategory(category) && category !== "success" ? category : null;
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import zhCN from "../../locales/zh-CN/common.json";
import zhTW from "../../locales/zh-TW/common.json";
import en from "../../locales/en/common.json";
import th from "../../locales/th/common.json";
function leafKeys(value: unknown, prefix = ""): string[] {
if (value === null || typeof value !== "object") {
return [prefix];
}
return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>
leafKeys(child, prefix ? `${prefix}.${key}` : key),
);
}
describe("datasource locale keys", () => {
const base = leafKeys((zhCN as { datasource: unknown }).datasource).sort();
it.each([
["zh-TW", zhTW],
["en", en],
["th", th],
])("%s has the same datasource keys as zh-CN", (_name, messages) => {
expect(leafKeys((messages as { datasource: unknown }).datasource).sort()).toEqual(base);
});
it("has the D23 strings", () => {
for (const key of [
"datasource.actions.testConnection",
"datasource.actions.enable",
"datasource.circuit.openBody",
"datasource.errors.circuit_open",
"datasource.form.invalidRange",
]) {
expect(leafKeys(zhCN)).toContain(key);
}
});
});
@@ -0,0 +1,98 @@
import { describe, expect, it } from "vitest";
import { buildCreatePayload, buildDraftTestPayload, buildUpdatePayload } from "./payload";
import { SECRET_MASK, type DatasourceForm } from "./types";
function form(overrides: Partial<DatasourceForm> = {}): DatasourceForm {
return {
name: " 产线工艺库 ",
description: "",
engine: "postgresql",
host: "db.example.test",
port: 5432,
database_name: "process_demo",
username: "readonly_demo",
password: "",
circuit_failure_window_seconds: 300,
circuit_failure_threshold: 3,
circuit_open_cooldown_seconds: 600,
...overrides,
};
}
describe("datasource payloads", () => {
it("create sends the typed password and trims text fields", () => {
const payload = buildCreatePayload(form({ password: "typed-by-user" }));
expect(payload.password).toBe("typed-by-user");
expect(payload.name).toBe("产线工艺库");
expect(payload.description).toBeNull();
});
it("edit with a blank password omits the password key", () => {
const payload = buildUpdatePayload(form({ password: "" }));
expect("password" in payload).toBe(false);
expect(JSON.stringify(payload)).not.toContain("password");
});
it("edit with a spaces-only password omits the password key", () => {
expect("password" in buildUpdatePayload(form({ password: " " }))).toBe(false);
});
it("edit with a typed password sends it", () => {
expect(buildUpdatePayload(form({ password: "new-secret-value" })).password).toBe("new-secret-value");
});
it("never carries the mask placeholder unless the user typed it into the model", () => {
// The mask lives only inside SecretInput; the form model stays blank until the user types.
expect(JSON.stringify(buildUpdatePayload(form()))).not.toContain(SECRET_MASK);
});
it("never sends the read-only intent", () => {
expect("read_only_intent" in buildCreatePayload(form({ password: "x" }))).toBe(false);
expect("read_only_intent" in buildUpdatePayload(form())).toBe(false);
});
it("create sends no circuit fields (the server defaults apply)", () => {
const body = JSON.stringify(buildCreatePayload(form({ password: "x" })));
expect(body).not.toContain("circuit");
});
it("edit sends the three circuit parameters as numbers", () => {
const payload = buildUpdatePayload(
form({
circuit_failure_window_seconds: 120,
circuit_failure_threshold: 5,
circuit_open_cooldown_seconds: 900,
}),
);
expect(payload.circuit_failure_window_seconds).toBe(120);
expect(payload.circuit_failure_threshold).toBe(5);
expect(payload.circuit_open_cooldown_seconds).toBe(900);
});
});
describe("draft test payload", () => {
it("create sends the typed password and no datasource_id", () => {
const payload = buildDraftTestPayload(form({ password: "typed-by-user" }));
expect(payload.password).toBe("typed-by-user");
expect("datasource_id" in payload).toBe(false);
expect(payload.host).toBe("db.example.test");
});
it("edit with a blank password sends the id and no password key", () => {
const payload = buildDraftTestPayload(form({ password: " " }), "ds-1");
expect(payload.datasource_id).toBe("ds-1");
expect("password" in payload).toBe(false);
});
it("edit with a typed password sends both, never the mask", () => {
const payload = buildDraftTestPayload(form({ password: "new-pw" }), "ds-1");
expect(payload.password).toBe("new-pw");
expect(payload.datasource_id).toBe("ds-1");
expect(JSON.stringify(payload)).not.toContain(SECRET_MASK);
});
it("carries only connection fields", () => {
const keys = Object.keys(buildDraftTestPayload(form({ password: "x" }), "ds-1")).sort();
expect(keys).toEqual(["database_name", "datasource_id", "engine", "host", "password", "port", "username"]);
});
});
@@ -0,0 +1,90 @@
/**
* Request bodies for create, update and draft test.
* The saved password is never in the form, so an edit that leaves the password blank
* must send no password key at all.
*/
import type { DatasourceForm } from "./types";
type CommonFields = {
name: string;
description: string | null;
engine: string;
host: string;
port: number;
database_name: string;
username: string;
};
export type CreatePayload = CommonFields & { password: string };
/** Circuit parameters are edited on the detail page only; create relies on server defaults. */
export type UpdatePayload = CommonFields & {
password?: string;
circuit_failure_window_seconds: number;
circuit_failure_threshold: number;
circuit_open_cooldown_seconds: number;
};
/** Body of POST /datasources/test-draft: connection fields only, nothing is saved. */
export type DraftTestPayload = {
engine: string;
host: string;
port: number;
database_name: string;
username: string;
password?: string;
datasource_id?: string;
};
function common(form: DatasourceForm): CommonFields {
const description = form.description.trim();
return {
name: form.name.trim(),
description: description === "" ? null : description,
engine: form.engine,
host: form.host.trim(),
port: Number(form.port),
database_name: form.database_name.trim(),
username: form.username.trim(),
};
}
export function buildCreatePayload(form: DatasourceForm): CreatePayload {
return { ...common(form), password: form.password };
}
/** A blank password (or one made only of spaces) means "keep the stored one". */
export function buildUpdatePayload(form: DatasourceForm): UpdatePayload {
const payload: UpdatePayload = {
...common(form),
circuit_failure_window_seconds: Number(form.circuit_failure_window_seconds),
circuit_failure_threshold: Number(form.circuit_failure_threshold),
circuit_open_cooldown_seconds: Number(form.circuit_open_cooldown_seconds),
};
if (form.password.trim() !== "") {
payload.password = form.password;
}
return payload;
}
/**
* Draft test body from the current form. A typed password is sent as is.
* An edit passes `datasourceId`; with no typed password the server then uses the stored one.
* A create has no id, so the form must hold a password.
*/
export function buildDraftTestPayload(form: DatasourceForm, datasourceId?: string): DraftTestPayload {
const payload: DraftTestPayload = {
engine: form.engine,
host: form.host.trim(),
port: Number(form.port),
database_name: form.database_name.trim(),
username: form.username.trim(),
};
if (form.password.trim() !== "") {
payload.password = form.password;
}
if (datasourceId) {
payload.datasource_id = datasourceId;
}
return payload;
}
+78
View File
@@ -0,0 +1,78 @@
/** Datasource shapes returned by /datasources. A password or ciphertext is never part of them. */
/** Fixed-length placeholder shown instead of a saved password. It is not the password. */
export const SECRET_MASK = "••••••••";
export type DatasourceEngine = "postgresql" | "mysql" | "sqlserver";
export const ENGINES: { value: DatasourceEngine; label: string; port: number }[] = [
{ value: "postgresql", label: "PostgreSQL", port: 5432 },
{ value: "mysql", label: "MySQL", port: 3306 },
{ value: "sqlserver", label: "SQL Server", port: 1433 },
];
export type TestCategory = "success" | "auth_failed" | "timeout" | "unreachable" | "rejected";
export const FAILURE_CATEGORIES: TestCategory[] = ["auth_failed", "timeout", "unreachable", "rejected"];
export type CircuitState = "closed" | "open";
/** Backend defaults and ranges for the circuit parameters (edited on the detail page only). */
export const CIRCUIT_DEFAULTS = { window: 300, threshold: 3, cooldown: 600 } as const;
export const CIRCUIT_SECONDS_RANGE = { min: 1, max: 86400 } as const;
export const CIRCUIT_THRESHOLD_RANGE = { min: 1, max: 100 } as const;
export type Datasource = {
id: string;
name: string;
description: string | null;
kind: string;
engine: DatasourceEngine;
host: string;
port: number;
database_name: string;
username: string;
secret_configured: boolean;
read_only_intent: boolean;
enabled: boolean;
circuit_state: CircuitState;
circuit_opened_at: string | null;
circuit_open_until: string | null;
circuit_failure_window_seconds: number;
circuit_failure_threshold: number;
circuit_open_cooldown_seconds: number;
last_test_category: TestCategory | null;
last_test_at: string | null;
last_test_message: string | null;
created_at: string | null;
updated_at: string | null;
};
export type DatasourceList = { items: Datasource[] };
export type DatasourceReferences = { id: string; items: unknown[] };
export type ConnectionTestOutcome = {
id: string;
category: TestCategory;
message: string;
last_test_at: string | null;
};
/** Result of a draft test: the category only; nothing is stored on the server for it. */
export type DraftTestOutcome = { category: TestCategory; message: string };
/** Editable fields of the form. The password is kept apart from the saved record. */
export type DatasourceForm = {
name: string;
description: string;
engine: DatasourceEngine;
host: string;
port: number | null;
database_name: string;
username: string;
password: string;
circuit_failure_window_seconds: number | null;
circuit_failure_threshold: number | null;
circuit_open_cooldown_seconds: number | null;
};
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { isFilledText, isIntegerInRange } from "./validation";
describe("isFilledText", () => {
it("accepts text with a visible character, host names included (no format check)", () => {
expect(isFilledText("db.example.test")).toBe(true);
expect(isFilledText("10.0.0.1")).toBe(true);
expect(isFilledText("not a hostname at all")).toBe(true);
});
it("rejects blank, spaces-only and non-strings", () => {
expect(isFilledText("")).toBe(false);
expect(isFilledText(" ")).toBe(false);
expect(isFilledText(null)).toBe(false);
expect(isFilledText(undefined)).toBe(false);
});
});
describe("isIntegerInRange", () => {
it("port 1-65535", () => {
expect(isIntegerInRange(1, 1, 65535)).toBe(true);
expect(isIntegerInRange(65535, 1, 65535)).toBe(true);
expect(isIntegerInRange(0, 1, 65535)).toBe(false);
expect(isIntegerInRange(65536, 1, 65535)).toBe(false);
});
it("circuit ranges match the backend (seconds 1-86400, threshold 1-100)", () => {
expect(isIntegerInRange(86400, 1, 86400)).toBe(true);
expect(isIntegerInRange(86401, 1, 86400)).toBe(false);
expect(isIntegerInRange(100, 1, 100)).toBe(true);
expect(isIntegerInRange(101, 1, 100)).toBe(false);
});
it("rejects decimals, NaN, null and strings", () => {
expect(isIntegerInRange(2.5, 1, 100)).toBe(false);
expect(isIntegerInRange(Number.NaN, 1, 100)).toBe(false);
expect(isIntegerInRange(null, 1, 100)).toBe(false);
expect(isIntegerInRange("5", 1, 100)).toBe(false);
});
});
@@ -0,0 +1,11 @@
/** Pure checks behind the datasource form rules, so they can be unit tested without a DOM. */
/** A text field counts as filled only when it has a non-space character. */
export function isFilledText(value: unknown): boolean {
return typeof value === "string" && value.trim() !== "";
}
/** A whole number within [min, max]. null, NaN, decimals and strings are rejected. */
export function isIntegerInRange(value: unknown, min: number, max: number): boolean {
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
}
+2
View File
@@ -5,8 +5,10 @@ import "element-plus/theme-chalk/dark/css-vars.css";
import "./styles.css";
import App from "./App.vue";
import { i18n } from "./i18n";
import { createAppRouter } from "./router";
const app = createApp(App);
app.use(createPinia());
app.use(i18n);
app.use(createAppRouter());
app.mount("#app");
+45
View File
@@ -0,0 +1,45 @@
/**
* Console routes. Hash history keeps every page URL out of the API proxy prefixes
* (the datasource API also lives under /datasources).
* `meta.crumbs` lists the nav keys after "Watchman" in the breadcrumb.
*/
import { createRouter, createWebHashHistory, type RouterHistory } from "vue-router";
import DatasourceEdit from "./datasources/DatasourceEdit.vue";
import DatasourceGate from "./datasources/DatasourceGate.vue";
import DatasourceList from "./datasources/DatasourceList.vue";
import HomeView from "./HomeView.vue";
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
return createRouter({
history,
routes: [
{ path: "/", name: "home", component: HomeView, meta: { crumbs: [] } },
{
path: "/datasources",
component: DatasourceGate,
children: [
{
path: "",
name: "datasource-list",
component: DatasourceList,
meta: { crumbs: ["datasources"] },
},
{
path: "new",
name: "datasource-create",
component: DatasourceEdit,
meta: { crumbs: ["datasources", "create"] },
},
{
path: ":id",
name: "datasource-detail",
component: DatasourceEdit,
meta: { crumbs: ["datasources", "detail"] },
},
],
},
{ path: "/:pathMatch(.*)*", redirect: "/" },
],
});
}
+10 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
import { authHeaders, clearSession, loadSession, saveSession } from "./session";
import { allowsDatasources, authHeaders, clearSession, loadSession, saveSession } from "./session";
describe("session token storage", () => {
beforeEach(() => {
@@ -22,3 +22,12 @@ describe("session token storage", () => {
expect(authHeaders()).toEqual({});
});
});
describe("datasource access", () => {
it("allows only watchman-admin", () => {
expect(allowsDatasources(["watchman-admin"])).toBe(true);
expect(allowsDatasources(["watchman-operator"])).toBe(false);
expect(allowsDatasources(["watchman-viewer"])).toBe(false);
expect(allowsDatasources([])).toBe(false);
});
});
+5
View File
@@ -18,6 +18,11 @@ export function allowsEnter(roles: string[]): boolean {
return roles.some((role) => ENTER_ROLES.has(role));
}
/** Only watchman-admin opens the datasource pages. The backend enforces the same rule. */
export function allowsDatasources(roles: string[]): boolean {
return roles.includes("watchman-admin");
}
export function saveSession(user: SessionUser): void {
const next = { ...user };
if (next.expires_in && !next.token_expires_at) {
+1
View File
@@ -11,6 +11,7 @@ export default defineConfig({
"/health": "http://127.0.0.1:8000",
"/platform": "http://127.0.0.1:8000",
"/auth": "http://127.0.0.1:8000",
"/datasources": "http://127.0.0.1:8000",
},
},
});