WuKongIM Web 集群监控工作台(/cluster/monitor)表面契约重构实战指南
WuKongIM Web 集群监控工作台(/cluster/monitor)表面契约重构实战指南
本文聚焦 WuKongIM Web 管理端集群实时监控页(
/cluster/monitor)的一次"纯视图契约"重构:在不改动实时监控行为的前提下,为工具栏、快照条、指标网格、加载态与数据源状态五大 UI 区域统一注入命名化data-cluster-monitor-surface标记,并用测试先行的方式固化页面级契约。读完本文,你将掌握这套表面标记(surface marker)的设计动机、TDD 落地流程、测试断言写法,以及结合源码理解集群监控页完整数据流与验证收尾方法。
背景与目标:为什么需要"表面契约"
WuKongIM 的集群监控页承担着控制器控制面、复制、内部网络、队列与存储水位等实时指标的展示职责。随着页面迭代,测试与后续维护往往依赖诸如 data-monitor-toolbar、data-testid="cluster-monitor-snapshot-cell" 这类零散标记,它们缺乏统一的命名体系,难以支撑"页面级"契约测试与未来维护。
本次重构(见 实施计划)的目标是:
Add stable named surface contracts and quiet editorial shell alignment to
/cluster/monitorwhile preserving realtime monitor behavior.
即:为 /cluster/monitor 增加稳定、命名的表面契约(surface contract),同时对齐编辑壳(editorial shell)的圆角样式,并完全保持实时监控行为不变。这里的"表面"(surface)指的是页面上可被测试稳定定位的宏观 UI 区域,而非具体指标卡细节。
关键架构决策是:这是一次纯前端视图契约变更。现有监控模型、API 调用、分类默认值、节点过滤、时间范围、刷新行为、图表渲染与 i18n 文案全部保持不变,只在大 UI 区域上补充标记。
技术栈与重构范围界定
计划明确声明的技术栈为:React、TypeScript、React Intl、Tailwind CSS、Vitest、React Testing Library、Bun,与仓库 web/ 目录实际使用的技术栈一致(见 web/package.json)。
修改清单(5 个文件)
| 文件 | 变更内容 |
|---|---|
| web/src/pages/cluster-monitor/page.test.tsx | 持有页面级契约测试:工具栏、快照、指标网格、加载态、数据源禁用态、数据源不可用态、默认 common 分类、无 All 分类、节点选择、时间范围与刷新行为 |
| web/src/pages/cluster-monitor/components/cluster-monitor-toolbar.tsx | 在现有工具栏区域上新增命名表面标记,保留 data-monitor-toolbar="true" |
| web/src/pages/cluster-monitor/components/cluster-monitor-snapshot-strip.tsx | 在紧凑快照条上新增命名表面标记 |
| web/src/pages/cluster-monitor/components/cluster-monitor-card-grid.tsx | 在响应式图表网格上新增命名表面标记 |
| web/src/pages/cluster-monitor/page.tsx | 为既有状态壳新增命名加载态与数据源状态标记,并将圆角与编辑台(console)表面语言对齐(rounded-lg → rounded-md) |
明确不修改(4 个文件)
web/src/lib/manager-api.tsweb/src/lib/manager-api.types.tsweb/src/pages/cluster-monitor/metric-config.ts- i18n 文件、路由、后端代码、
cluster-dashboard、business-dashboard
也就是说,数据获取层、类型契约、指标配置字典与国际化文案都被视为稳定边界,本次只动视图壳层。这也呼应了计划中"Architecture: This is a frontend view-contract change only"的定位。
表面契约设计:五个命名标记
重构在页面上固定五个 data-cluster-monitor-surface 取值,构成完整的页面表面契约:
| 表面名 | 含义 | 对应组件 |
|---|---|---|
toolbar |
工具栏区域(分类/节点/时间范围/刷新控件) | ClusterMonitorToolbar |
snapshot |
顶部紧凑快照条 | ClusterMonitorSnapshotStrip |
metrics |
指标卡网格 | ClusterMonitorCardGrid |
loading |
数据加载中的状态壳 | ClusterMonitorLoadingState |
source-state |
数据源禁用/不可用状态壳 | ClusterMonitorSourceState |
其中 toolbar 表面同时保留旧的 data-monitor-toolbar="true",保证既有断言不破坏;快照单元格继续保留 data-testid="cluster-monitor-snapshot-cell",指标卡继续使用 data-testid="cluster-monitor-metric-card"(由 cluster-monitor-metric-card.tsx 提供)。
页面路由注册在 web/src/app/router.tsx:/cluster/monitor 懒加载 ClusterMonitorPage,且旧路由 /dashboard 会重定向到 /cluster/monitor,说明该页已承担原业务实时监控看板的职责。
Task 1:测试先行,固化表面契约
重构遵循 TDD 流程,先写失败测试,再补标记。整体分为 8 个步骤。
Step 1:编写失败的表面标记测试
在 page.test.tsx 的 renderClusterMonitorPage() 之后立即加入测试辅助函数:
function clusterMonitorSurface(name: "toolbar" | "snapshot" | "metrics" | "loading" | "source-state") {
return document.querySelector(`[data-cluster-monitor-surface="${name}"]`)
}
该辅助函数以类型字面量约束表面名,避免拼写漂移,并通过 document.querySelector 直接在渲染后的 DOM 上定位表面元素——这正是"表面契约"测试的核心手法:不依赖组件内部实现,只依赖渲染结果。
随后替换四个既有测试用例中的断言块:
1. 数据渲染测试(renders cluster monitor cards from realtime API data)。原断言:
expect(screen.getByLabelText(/category/i).closest("section")).toHaveAttribute("data-monitor-toolbar", "true")
expect(screen.getAllByTestId("cluster-monitor-snapshot-cell").length).toBeGreaterThan(0)
替换为:
const toolbar = screen.getByLabelText(/category/i).closest("section")
expect(toolbar).toHaveAttribute("data-monitor-toolbar", "true")
expect(toolbar).toHaveAttribute("data-cluster-monitor-surface", "toolbar")
expect(clusterMonitorSurface("snapshot")).toBeInTheDocument()
expect(clusterMonitorSurface("metrics")).toBeInTheDocument()
expect(screen.getAllByTestId("cluster-monitor-snapshot-cell").length).toBeGreaterThan(0)
expect(clusterMonitorSurface("loading")).not.toBeInTheDocument()
expect(clusterMonitorSurface("source-state")).not.toBeInTheDocument()
该块同时验证了正向存在(toolbar/snapshot/metrics)与负向不存在(loading/source-state),确保正常数据渲染时不会残留状态壳。
2. 数据源禁用引导(shows prometheus setup guidance when realtime monitor is disabled)。原断言:
expect(await screen.findByText("Prometheus monitoring is not enabled")).toBeInTheDocument()
替换为:
const disabledTitle = await screen.findByText("Prometheus monitoring is not enabled")
expect(disabledTitle).toBeInTheDocument()
expect(disabledTitle.closest("section")).toHaveAttribute("data-cluster-monitor-surface", "source-state")
3. 数据源不可用与请求被拒(shows unavailable guidance for source errors and rejected requests)。第一处替换:
const unavailableTitle = await screen.findByText("Prometheus is unavailable")
expect(unavailableTitle).toBeInTheDocument()
expect(unavailableTitle.closest("section")).toHaveAttribute("data-cluster-monitor-surface", "source-state")
expect(screen.getByText("dial tcp 127.0.0.1:9090: connect: connection refused")).toBeInTheDocument()
expect(screen.queryByTestId("cluster-monitor-metric-card")).not.toBeInTheDocument()
第二处替换:
const rejectedTitle = await screen.findByText("Prometheus is unavailable")
expect(rejectedTitle).toBeInTheDocument()
expect(rejectedTitle.closest("section")).toHaveAttribute("data-cluster-monitor-surface", "source-state")
expect(screen.getByText("manager api unavailable")).toBeInTheDocument()
注意:测试中分别通过 mockResolvedValueOnce(unavailableClusterMonitorResponse()) 与 mockRejectedValueOnce(new Error("manager api unavailable")) 覆盖"Prometheus 返回不可用状态"与"manager API 请求本身被拒"两条路径,二者最终都渲染同一个 source-state 表面。
4. 加载态前置渲染(does not silently render preview fixture before the realtime API responds)。原断言:
expect(screen.getByText("Loading cluster monitor data...")).toBeInTheDocument()
替换为:
const loadingText = screen.getByText("Loading cluster monitor data...")
expect(loadingText).toBeInTheDocument()
expect(loadingText.closest("section")).toHaveAttribute("data-cluster-monitor-surface", "loading")
该用例使用 mockReturnValue(new Promise(() => undefined)) 让请求永不返回,验证加载态真实渲染,且不会在实时 API 响应前悄悄渲染预览 fixture(queryByText("UI Preview") 必须为空)。
Step 2:运行聚焦测试,确认失败
cd web && /Users/tt/.bun/bin/bun run test -- src/pages/cluster-monitor/page.test.tsx -t "renders cluster monitor cards|shows prometheus setup guidance|shows unavailable guidance|does not silently render"
预期结果:FAIL。至少一个断言报告 data-cluster-monitor-surface 缺失或取值不同。注意此命令中的 /Users/tt/.bun/bin/bun 是计划作者机器上的 Bun 绝对路径,读者在自己的环境中可替换为 bun(若已加入 PATH)或 npx bun。
Step 3~6:为四个组件补上表面标记
工具栏(cluster-monitor-toolbar.tsx)——将 <section> 起始标签改为:
<section
className="flex flex-col gap-3 border-b border-border bg-background pb-4 lg:flex-row lg:items-center lg:justify-between"
data-cluster-monitor-surface="toolbar"
data-monitor-toolbar="true"
>
快照条(cluster-monitor-snapshot-strip.tsx)——起始标签改为:
<section className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-7" data-cluster-monitor-surface="snapshot">
快照单元格保持原样:
<div className="border-b border-border px-1 py-3 sm:px-3" data-testid="cluster-monitor-snapshot-cell" key={entry.key}>
指标网格(cluster-monitor-card-grid.tsx)——起始标签改为:
<section className="grid gap-3 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4" data-cluster-monitor-surface="metrics">
指标卡渲染保持不变:
<ClusterMonitorMetricCard card={card} key={card.key} />
加载态与数据源状态壳(page.tsx)——加载壳由:
<section className="rounded-lg border border-border/80 bg-card/82 px-4 py-4 text-sm text-muted-foreground" role="status">
改为(圆角 rounded-lg → rounded-md,对齐编辑壳语言):
<section
className="rounded-md border border-border/80 bg-card/82 px-4 py-4 text-sm text-muted-foreground"
data-cluster-monitor-surface="loading"
role="status"
>
数据源状态壳(page.tsx)由:
<section className="rounded-lg border border-border/80 bg-card/88 px-5 py-6 text-sm text-muted-foreground" role="status">
改为:
<section
className="rounded-md border border-border/80 bg-card/88 px-5 py-6 text-sm text-muted-foreground"
data-cluster-monitor-surface="source-state"
role="status"
>
需要说明的是,仓库当前源码中的这两个状态壳已经落地了上述改造(分别带有 data-cluster-monitor-surface="loading" 与 data-cluster-monitor-surface="source-state"),计划文档中的片段即是对应实现目标。ClusterMonitorSourceState 在数据源被禁用时(kind="disabled")还会展示两个配置提示码:WK_METRICS_ENABLE=true 与 WK_PROMETHEUS_ENABLE=true,这两个环境变量在服务端配置解析中真实存在,见 internal/config/build.go 与 internal/config/schema.go。
Step 7:运行聚焦测试,验证通过
cd web && /Users/tt/.bun/bin/bun run test -- src/pages/cluster-monitor/page.test.tsx
预期结果:PASS。既有断言全部继续通过,包括:首次请求 { window: "15m", category: "common" }、无 All 分类、节点过滤、分类过滤、时间范围、手动刷新、自动刷新、数据源状态、帮助按钮、字节格式化与指标渲染。
Step 8:提交变更
git status --short
git add web/src/pages/cluster-monitor/page.test.tsx \
web/src/pages/cluster-monitor/components/cluster-monitor-toolbar.tsx \
web/src/pages/cluster-monitor/components/cluster-monitor-snapshot-strip.tsx \
web/src/pages/cluster-monitor/components/cluster-monitor-card-grid.tsx \
web/src/pages/cluster-monitor/page.tsx
git commit -m "style(web): name cluster monitor surfaces"
预期:提交成功,且既有未跟踪文件(如 docs/superpowers/plans/2026-07-05-legacy-app-slot-store-adapter.md)不会被误纳入本次提交——即 git add 只精确添加表面契约相关的 5 个文件。
结合源码:页面数据流与渲染模型
理解表面契约的价值,需要先看清 page.tsx 的整体数据流。
页面状态机
页面以 ClusterMonitorPageState 区分三种状态(page.tsx):
type ClusterMonitorPageState =
{ kind: "loading" } | { kind: "ready"; response: RealtimeMonitorResponse } | { kind: "error"; message: string }
渲染分支(page.tsx)正好对应三个表面:
loading→ClusterMonitorLoadingStateerror或prometheus_unavailable→ClusterMonitorSourceState kind="unavailable"prometheus_disabled→ClusterMonitorSourceState kind="disabled"- 其余就绪且可渲染 → 快照条 + goroutine 表 + 指标网格
注意 isRenderableClusterMonitor(page.tsx)的判定逻辑:ready/partial 状态需要至少有一个已知快照条目、已知指标卡或 goroutine 节点数据才算可渲染;prometheus_unavailable 仅在存在可用且已知的指标卡时才渲染模型——这保证了"部分可用"时不出现空壳。
实时数据获取
数据由 getRealtimeMonitor 从 manager API 拉取(web/src/lib/manager-api.ts):
export function getRealtimeMonitor(params?: { window?: string; step?: string; nodeId?: number; category?: RealtimeMonitorCategory }) {
const search = new URLSearchParams()
if (params?.window) search.set("window", params.window)
if (params?.step) search.set("step", params.step)
if (typeof params?.nodeId === "number") search.set("node_id", String(params.nodeId))
if (params?.category) search.set("category", params.category)
const query = search.toString()
return jsonManagerFetch<RealtimeMonitorResponse>(`/manager/realtime-monitor${query ? `?${query}` : ""}`)
}
即请求 /manager/realtime-monitor?window=15m&step=20s&node_id=2&category=internal 这类 URL。响应类型 RealtimeMonitorResponse(web/src/lib/manager-api.types.ts)包含 status(ready/partial/prometheus_disabled/prometheus_unavailable)、sources(prometheus / control_snapshot / goroutines 三路数据源状态)、categories、snapshot、cards 与可选的 goroutines 明细。
页面中 useEffect(page.tsx)以 ${timeRange}:${selectedNodeId ?? "all"}:${selectedCategory} 作为查询键做去重:相同查询且已就绪时不重置为 loading,避免不必要的闪烁;手动刷新通过 refreshNonce 触发重取;自动刷新由 monitorRefreshIntervalMs(refreshInterval) 驱动的定时器触发(page.tsx)。
指标配置与排序
指标字典 metric-config.ts 是渲染模型的元数据核心:
clusterMonitorMetricConfig:每个指标键配置titleId、helpId、chartColor、precision、stage、tone;clusterMonitorMetricOperationalPriority(metric-config.ts):按运维关注度排序——健康类指标(clusterMonitorHealthMetrics)优先级 0,critical 类优先级 1,运行时压力类优先级 2,延迟类优先级 3,其余 4;clusterMonitorMetricTone(metric-config.ts):对"零即健康"指标(clusterMonitorZeroMeansHealthyMetrics,如controllerApplyGap、rpcErrorRate、storageCommitErrorRate),当值为 0 时强制归一为normal,避免误报。
页面模型构建(buildRealtimeMonitorModel,page.tsx)按优先级排序卡片、按 clusterMonitorSnapshotLabelIds/clusterMonitorStatLabelIds 过滤并映射快照与统计项,再通过 byteDisplayScale(page.tsx)将字节类指标按 1024 进制动态缩放到 KB/MB/GB/TB(含 /s 速率后缀)。测试中 formats large internal traffic byte rates 与 formats node memory pressure bytes 正是对这些格式化逻辑的契约保护。
工具栏控件
cluster-monitor-toolbar.tsx 暴露的控件与默认值:
- 时间范围:
["5m", "15m", "30m", "1h"],默认15m; - 指标分类:
["common", "gateway", "internal", "message", "conversation", "channel", "database", "control", "slot", "node", "goroutines"],默认common,且没有All分类(测试明确断言queryByRole("option", { name: "All" })为空); - 节点选择:
MonitorNodeSelector,选择后请求携带node_id; - 刷新间隔:
MonitorRefreshControls,默认30s;当切换到goroutines分类时自动降为5s(见 page.tsx 的changeCategory),并提供手动"Refresh now"。
Task 2:验证与构建收尾
表面标记落地后,还需要全量验证与构建收尾,共 6 步。
Step 1:完整聚焦监控验证
cd web && /Users/tt/.bun/bin/bun run test -- src/pages/cluster-monitor/page.test.tsx src/pages/cluster-monitor/components/cluster-monitor-metric-card.test.ts src/pages/cluster-monitor/preview-data.test.ts src/pages/page-shells.test.tsx
预期:PASS。页面壳仍渲染 /cluster/monitor,指标卡模型测试(cluster-monitor-metric-card.test.ts)继续通过,预览数据测试(preview-data.test.ts)保持确定性。
Step 2:TypeScript 构建验证
cd web && /Users/tt/.bun/bin/bunx tsc -b
预期:PASS,无 TypeScript 错误。这保证了新增 JSX 属性与类型定义兼容。
Step 3:生产构建验证
cd web && /Users/tt/.bun/bin/bun run build
预期:PASS。Vite 的 chunk 体积警告在构建成功退出时可接受。
Step 4:清理构建产物中的哈希变动
git status --short web/dist/index.html
git diff -- web/dist/index.html
若 diff 仅涉及构建生成的文件名哈希变动,则执行:
git restore -- web/dist/index.html
预期:web/dist/index.html 恢复干净。若存在手写源码改动,则保留并排查构建为何触及它。
Step 5:空白符验证
git diff --check
预期:无空白符错误。
Step 6:检查最终本地状态
git status --short --branch
git log --oneline -n 5
预期:本地 main 包含 style(web): name cluster monitor surfaces 提交,计划/规格提交位于其下,无关的未跟踪文件保持未提交状态。
测试矩阵:行为不变的保障
计划最值得借鉴的一点是:表面契约重构必须由既有行为测试矩阵背书。归纳 page.test.tsx 中覆盖的维度,它们全部要求"改造后继续通过":
- 首次请求参数:默认
{ window: "15m", category: "common" },切换分类/节点后category、nodeId正确传递; - 分类契约:存在
common/gateway/database等选项,不存在All; - 数据源状态:禁用态展示
WK_METRICS_ENABLE=true/WK_PROMETHEUS_ENABLE=true引导,且不渲染指标卡;不可用态与请求被拒统一收敛到source-state表面; - 加载态:API 未响应前显示加载文案,不渲染预览 fixture;
- 刷新行为:手动刷新立即触发一次请求;
30s自动刷新按定时器触发;切到off后定时器停止; - 格式化:字节速率动态缩放(KB/s、MB/s)、节点 CPU/内存、GC 压力、重复系列键去重等;
- goroutine 专属行为:切换
goroutines分类后按5s刷新、按节点/模块聚合展示、任务展开等。
总结
WuKongIM 集群监控工作台表面契约重构是一个"小而完整"的前端工程实践范本:用 data-cluster-monitor-surface 统一五个宏观 UI 区域的定位语义,测试先行固化契约,随后以最小 diff 落地标记,最后通过全量测试、类型检查、生产构建与 git 卫生检查完成收尾。它既为测试与未来维护提供了稳定锚点,也证明了"纯视图契约变更可以做到零行为漂移"。
对读者而言,这套方法论可直接迁移到任何需要稳定自动化定位、但又不想侵入数据层与行为逻辑的 React 页面改造场景;对 WuKongIM 使用者而言,了解这些表面标记有助于编写更健壮的端到端与组件级测试,并快速定位集群监控页的加载、禁用、不可用等异常态的 UI 处理路径。