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

+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",
},
},
});