Files
story/test/e2e/visual-ops-alert-controlled-actions.mjs
T

116 lines
9.1 KiB
JavaScript

import { createRequire } from "node:module";
import { randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const require = createRequire(process.env.PLAYWRIGHT_REQUIRE_FROM ?? import.meta.url);
const { chromium } = require("playwright");
const outputDirectory = new URL("./screenshots/", import.meta.url);
const webURL = process.env.VISUAL_WEB_URL ?? "http://localhost:3100";
const webHostPattern = new RegExp(new URL(webURL).host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const oidcURLPattern = new RegExp(process.env.VISUAL_OIDC_URL_PATTERN ?? "localhost:58180");
const marker = randomUUID().slice(0, 8);
const routeID = randomUUID();
const routePublicID = randomUUID();
const silenceID = randomUUID();
const silencePublicID = randomUUID();
const outboxID = randomUUID();
const outboxPublicID = randomUUID();
const testRef = randomUUID();
const receiverGroup = `visual-oncall-${marker}`;
const silenceRule = `VISUAL_SILENCE_${marker.toUpperCase()}`;
await mkdir(outputDirectory, { recursive: true });
function psql(statement) {
return execFileSync("docker", ["compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-U", "voice", "-d", "voice_platform", "-Atc", statement], { cwd: process.cwd(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
}
function cleanup() {
psql(`BEGIN; DELETE FROM outbox_event WHERE id='${outboxID}'::uuid; DELETE FROM alert_silence WHERE id='${silenceID}'::uuid; DELETE FROM alert_routing_policy WHERE id='${routeID}'::uuid; COMMIT;`);
}
psql(`BEGIN;
INSERT INTO alert_routing_policy(id,public_id,tenant_id,category,severity,version_no,status,receiver_group,response_minutes,escalation_after_minutes,escalation_receiver_group,runbook_ref,change_summary,created_by,row_version)
VALUES('${routeID}'::uuid,'${routePublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'COST','LOW',1,'ACTIVE','${receiverGroup}',30,60,'visual-escalation-${marker}','runbook://visual/alert-test','页面联通测试无提交验证','10000000-0000-0000-0000-000000000102'::uuid,4);
INSERT INTO alert_silence(id,public_id,tenant_id,rule_code,matcher,reason,starts_at,ends_at,created_by,row_version)
VALUES('${silenceID}'::uuid,'${silencePublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'${silenceRule}','{}'::jsonb,'页面静默撤销无提交验证',now()-interval '10 minutes',now()+interval '2 hours','10000000-0000-0000-0000-000000000101'::uuid,5);
INSERT INTO outbox_event(id,public_id,tenant_id,aggregate_type,aggregate_id,event_type,payload,status,attempt_count,manual_retry_count,last_error_code,dead_at,deduplication_key,payload_hash)
VALUES('${outboxID}'::uuid,'${outboxPublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'alert_delivery_test','${testRef}'::uuid,'alert.webhook_test_requested',jsonb_build_object('action','TEST','test_ref','${testRef}','tenant_id','10000000-0000-0000-0000-000000000001','routing_policy_id','${routePublicID}','category','COST','severity','LOW','receiver_group','${receiverGroup}','runbook_ref','runbook://visual/alert-test'),'dead',4,1,'WEBHOOK_CONNECT_FAILED',now(),'visual-alert-test-${marker}',repeat('a',64));
COMMIT;`);
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH ?? "C:/Program Files/Google/Chrome/Application/chrome.exe" });
const page = await browser.newPage({ viewport: { width: 1440, height: 1100 }, deviceScaleFactor: 1 });
const consoleErrors = [];
const failedRequests = [];
const mutations = [];
page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
page.on("request", (request) => {
if (request.method() === "POST" && /\/api\/v1\/ops\/(alert-routing-policies\/[^/]+\/delivery-tests|diagnostics\/jobs\/[^/]+\/retry|alert-silences\/[^/]+\/revoke)$/.test(request.url())) mutations.push(`${request.method()} ${request.url()}`);
});
page.on("requestfailed", (request) => {
const failure = request.failure()?.errorText ?? "failed";
const requestURL = new URL(request.url());
if (request.method() === "GET" && requestURL.pathname === "/api/v1/events" && failure.includes("ERR_ABORTED")) return;
failedRequests.push(`${request.method()} ${request.url()} ${failure}`);
});
try {
await page.goto(`${webURL}/?workspace=alerts`, { waitUntil: "networkidle" });
await page.getByRole("button", { name: "登录研发环境" }).click();
await page.waitForURL(oidcURLPattern);
await page.locator("#username").fill(process.env.VISUAL_USERNAME ?? "owner");
await page.locator("#password").fill(process.env.VISUAL_PASSWORD ?? "LocalOnly123!");
await page.locator("#kc-login").click();
await page.waitForURL(webHostPattern, { timeout: 15000 });
await page.getByRole("heading", { name: "告警监测与处置闭环" }).waitFor();
const routeRow = page.locator(".alert-ledger-grid section").filter({ hasText: "活动路由" }).locator("li").filter({ hasText: receiverGroup });
await routeRow.getByRole("button", { name: "测试通知" }).click();
let form = page.getByRole("form", { name: "告警受控操作" });
let text = await form.textContent();
const testTargetBound = text?.includes(routePublicID) === true && text?.includes(receiverGroup) === true && text?.includes("行版本 v4") === true;
let submit = form.getByRole("button", { name: "确认发送测试通知" });
const testEmptyDisabled = await submit.isDisabled();
await form.getByLabel("测试原因").fill("验证当前值班接收组和Webhook签名投递链路");
const testNeedsAcknowledgement = await submit.isDisabled();
await form.getByLabel(/我确认接收组知晓本次测试/).check();
const testEnabled = await submit.isEnabled();
await form.getByRole("button", { name: "取消" }).click();
const retryRow = page.locator(".alert-ledger-grid section").filter({ hasText: "接收器联通测试" }).locator("li").filter({ hasText: testRef });
await retryRow.getByRole("button", { name: "受控重试" }).click();
form = page.getByRole("form", { name: "告警受控操作" });
text = await form.textContent();
const retryTargetBound = text?.includes(outboxPublicID) === true && text?.includes(testRef) === true && text?.includes("WEBHOOK_CONNECT_FAILED") === true && text?.includes("已尝试 4 次") === true;
submit = form.getByRole("button", { name: "确认受控重试" });
const retryEmptyDisabled = await submit.isDisabled();
await form.getByLabel("重试原因和修复依据").fill("接收器网络配置已修复并完成连通性复核");
const retryNeedsAcknowledgement = await submit.isDisabled();
await form.getByLabel(/我确认接收器配置或网络问题已经处理/).check();
const retryEnabled = await submit.isEnabled();
await form.getByRole("button", { name: "取消" }).click();
const silenceRow = page.locator(".alert-ledger-grid section").filter({ hasText: "静默记录" }).locator("li").filter({ hasText: silenceRule });
await silenceRow.getByRole("button", { name: "提前撤销" }).click();
form = page.getByRole("form", { name: "告警受控操作" });
text = await form.textContent();
const silenceTargetBound = text?.includes(silencePublicID) === true && text?.includes(silenceRule) === true && text?.includes("行版本 v5") === true;
submit = form.getByRole("button", { name: "确认撤销静默" });
const silenceEmptyDisabled = await submit.isDisabled();
await form.getByLabel("提前撤销原因").fill("维护窗口已结束,恢复正常告警处置");
const silenceNeedsAcknowledgement = await submit.isDisabled();
await form.getByLabel(/我确认静默条件已经解除/).check();
const silenceEnabled = await submit.isEnabled();
await page.screenshot({ path: fileURLToPath(new URL("ops-alert-controlled-actions.png", outputDirectory)), fullPage: true });
await form.getByRole("button", { name: "取消" }).click();
const cancelClosed = await form.count() === 0;
const overflow = await page.evaluate(() => [...document.querySelectorAll("body *")].filter((element) => element instanceof HTMLElement && element.scrollWidth > element.clientWidth + 2 && getComputedStyle(element).overflowX === "visible").slice(0, 20).map((element) => `${element.tagName}.${element.className}: ${element.clientWidth}/${element.scrollWidth}`));
const result = { testTargetBound, testEmptyDisabled, testNeedsAcknowledgement, testEnabled, retryTargetBound, retryEmptyDisabled, retryNeedsAcknowledgement, retryEnabled, silenceTargetBound, silenceEmptyDisabled, silenceNeedsAcknowledgement, silenceEnabled, cancelClosed, mutations, overflow, consoleErrors, failedRequests };
console.log(JSON.stringify(result, null, 2));
if (!testTargetBound || !testEmptyDisabled || !testNeedsAcknowledgement || !testEnabled || !retryTargetBound || !retryEmptyDisabled || !retryNeedsAcknowledgement || !retryEnabled || !silenceTargetBound || !silenceEmptyDisabled || !silenceNeedsAcknowledgement || !silenceEnabled || !cancelClosed || mutations.length || overflow.length || consoleErrors.length || failedRequests.length) throw new Error("Ops alert controlled actions visual smoke failed");
} finally {
await browser.close();
cleanup();
}