feat: 接通后台渲染异常上报与响应契约校验

This commit is contained in:
que01 committed 2026-10-21 11:43:41 +08:00
1 parent 330d67adc1
commit adcaa12970
22 files changed
+845 -33

No files matched your search

@@ -1,5 +1,6 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { Button, Result, Space, Typography } from "antd";
import { createApiClient } from "../lib/api.js";
interface AdminErrorBoundaryProps {
children: ReactNode;
@@ -24,13 +25,28 @@ export class AdminErrorBoundary extends Component<
AdminErrorBoundaryState
> {
override state: AdminErrorBoundaryState = { error: null, errorId: null };
private reportedErrorId: string | null = null;
static getDerivedStateFromError(error: Error): AdminErrorBoundaryState {
return { error, errorId: createErrorId() };
}
override componentDidCatch(error: Error, info: ErrorInfo) {
console.error("[admin] 页面渲染异常", this.state.errorId, error, info.componentStack);
const errorId = this.state.errorId ?? createErrorId();
console.error("[admin] 页面渲染异常", errorId, error, info.componentStack);
if (this.reportedErrorId === errorId) return;
this.reportedErrorId = errorId;
// 上报失败不能影响错误页本身:只记录到控制台,不抛出、不改状态。
void createApiClient()
.reportAdminClientError({
errorId,
message: error.message.slice(0, 2000) || error.name,
route: `${window.location.pathname}${window.location.search}`.slice(0, 500),
...(info.componentStack ? { componentStack: info.componentStack.slice(0, 20000) } : {}),
})
.catch((reportError: unknown) => {
console.warn("[admin] 渲染异常上报失败", errorId, reportError);
});
}
private reset = () => {
+23
View File
@@ -0,0 +1,23 @@
import { IsOptional, IsString, Matches, MaxLength, MinLength } from "class-validator";
/** 后台渲染异常上报:只接受白名单字段,避免把任意浏览器数据写进日志。 */
export class CreateClientErrorDto {
@IsString()
@Matches(/^[A-Za-z0-9._-]{4,128}$/, { message: "errorId 格式不正确" })
errorId!: string;
@IsString()
@MinLength(1, { message: "message 不能为空" })
@MaxLength(2000, { message: "message 过长" })
message!: string;
@IsString()
@Matches(/^\//, { message: "route 必须以 / 开头" })
@MaxLength(500, { message: "route 过长" })
route!: string;
@IsOptional()
@IsString()
@MaxLength(20000, { message: "componentStack 过长" })
componentStack?: string;
}
@@ -0,0 +1,36 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import { Body, Controller, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { CreateClientErrorDto } from "../../client-error.dto.js";
import { AdminClientErrorService } from "./admin-client-error.service.js";
@AdminBrand()
@Controller("admin/client-errors")
export class AdminClientErrorController {
constructor(
private readonly access: AdminAccessService,
private readonly errors: AdminClientErrorService,
) {}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateClientErrorDto,
): Promise<{ received: true; duplicate: boolean }> {
const identity = await this.access.requireBrand(request);
return this.errors.record({
subject: identity.subject,
brandId: identity.brandId,
errorId: body.errorId,
message: body.message,
route: body.route,
componentStack: body.componentStack,
requestId:
(request as FastifyRequest & { requestId?: string }).requestId ??
request.headers["x-request-id"]?.toString() ??
null,
userAgent: request.headers["user-agent"]?.toString().slice(0, 300) ?? null,
});
}
}
@@ -0,0 +1,91 @@
import { HttpException, Injectable } from "@nestjs/common";
const RATE_WINDOW_MS = 60_000;
const RATE_LIMIT = 10;
const DEDUPE_TTL_MS = 10 * 60_000;
const DEDUPE_CAPACITY = 500;
const LOG_STACK_LIMIT = 4000;
export interface ClientErrorReport {
subject: string;
brandId: string;
errorId: string;
message: string;
route: string;
componentStack?: string | undefined;
requestId: string | null;
userAgent: string | null;
}
export interface ClientErrorReceipt {
received: true;
duplicate: boolean;
}
/**
* 后台渲染异常去重与限流。
* 当前生产为单实例 PM2,因此使用进程内窗口;扩成多实例前需要换成共享存储。
*/
@Injectable()
export class AdminClientErrorService {
private readonly recentErrorIds = new Map<string, number>();
private readonly windows = new Map<string, number[]>();
record(report: ClientErrorReport): ClientErrorReceipt {
const now = Date.now();
this.prune(now);
const dedupeKey = `${report.subject}:${report.errorId}`;
if (this.recentErrorIds.has(dedupeKey)) {
return { received: true, duplicate: true };
}
this.assertWithinRate(report.subject, now);
this.recentErrorIds.set(dedupeKey, now);
this.trimDedupe();
console.error("admin client error", {
errorId: report.errorId,
message: report.message,
route: report.route,
subject: report.subject,
brandId: report.brandId,
requestId: report.requestId,
userAgent: report.userAgent,
componentStack: report.componentStack?.slice(0, LOG_STACK_LIMIT) ?? null,
});
return { received: true, duplicate: false };
}
private assertWithinRate(subject: string, now: number): void {
const recent = (this.windows.get(subject) ?? []).filter(
(timestamp) => now - timestamp < RATE_WINDOW_MS,
);
if (recent.length >= RATE_LIMIT) {
this.windows.set(subject, recent);
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
}
recent.push(now);
this.windows.set(subject, recent);
}
private prune(now: number): void {
for (const [key, timestamp] of this.recentErrorIds) {
if (now - timestamp >= DEDUPE_TTL_MS) this.recentErrorIds.delete(key);
}
for (const [subject, timestamps] of this.windows) {
const recent = timestamps.filter((timestamp) => now - timestamp < RATE_WINDOW_MS);
if (recent.length === 0) this.windows.delete(subject);
else this.windows.set(subject, recent);
}
}
private trimDedupe(): void {
while (this.recentErrorIds.size > DEDUPE_CAPACITY) {
const oldest = this.recentErrorIds.keys().next();
if (oldest.done) return;
this.recentErrorIds.delete(oldest.value);
}
}
}
@@ -2,6 +2,8 @@ import { Module } from "@nestjs/common";
import { BookingModule } from "../booking.module.js";
import { InfrastructureModule } from "../infrastructure.module.js";
import { AdminBookingController } from "./admin-booking.controller.js";
import { AdminClientErrorController } from "./admin-client-error.controller.js";
import { AdminClientErrorService } from "./admin-client-error.service.js";
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
import { AdminConfigController } from "./admin-config.controller.js";
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
@@ -32,6 +34,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
AdminBookingController,
AdminTemplatePackageController,
TemplateOperationMetricsController,
AdminClientErrorController,
],
providers: [
AdminBrandConfigService,
@@ -44,6 +47,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
AdminTemplatePreviewService,
AdminTemplatePreviewAssetsService,
TemplateOperationMetricsService,
AdminClientErrorService,
],
})
export class AdminModule {}
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { HttpException } from "@nestjs/common";
import { AdminClientErrorService } from "../src/modules/admin/admin-client-error.service.js";
function report(errorId: string, subject = "admin:user-1") {
return {
subject,
brandId: "brand-1",
errorId,
message: "boom",
route: "/admin/trust",
requestId: "req-1",
userAgent: "test-agent",
};
}
test("首次上报记录,相同 errorId 在窗口内按管理员去重", () => {
const service = new AdminClientErrorService();
assert.deepEqual(service.record(report("admin-error-1")), {
received: true,
duplicate: false,
});
assert.deepEqual(service.record(report("admin-error-1")), {
received: true,
duplicate: true,
});
// 不同管理员使用相同 errorId 时互不影响
assert.deepEqual(service.record(report("admin-error-1", "admin:user-2")), {
received: true,
duplicate: false,
});
});
test("同一管理员 60 秒内最多接受 10 条不同错误", () => {
const service = new AdminClientErrorService();
for (let index = 0; index < 10; index += 1) {
assert.deepEqual(service.record(report(`admin-rate-${index}`)), {
received: true,
duplicate: false,
});
}
try {
service.record(report("admin-rate-overflow"));
assert.fail("应当触发限流");
} catch (error) {
assert.ok(error instanceof HttpException);
assert.equal(error.getStatus(), 429);
}
// 另一个管理员不受影响
assert.deepEqual(service.record(report("admin-rate-other", "admin:user-2")), {
received: true,
duplicate: false,
});
});
+36
View File
@@ -1892,6 +1892,42 @@ async function request(url, options = {}) {
});
}
test("admin client error reports are authenticated, validated, and deduplicated", async () => {
await assertProtectedRouteBoundary("/admin/client-errors", {
method: "POST",
payload: { errorId: "admin-boundary-check", message: "boom", route: "/admin/publication" },
});
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const errorId = `admin-it-${Date.now().toString(36)}`;
const payload = {
errorId,
message: "Cannot read properties of null (reading 'type')",
route: "/admin/trust?tab=1",
componentStack: "at TrustContentPage",
};
const first = await request("/admin/client-errors", { method: "POST", headers, payload });
assert.equal(first.statusCode, 201);
assert.deepEqual(JSON.parse(first.body), { received: true, duplicate: false });
const duplicate = await request("/admin/client-errors", { method: "POST", headers, payload });
assert.equal(duplicate.statusCode, 201);
assert.deepEqual(JSON.parse(duplicate.body), { received: true, duplicate: true });
const invalid = await request("/admin/client-errors", {
method: "POST",
headers,
payload: { errorId: "bad", message: "", route: "no-slash" },
});
assert.equal(invalid.statusCode, 400);
});
async function assertProtectedRouteBoundary(url, options = {}) {
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
+7
View File
@@ -657,6 +657,13 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: null,
successTest: "wechat login creates a customer session for the requested brand",
},
{
method: "POST",
path: "/admin/client-errors",
auth: "brand",
authorizationTest: "admin client error reports are authenticated, validated, and deduplicated",
successTest: "admin client error reports are authenticated, validated, and deduplicated",
},
{
method: "PUT",
path: "/admin/uploads/local",
@@ -1,3 +1,4 @@
import assert from "node:assert/strict";
import { test, expect, type Page, type Route } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
@@ -19,12 +20,27 @@ interface MockOptions {
memberships?: unknown;
/** 品牌名称的异常返回 */
brandName?: unknown;
/** 始终返回的异常信任内容,用于验证契约错误态 */
trustContent?: unknown;
/** 只在首次请求时返回的异常信任内容,重新加载后恢复 */
trustContentOnce?: unknown;
/** 只在首次请求时返回的异常工作区数据,用于触发渲染异常 */
workspaceOnce?: unknown;
/** 上报接口返回的状态码 */
clientErrorStatus?: number;
}
type ClientErrorReport = {
errorId?: string;
message?: string;
route?: string;
componentStack?: string;
};
async function mockAdminApi(page: Page, options: MockOptions = {}) {
let servedTrustContent = false;
let servedWorkspace = false;
const clientErrors: ClientErrorReport[] = [];
await page.route("**/api/**", async (route: Route) => {
const request = route.request();
@@ -70,13 +86,35 @@ async function mockAdminApi(page: Page, options: MockOptions = {}) {
});
}
if (path === "/admin/config/trust-content" && method === "GET") {
if (options.trustContent !== undefined) {
return route.fulfill({ json: options.trustContent });
}
if (!servedTrustContent && options.trustContentOnce !== undefined) {
servedTrustContent = true;
return route.fulfill({ json: options.trustContentOnce });
}
return route.fulfill({ json: [] });
}
if (path === "/admin/client-errors" && method === "POST") {
clientErrors.push(JSON.parse(request.postData() ?? "{}") as ClientErrorReport);
return route.fulfill({
status: options.clientErrorStatus ?? 201,
...(options.clientErrorStatus && options.clientErrorStatus >= 400
? {
json: {
data: null,
error: { code: "HTTP_500", message: "上报失败" },
requestId: "req-client-error",
},
}
: { json: { received: true, duplicate: false } }),
});
}
if (path === "/admin/workspace") {
if (!servedWorkspace && options.workspaceOnce !== undefined) {
servedWorkspace = true;
return route.fulfill({ json: options.workspaceOnce });
}
return route.fulfill({
json: {
brand: { id: "brand-current", name: "独立工坊" },
@@ -92,6 +130,8 @@ async function mockAdminApi(page: Page, options: MockOptions = {}) {
}
return route.fulfill({ json: [] });
});
return { clientErrors };
}
test("品牌成员与品牌名称异常时后台外壳仍可正常使用", async ({ page }) => {
@@ -109,14 +149,27 @@ test("品牌成员与品牌名称异常时后台外壳仍可正常使用", async
await expect(page.getByRole("button", { name: "退出登录" })).toBeVisible();
});
test("内容区渲染出错时保留导航,重新加载后恢复", async ({ page }) => {
test("内容区渲染出错时上报错误编号并保留导航,重新加载后恢复", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await mockAdminApi(page, { trustContentOnce: [null] });
const { clientErrors } = await mockAdminApi(page, {
workspaceOnce: {
brand: { id: "brand-current", name: "独立工坊" },
installations: [],
templateContent: { displayName: "独立创作者画册", trustContentTypes: [null] },
offerings: [],
forms: [],
},
});
await page.goto(`${adminOrigin}/admin/trust`);
await expect(page.getByText("页面渲染出错")).toBeVisible();
await expect(page.getByText(/错误编号:admin-/)).toBeVisible();
await expect.poll(() => clientErrors.length).toBe(1);
const report = clientErrors[0];
assert.match(report?.errorId ?? "", /^admin-/);
assert.equal(report?.route, "/admin/trust");
assert.ok(report?.message);
// 外壳导航仍然可用,不会因为单个页面崩溃而整站白屏
await expect(page.getByRole("button", { name: "退出登录" })).toBeVisible();
@@ -130,3 +183,38 @@ test("内容区渲染出错时保留导航,重新加载后恢复", async ({ pa
await expect(page.getByRole("heading", { name: "信任内容" })).toBeVisible();
await expect(page.getByText("页面渲染出错")).toBeHidden();
});
test("响应契约不符时展示可读错误,不进入渲染错误边界", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { clientErrors } = await mockAdminApi(page, { trustContent: [null] });
await page.goto(`${adminOrigin}/admin/trust`);
await expect(page.getByRole("alert")).toContainText("接口返回数据结构不符合契约");
await expect(page.getByRole("alert")).toContainText("/admin/config/trust-content");
await expect(page.getByText("页面渲染出错")).toBeHidden();
assert.equal(clientErrors.length, 0);
});
test("错误上报失败时错误页仍然可用", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { clientErrors } = await mockAdminApi(page, {
clientErrorStatus: 500,
workspaceOnce: {
brand: { id: "brand-current", name: "独立工坊" },
installations: [],
templateContent: { displayName: "独立创作者画册", trustContentTypes: [null] },
offerings: [],
forms: [],
},
});
await page.goto(`${adminOrigin}/admin/trust`);
await expect(page.getByText("页面渲染出错")).toBeVisible();
await expect(page.getByRole("button", { name: "重新加载页面" })).toBeVisible();
await expect.poll(() => clientErrors.length).toBe(1);
// 上报失败不会让错误页递归崩溃,也不会产生未捕获异常
await page.waitForTimeout(300);
await expect(page.getByText("页面渲染出错")).toBeVisible();
});