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 ids = [randomUUID(), randomUUID(), randomUUID()]; const publicIDs = [randomUUID(), randomUUID(), randomUUID()]; const marker = randomUUID().slice(0, 8); const titles = [`页面接手告警夹具-${marker}`, `页面缓解告警夹具-${marker}`, `页面关闭告警夹具-${marker}`]; 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(`DELETE FROM alert_incident WHERE id IN ('${ids[0]}'::uuid,'${ids[1]}'::uuid,'${ids[2]}'::uuid);`); } psql(`INSERT INTO alert_incident(id,public_id,tenant_id,rule_code,category,severity,status,fingerprint,title,summary,first_detected_at,last_detected_at,occurrence_count,acknowledged_at,mitigated_at,row_version) VALUES ('${ids[0]}'::uuid,'${publicIDs[0]}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'VISUAL_ACK_${marker.toUpperCase()}','TECHNICAL','HIGH','OPEN','visual-ack-${marker}','${titles[0]}','验证页面内确认接手门禁',now()-interval '10 minutes',now(),2,NULL,NULL,4), ('${ids[1]}'::uuid,'${publicIDs[1]}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'VISUAL_MIT_${marker.toUpperCase()}','BUSINESS','MEDIUM','ACKNOWLEDGED','visual-mit-${marker}','${titles[1]}','验证页面内记录缓解门禁',now()-interval '20 minutes',now(),3,now()-interval '15 minutes',NULL,5), ('${ids[2]}'::uuid,'${publicIDs[2]}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'VISUAL_RES_${marker.toUpperCase()}','SECURITY','CRITICAL','MITIGATED','visual-res-${marker}','${titles[2]}','验证页面内关闭告警门禁',now()-interval '30 minutes',now(),4,now()-interval '25 minutes',now()-interval '5 minutes',6);`); 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 transitionMutations = []; page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); }); page.on("request", (request) => { if (request.method() === "POST" && /\/api\/v1\/ops\/alerts\/[^/]+\/(acknowledge|mitigate|resolve)$/.test(request.url())) transitionMutations.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}`); }); async function openAlert(title) { await page.locator(".alert-queue li").filter({ hasText: title }).getByRole("button").click(); await page.locator(".alert-detail").getByRole("heading", { name: title }).waitFor(); } 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(); await openAlert(titles[0]); await page.getByRole("button", { name: "确认并接手" }).click(); let form = page.getByRole("form", { name: "告警处置动作" }); let text = await form.textContent(); const acknowledgeTargetBound = text?.includes(publicIDs[0]) === true && text?.includes("行版本 v4") === true && text?.includes("当前待确认") === true; let submit = form.getByRole("button", { name: "确认接手" }); const acknowledgeEmptyDisabled = await submit.isDisabled(); await form.getByLabel("接手说明").fill("已按运行手册确认影响范围并接手后续处置"); const acknowledgeEnabled = await submit.isEnabled(); await form.getByRole("button", { name: "取消" }).click(); await openAlert(titles[1]); await page.getByRole("button", { name: "记录缓解" }).click(); form = page.getByRole("form", { name: "告警处置动作" }); text = await form.textContent(); const mitigateTargetBound = text?.includes(publicIDs[1]) === true && text?.includes("行版本 v5") === true && text?.includes("当前已确认") === true; submit = form.getByRole("button", { name: "确认记录缓解" }); const mitigateEmptyDisabled = await submit.isDisabled(); await form.getByLabel("缓解说明").fill("已执行隔离措施,影响范围收敛并进入持续观察"); const mitigateEnabled = await submit.isEnabled(); await form.getByRole("button", { name: "取消" }).click(); await openAlert(titles[2]); await page.getByRole("button", { name: "验证并关闭" }).click(); form = page.getByRole("form", { name: "告警处置动作" }); text = await form.textContent(); const resolveTargetBound = text?.includes(publicIDs[2]) === true && text?.includes("行版本 v6") === true && text?.includes("当前已缓解") === true; submit = form.getByRole("button", { name: "确认关闭告警" }); const resolveEmptyDisabled = await submit.isDisabled(); await form.getByLabel("关闭验证说明").fill("恢复指标持续正常,关联影响和遗留风险已完成复核"); const resolveNeedsAcknowledgement = await submit.isDisabled(); await form.getByLabel(/我确认缓解措施已经验证/).check(); const resolveEnabled = await submit.isEnabled(); await page.screenshot({ path: fileURLToPath(new URL("ops-alert-transition-form.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 = { acknowledgeTargetBound, acknowledgeEmptyDisabled, acknowledgeEnabled, mitigateTargetBound, mitigateEmptyDisabled, mitigateEnabled, resolveTargetBound, resolveEmptyDisabled, resolveNeedsAcknowledgement, resolveEnabled, cancelClosed, transitionMutations, overflow, consoleErrors, failedRequests }; console.log(JSON.stringify(result, null, 2)); if (!acknowledgeTargetBound || !acknowledgeEmptyDisabled || !acknowledgeEnabled || !mitigateTargetBound || !mitigateEmptyDisabled || !mitigateEnabled || !resolveTargetBound || !resolveEmptyDisabled || !resolveNeedsAcknowledgement || !resolveEnabled || !cancelClosed || transitionMutations.length || overflow.length || consoleErrors.length || failedRequests.length) throw new Error("Ops alert transition visual smoke failed"); } finally { await browser.close(); cleanup(); }